LLVM API Documentation

ScalarEvolution.cpp
Go to the documentation of this file.
00001 //===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file contains the implementation of the scalar evolution analysis
00011 // engine, which is used primarily to analyze expressions involving induction
00012 // variables in loops.
00013 //
00014 // There are several aspects to this library.  First is the representation of
00015 // scalar expressions, which are represented as subclasses of the SCEV class.
00016 // These classes are used to represent certain types of subexpressions that we
00017 // can handle. We only create one SCEV of a particular shape, so
00018 // pointer-comparisons for equality are legal.
00019 //
00020 // One important aspect of the SCEV objects is that they are never cyclic, even
00021 // if there is a cycle in the dataflow for an expression (ie, a PHI node).  If
00022 // the PHI node is one of the idioms that we can represent (e.g., a polynomial
00023 // recurrence) then we represent it directly as a recurrence node, otherwise we
00024 // represent it as a SCEVUnknown node.
00025 //
00026 // In addition to being able to represent expressions of various types, we also
00027 // have folders that are used to build the *canonical* representation for a
00028 // particular expression.  These folders are capable of using a variety of
00029 // rewrite rules to simplify the expressions.
00030 //
00031 // Once the folders are defined, we can implement the more interesting
00032 // higher-level code, such as the code that recognizes PHI nodes of various
00033 // types, computes the execution count of a loop, etc.
00034 //
00035 // TODO: We should use these routines and value representations to implement
00036 // dependence analysis!
00037 //
00038 //===----------------------------------------------------------------------===//
00039 //
00040 // There are several good references for the techniques used in this analysis.
00041 //
00042 //  Chains of recurrences -- a method to expedite the evaluation
00043 //  of closed-form functions
00044 //  Olaf Bachmann, Paul S. Wang, Eugene V. Zima
00045 //
00046 //  On computational properties of chains of recurrences
00047 //  Eugene V. Zima
00048 //
00049 //  Symbolic Evaluation of Chains of Recurrences for Loop Optimization
00050 //  Robert A. van Engelen
00051 //
00052 //  Efficient Symbolic Analysis for Optimizing Compilers
00053 //  Robert A. van Engelen
00054 //
00055 //  Using the chains of recurrences algebra for data dependence testing and
00056 //  induction variable substitution
00057 //  MS Thesis, Johnie Birch
00058 //
00059 //===----------------------------------------------------------------------===//
00060 
00061 #include "llvm/Analysis/ScalarEvolution.h"
00062 #include "llvm/ADT/STLExtras.h"
00063 #include "llvm/ADT/SmallPtrSet.h"
00064 #include "llvm/ADT/Statistic.h"
00065 #include "llvm/Analysis/ConstantFolding.h"
00066 #include "llvm/Analysis/InstructionSimplify.h"
00067 #include "llvm/Analysis/LoopInfo.h"
00068 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
00069 #include "llvm/Analysis/ValueTracking.h"
00070 #include "llvm/IR/ConstantRange.h"
00071 #include "llvm/IR/Constants.h"
00072 #include "llvm/IR/DataLayout.h"
00073 #include "llvm/IR/DerivedTypes.h"
00074 #include "llvm/IR/Dominators.h"
00075 #include "llvm/IR/GetElementPtrTypeIterator.h"
00076 #include "llvm/IR/GlobalAlias.h"
00077 #include "llvm/IR/GlobalVariable.h"
00078 #include "llvm/IR/InstIterator.h"
00079 #include "llvm/IR/Instructions.h"
00080 #include "llvm/IR/LLVMContext.h"
00081 #include "llvm/IR/Operator.h"
00082 #include "llvm/Support/CommandLine.h"
00083 #include "llvm/Support/Debug.h"
00084 #include "llvm/Support/ErrorHandling.h"
00085 #include "llvm/Support/MathExtras.h"
00086 #include "llvm/Support/raw_ostream.h"
00087 #include "llvm/Target/TargetLibraryInfo.h"
00088 #include <algorithm>
00089 using namespace llvm;
00090 
00091 #define DEBUG_TYPE "scalar-evolution"
00092 
00093 STATISTIC(NumArrayLenItCounts,
00094           "Number of trip counts computed with array length");
00095 STATISTIC(NumTripCountsComputed,
00096           "Number of loops with predictable loop counts");
00097 STATISTIC(NumTripCountsNotComputed,
00098           "Number of loops without predictable loop counts");
00099 STATISTIC(NumBruteForceTripCountsComputed,
00100           "Number of loops with trip counts computed by force");
00101 
00102 static cl::opt<unsigned>
00103 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
00104                         cl::desc("Maximum number of iterations SCEV will "
00105                                  "symbolically execute a constant "
00106                                  "derived loop"),
00107                         cl::init(100));
00108 
00109 // FIXME: Enable this with XDEBUG when the test suite is clean.
00110 static cl::opt<bool>
00111 VerifySCEV("verify-scev",
00112            cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
00113 
00114 INITIALIZE_PASS_BEGIN(ScalarEvolution, "scalar-evolution",
00115                 "Scalar Evolution Analysis", false, true)
00116 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
00117 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
00118 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
00119 INITIALIZE_PASS_END(ScalarEvolution, "scalar-evolution",
00120                 "Scalar Evolution Analysis", false, true)
00121 char ScalarEvolution::ID = 0;
00122 
00123 //===----------------------------------------------------------------------===//
00124 //                           SCEV class definitions
00125 //===----------------------------------------------------------------------===//
00126 
00127 //===----------------------------------------------------------------------===//
00128 // Implementation of the SCEV class.
00129 //
00130 
00131 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
00132 void SCEV::dump() const {
00133   print(dbgs());
00134   dbgs() << '\n';
00135 }
00136 #endif
00137 
00138 void SCEV::print(raw_ostream &OS) const {
00139   switch (static_cast<SCEVTypes>(getSCEVType())) {
00140   case scConstant:
00141     cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
00142     return;
00143   case scTruncate: {
00144     const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
00145     const SCEV *Op = Trunc->getOperand();
00146     OS << "(trunc " << *Op->getType() << " " << *Op << " to "
00147        << *Trunc->getType() << ")";
00148     return;
00149   }
00150   case scZeroExtend: {
00151     const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
00152     const SCEV *Op = ZExt->getOperand();
00153     OS << "(zext " << *Op->getType() << " " << *Op << " to "
00154        << *ZExt->getType() << ")";
00155     return;
00156   }
00157   case scSignExtend: {
00158     const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
00159     const SCEV *Op = SExt->getOperand();
00160     OS << "(sext " << *Op->getType() << " " << *Op << " to "
00161        << *SExt->getType() << ")";
00162     return;
00163   }
00164   case scAddRecExpr: {
00165     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
00166     OS << "{" << *AR->getOperand(0);
00167     for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
00168       OS << ",+," << *AR->getOperand(i);
00169     OS << "}<";
00170     if (AR->getNoWrapFlags(FlagNUW))
00171       OS << "nuw><";
00172     if (AR->getNoWrapFlags(FlagNSW))
00173       OS << "nsw><";
00174     if (AR->getNoWrapFlags(FlagNW) &&
00175         !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
00176       OS << "nw><";
00177     AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
00178     OS << ">";
00179     return;
00180   }
00181   case scAddExpr:
00182   case scMulExpr:
00183   case scUMaxExpr:
00184   case scSMaxExpr: {
00185     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
00186     const char *OpStr = nullptr;
00187     switch (NAry->getSCEVType()) {
00188     case scAddExpr: OpStr = " + "; break;
00189     case scMulExpr: OpStr = " * "; break;
00190     case scUMaxExpr: OpStr = " umax "; break;
00191     case scSMaxExpr: OpStr = " smax "; break;
00192     }
00193     OS << "(";
00194     for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
00195          I != E; ++I) {
00196       OS << **I;
00197       if (std::next(I) != E)
00198         OS << OpStr;
00199     }
00200     OS << ")";
00201     switch (NAry->getSCEVType()) {
00202     case scAddExpr:
00203     case scMulExpr:
00204       if (NAry->getNoWrapFlags(FlagNUW))
00205         OS << "<nuw>";
00206       if (NAry->getNoWrapFlags(FlagNSW))
00207         OS << "<nsw>";
00208     }
00209     return;
00210   }
00211   case scUDivExpr: {
00212     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
00213     OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
00214     return;
00215   }
00216   case scUnknown: {
00217     const SCEVUnknown *U = cast<SCEVUnknown>(this);
00218     Type *AllocTy;
00219     if (U->isSizeOf(AllocTy)) {
00220       OS << "sizeof(" << *AllocTy << ")";
00221       return;
00222     }
00223     if (U->isAlignOf(AllocTy)) {
00224       OS << "alignof(" << *AllocTy << ")";
00225       return;
00226     }
00227 
00228     Type *CTy;
00229     Constant *FieldNo;
00230     if (U->isOffsetOf(CTy, FieldNo)) {
00231       OS << "offsetof(" << *CTy << ", ";
00232       FieldNo->printAsOperand(OS, false);
00233       OS << ")";
00234       return;
00235     }
00236 
00237     // Otherwise just print it normally.
00238     U->getValue()->printAsOperand(OS, false);
00239     return;
00240   }
00241   case scCouldNotCompute:
00242     OS << "***COULDNOTCOMPUTE***";
00243     return;
00244   }
00245   llvm_unreachable("Unknown SCEV kind!");
00246 }
00247 
00248 Type *SCEV::getType() const {
00249   switch (static_cast<SCEVTypes>(getSCEVType())) {
00250   case scConstant:
00251     return cast<SCEVConstant>(this)->getType();
00252   case scTruncate:
00253   case scZeroExtend:
00254   case scSignExtend:
00255     return cast<SCEVCastExpr>(this)->getType();
00256   case scAddRecExpr:
00257   case scMulExpr:
00258   case scUMaxExpr:
00259   case scSMaxExpr:
00260     return cast<SCEVNAryExpr>(this)->getType();
00261   case scAddExpr:
00262     return cast<SCEVAddExpr>(this)->getType();
00263   case scUDivExpr:
00264     return cast<SCEVUDivExpr>(this)->getType();
00265   case scUnknown:
00266     return cast<SCEVUnknown>(this)->getType();
00267   case scCouldNotCompute:
00268     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
00269   }
00270   llvm_unreachable("Unknown SCEV kind!");
00271 }
00272 
00273 bool SCEV::isZero() const {
00274   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
00275     return SC->getValue()->isZero();
00276   return false;
00277 }
00278 
00279 bool SCEV::isOne() const {
00280   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
00281     return SC->getValue()->isOne();
00282   return false;
00283 }
00284 
00285 bool SCEV::isAllOnesValue() const {
00286   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
00287     return SC->getValue()->isAllOnesValue();
00288   return false;
00289 }
00290 
00291 /// isNonConstantNegative - Return true if the specified scev is negated, but
00292 /// not a constant.
00293 bool SCEV::isNonConstantNegative() const {
00294   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
00295   if (!Mul) return false;
00296 
00297   // If there is a constant factor, it will be first.
00298   const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
00299   if (!SC) return false;
00300 
00301   // Return true if the value is negative, this matches things like (-42 * V).
00302   return SC->getValue()->getValue().isNegative();
00303 }
00304 
00305 SCEVCouldNotCompute::SCEVCouldNotCompute() :
00306   SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {}
00307 
00308 bool SCEVCouldNotCompute::classof(const SCEV *S) {
00309   return S->getSCEVType() == scCouldNotCompute;
00310 }
00311 
00312 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
00313   FoldingSetNodeID ID;
00314   ID.AddInteger(scConstant);
00315   ID.AddPointer(V);
00316   void *IP = nullptr;
00317   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
00318   SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
00319   UniqueSCEVs.InsertNode(S, IP);
00320   return S;
00321 }
00322 
00323 const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
00324   return getConstant(ConstantInt::get(getContext(), Val));
00325 }
00326 
00327 const SCEV *
00328 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
00329   IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
00330   return getConstant(ConstantInt::get(ITy, V, isSigned));
00331 }
00332 
00333 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
00334                            unsigned SCEVTy, const SCEV *op, Type *ty)
00335   : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
00336 
00337 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
00338                                    const SCEV *op, Type *ty)
00339   : SCEVCastExpr(ID, scTruncate, op, ty) {
00340   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
00341          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
00342          "Cannot truncate non-integer value!");
00343 }
00344 
00345 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
00346                                        const SCEV *op, Type *ty)
00347   : SCEVCastExpr(ID, scZeroExtend, op, ty) {
00348   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
00349          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
00350          "Cannot zero extend non-integer value!");
00351 }
00352 
00353 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
00354                                        const SCEV *op, Type *ty)
00355   : SCEVCastExpr(ID, scSignExtend, op, ty) {
00356   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
00357          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
00358          "Cannot sign extend non-integer value!");
00359 }
00360 
00361 void SCEVUnknown::deleted() {
00362   // Clear this SCEVUnknown from various maps.
00363   SE->forgetMemoizedResults(this);
00364 
00365   // Remove this SCEVUnknown from the uniquing map.
00366   SE->UniqueSCEVs.RemoveNode(this);
00367 
00368   // Release the value.
00369   setValPtr(nullptr);
00370 }
00371 
00372 void SCEVUnknown::allUsesReplacedWith(Value *New) {
00373   // Clear this SCEVUnknown from various maps.
00374   SE->forgetMemoizedResults(this);
00375 
00376   // Remove this SCEVUnknown from the uniquing map.
00377   SE->UniqueSCEVs.RemoveNode(this);
00378 
00379   // Update this SCEVUnknown to point to the new value. This is needed
00380   // because there may still be outstanding SCEVs which still point to
00381   // this SCEVUnknown.
00382   setValPtr(New);
00383 }
00384 
00385 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
00386   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
00387     if (VCE->getOpcode() == Instruction::PtrToInt)
00388       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
00389         if (CE->getOpcode() == Instruction::GetElementPtr &&
00390             CE->getOperand(0)->isNullValue() &&
00391             CE->getNumOperands() == 2)
00392           if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
00393             if (CI->isOne()) {
00394               AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
00395                                  ->getElementType();
00396               return true;
00397             }
00398 
00399   return false;
00400 }
00401 
00402 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
00403   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
00404     if (VCE->getOpcode() == Instruction::PtrToInt)
00405       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
00406         if (CE->getOpcode() == Instruction::GetElementPtr &&
00407             CE->getOperand(0)->isNullValue()) {
00408           Type *Ty =
00409             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
00410           if (StructType *STy = dyn_cast<StructType>(Ty))
00411             if (!STy->isPacked() &&
00412                 CE->getNumOperands() == 3 &&
00413                 CE->getOperand(1)->isNullValue()) {
00414               if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
00415                 if (CI->isOne() &&
00416                     STy->getNumElements() == 2 &&
00417                     STy->getElementType(0)->isIntegerTy(1)) {
00418                   AllocTy = STy->getElementType(1);
00419                   return true;
00420                 }
00421             }
00422         }
00423 
00424   return false;
00425 }
00426 
00427 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
00428   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
00429     if (VCE->getOpcode() == Instruction::PtrToInt)
00430       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
00431         if (CE->getOpcode() == Instruction::GetElementPtr &&
00432             CE->getNumOperands() == 3 &&
00433             CE->getOperand(0)->isNullValue() &&
00434             CE->getOperand(1)->isNullValue()) {
00435           Type *Ty =
00436             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
00437           // Ignore vector types here so that ScalarEvolutionExpander doesn't
00438           // emit getelementptrs that index into vectors.
00439           if (Ty->isStructTy() || Ty->isArrayTy()) {
00440             CTy = Ty;
00441             FieldNo = CE->getOperand(2);
00442             return true;
00443           }
00444         }
00445 
00446   return false;
00447 }
00448 
00449 //===----------------------------------------------------------------------===//
00450 //                               SCEV Utilities
00451 //===----------------------------------------------------------------------===//
00452 
00453 namespace {
00454   /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
00455   /// than the complexity of the RHS.  This comparator is used to canonicalize
00456   /// expressions.
00457   class SCEVComplexityCompare {
00458     const LoopInfo *const LI;
00459   public:
00460     explicit SCEVComplexityCompare(const LoopInfo *li) : LI(li) {}
00461 
00462     // Return true or false if LHS is less than, or at least RHS, respectively.
00463     bool operator()(const SCEV *LHS, const SCEV *RHS) const {
00464       return compare(LHS, RHS) < 0;
00465     }
00466 
00467     // Return negative, zero, or positive, if LHS is less than, equal to, or
00468     // greater than RHS, respectively. A three-way result allows recursive
00469     // comparisons to be more efficient.
00470     int compare(const SCEV *LHS, const SCEV *RHS) const {
00471       // Fast-path: SCEVs are uniqued so we can do a quick equality check.
00472       if (LHS == RHS)
00473         return 0;
00474 
00475       // Primarily, sort the SCEVs by their getSCEVType().
00476       unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
00477       if (LType != RType)
00478         return (int)LType - (int)RType;
00479 
00480       // Aside from the getSCEVType() ordering, the particular ordering
00481       // isn't very important except that it's beneficial to be consistent,
00482       // so that (a + b) and (b + a) don't end up as different expressions.
00483       switch (static_cast<SCEVTypes>(LType)) {
00484       case scUnknown: {
00485         const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
00486         const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
00487 
00488         // Sort SCEVUnknown values with some loose heuristics. TODO: This is
00489         // not as complete as it could be.
00490         const Value *LV = LU->getValue(), *RV = RU->getValue();
00491 
00492         // Order pointer values after integer values. This helps SCEVExpander
00493         // form GEPs.
00494         bool LIsPointer = LV->getType()->isPointerTy(),
00495              RIsPointer = RV->getType()->isPointerTy();
00496         if (LIsPointer != RIsPointer)
00497           return (int)LIsPointer - (int)RIsPointer;
00498 
00499         // Compare getValueID values.
00500         unsigned LID = LV->getValueID(),
00501                  RID = RV->getValueID();
00502         if (LID != RID)
00503           return (int)LID - (int)RID;
00504 
00505         // Sort arguments by their position.
00506         if (const Argument *LA = dyn_cast<Argument>(LV)) {
00507           const Argument *RA = cast<Argument>(RV);
00508           unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
00509           return (int)LArgNo - (int)RArgNo;
00510         }
00511 
00512         // For instructions, compare their loop depth, and their operand
00513         // count.  This is pretty loose.
00514         if (const Instruction *LInst = dyn_cast<Instruction>(LV)) {
00515           const Instruction *RInst = cast<Instruction>(RV);
00516 
00517           // Compare loop depths.
00518           const BasicBlock *LParent = LInst->getParent(),
00519                            *RParent = RInst->getParent();
00520           if (LParent != RParent) {
00521             unsigned LDepth = LI->getLoopDepth(LParent),
00522                      RDepth = LI->getLoopDepth(RParent);
00523             if (LDepth != RDepth)
00524               return (int)LDepth - (int)RDepth;
00525           }
00526 
00527           // Compare the number of operands.
00528           unsigned LNumOps = LInst->getNumOperands(),
00529                    RNumOps = RInst->getNumOperands();
00530           return (int)LNumOps - (int)RNumOps;
00531         }
00532 
00533         return 0;
00534       }
00535 
00536       case scConstant: {
00537         const SCEVConstant *LC = cast<SCEVConstant>(LHS);
00538         const SCEVConstant *RC = cast<SCEVConstant>(RHS);
00539 
00540         // Compare constant values.
00541         const APInt &LA = LC->getValue()->getValue();
00542         const APInt &RA = RC->getValue()->getValue();
00543         unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
00544         if (LBitWidth != RBitWidth)
00545           return (int)LBitWidth - (int)RBitWidth;
00546         return LA.ult(RA) ? -1 : 1;
00547       }
00548 
00549       case scAddRecExpr: {
00550         const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
00551         const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
00552 
00553         // Compare addrec loop depths.
00554         const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
00555         if (LLoop != RLoop) {
00556           unsigned LDepth = LLoop->getLoopDepth(),
00557                    RDepth = RLoop->getLoopDepth();
00558           if (LDepth != RDepth)
00559             return (int)LDepth - (int)RDepth;
00560         }
00561 
00562         // Addrec complexity grows with operand count.
00563         unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
00564         if (LNumOps != RNumOps)
00565           return (int)LNumOps - (int)RNumOps;
00566 
00567         // Lexicographically compare.
00568         for (unsigned i = 0; i != LNumOps; ++i) {
00569           long X = compare(LA->getOperand(i), RA->getOperand(i));
00570           if (X != 0)
00571             return X;
00572         }
00573 
00574         return 0;
00575       }
00576 
00577       case scAddExpr:
00578       case scMulExpr:
00579       case scSMaxExpr:
00580       case scUMaxExpr: {
00581         const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
00582         const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
00583 
00584         // Lexicographically compare n-ary expressions.
00585         unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
00586         if (LNumOps != RNumOps)
00587           return (int)LNumOps - (int)RNumOps;
00588 
00589         for (unsigned i = 0; i != LNumOps; ++i) {
00590           if (i >= RNumOps)
00591             return 1;
00592           long X = compare(LC->getOperand(i), RC->getOperand(i));
00593           if (X != 0)
00594             return X;
00595         }
00596         return (int)LNumOps - (int)RNumOps;
00597       }
00598 
00599       case scUDivExpr: {
00600         const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
00601         const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
00602 
00603         // Lexicographically compare udiv expressions.
00604         long X = compare(LC->getLHS(), RC->getLHS());
00605         if (X != 0)
00606           return X;
00607         return compare(LC->getRHS(), RC->getRHS());
00608       }
00609 
00610       case scTruncate:
00611       case scZeroExtend:
00612       case scSignExtend: {
00613         const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
00614         const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
00615 
00616         // Compare cast expressions by operand.
00617         return compare(LC->getOperand(), RC->getOperand());
00618       }
00619 
00620       case scCouldNotCompute:
00621         llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
00622       }
00623       llvm_unreachable("Unknown SCEV kind!");
00624     }
00625   };
00626 }
00627 
00628 /// GroupByComplexity - Given a list of SCEV objects, order them by their
00629 /// complexity, and group objects of the same complexity together by value.
00630 /// When this routine is finished, we know that any duplicates in the vector are
00631 /// consecutive and that complexity is monotonically increasing.
00632 ///
00633 /// Note that we go take special precautions to ensure that we get deterministic
00634 /// results from this routine.  In other words, we don't want the results of
00635 /// this to depend on where the addresses of various SCEV objects happened to
00636 /// land in memory.
00637 ///
00638 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
00639                               LoopInfo *LI) {
00640   if (Ops.size() < 2) return;  // Noop
00641   if (Ops.size() == 2) {
00642     // This is the common case, which also happens to be trivially simple.
00643     // Special case it.
00644     const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
00645     if (SCEVComplexityCompare(LI)(RHS, LHS))
00646       std::swap(LHS, RHS);
00647     return;
00648   }
00649 
00650   // Do the rough sort by complexity.
00651   std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
00652 
00653   // Now that we are sorted by complexity, group elements of the same
00654   // complexity.  Note that this is, at worst, N^2, but the vector is likely to
00655   // be extremely short in practice.  Note that we take this approach because we
00656   // do not want to depend on the addresses of the objects we are grouping.
00657   for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
00658     const SCEV *S = Ops[i];
00659     unsigned Complexity = S->getSCEVType();
00660 
00661     // If there are any objects of the same complexity and same value as this
00662     // one, group them.
00663     for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
00664       if (Ops[j] == S) { // Found a duplicate.
00665         // Move it to immediately after i'th element.
00666         std::swap(Ops[i+1], Ops[j]);
00667         ++i;   // no need to rescan it.
00668         if (i == e-2) return;  // Done!
00669       }
00670     }
00671   }
00672 }
00673 
00674 
00675 
00676 //===----------------------------------------------------------------------===//
00677 //                      Simple SCEV method implementations
00678 //===----------------------------------------------------------------------===//
00679 
00680 /// BinomialCoefficient - Compute BC(It, K).  The result has width W.
00681 /// Assume, K > 0.
00682 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
00683                                        ScalarEvolution &SE,
00684                                        Type *ResultTy) {
00685   // Handle the simplest case efficiently.
00686   if (K == 1)
00687     return SE.getTruncateOrZeroExtend(It, ResultTy);
00688 
00689   // We are using the following formula for BC(It, K):
00690   //
00691   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
00692   //
00693   // Suppose, W is the bitwidth of the return value.  We must be prepared for
00694   // overflow.  Hence, we must assure that the result of our computation is
00695   // equal to the accurate one modulo 2^W.  Unfortunately, division isn't
00696   // safe in modular arithmetic.
00697   //
00698   // However, this code doesn't use exactly that formula; the formula it uses
00699   // is something like the following, where T is the number of factors of 2 in
00700   // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
00701   // exponentiation:
00702   //
00703   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
00704   //
00705   // This formula is trivially equivalent to the previous formula.  However,
00706   // this formula can be implemented much more efficiently.  The trick is that
00707   // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
00708   // arithmetic.  To do exact division in modular arithmetic, all we have
00709   // to do is multiply by the inverse.  Therefore, this step can be done at
00710   // width W.
00711   //
00712   // The next issue is how to safely do the division by 2^T.  The way this
00713   // is done is by doing the multiplication step at a width of at least W + T
00714   // bits.  This way, the bottom W+T bits of the product are accurate. Then,
00715   // when we perform the division by 2^T (which is equivalent to a right shift
00716   // by T), the bottom W bits are accurate.  Extra bits are okay; they'll get
00717   // truncated out after the division by 2^T.
00718   //
00719   // In comparison to just directly using the first formula, this technique
00720   // is much more efficient; using the first formula requires W * K bits,
00721   // but this formula less than W + K bits. Also, the first formula requires
00722   // a division step, whereas this formula only requires multiplies and shifts.
00723   //
00724   // It doesn't matter whether the subtraction step is done in the calculation
00725   // width or the input iteration count's width; if the subtraction overflows,
00726   // the result must be zero anyway.  We prefer here to do it in the width of
00727   // the induction variable because it helps a lot for certain cases; CodeGen
00728   // isn't smart enough to ignore the overflow, which leads to much less
00729   // efficient code if the width of the subtraction is wider than the native
00730   // register width.
00731   //
00732   // (It's possible to not widen at all by pulling out factors of 2 before
00733   // the multiplication; for example, K=2 can be calculated as
00734   // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
00735   // extra arithmetic, so it's not an obvious win, and it gets
00736   // much more complicated for K > 3.)
00737 
00738   // Protection from insane SCEVs; this bound is conservative,
00739   // but it probably doesn't matter.
00740   if (K > 1000)
00741     return SE.getCouldNotCompute();
00742 
00743   unsigned W = SE.getTypeSizeInBits(ResultTy);
00744 
00745   // Calculate K! / 2^T and T; we divide out the factors of two before
00746   // multiplying for calculating K! / 2^T to avoid overflow.
00747   // Other overflow doesn't matter because we only care about the bottom
00748   // W bits of the result.
00749   APInt OddFactorial(W, 1);
00750   unsigned T = 1;
00751   for (unsigned i = 3; i <= K; ++i) {
00752     APInt Mult(W, i);
00753     unsigned TwoFactors = Mult.countTrailingZeros();
00754     T += TwoFactors;
00755     Mult = Mult.lshr(TwoFactors);
00756     OddFactorial *= Mult;
00757   }
00758 
00759   // We need at least W + T bits for the multiplication step
00760   unsigned CalculationBits = W + T;
00761 
00762   // Calculate 2^T, at width T+W.
00763   APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
00764 
00765   // Calculate the multiplicative inverse of K! / 2^T;
00766   // this multiplication factor will perform the exact division by
00767   // K! / 2^T.
00768   APInt Mod = APInt::getSignedMinValue(W+1);
00769   APInt MultiplyFactor = OddFactorial.zext(W+1);
00770   MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
00771   MultiplyFactor = MultiplyFactor.trunc(W);
00772 
00773   // Calculate the product, at width T+W
00774   IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
00775                                                       CalculationBits);
00776   const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
00777   for (unsigned i = 1; i != K; ++i) {
00778     const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
00779     Dividend = SE.getMulExpr(Dividend,
00780                              SE.getTruncateOrZeroExtend(S, CalculationTy));
00781   }
00782 
00783   // Divide by 2^T
00784   const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
00785 
00786   // Truncate the result, and divide by K! / 2^T.
00787 
00788   return SE.getMulExpr(SE.getConstant(MultiplyFactor),
00789                        SE.getTruncateOrZeroExtend(DivResult, ResultTy));
00790 }
00791 
00792 /// evaluateAtIteration - Return the value of this chain of recurrences at
00793 /// the specified iteration number.  We can evaluate this recurrence by
00794 /// multiplying each element in the chain by the binomial coefficient
00795 /// corresponding to it.  In other words, we can evaluate {A,+,B,+,C,+,D} as:
00796 ///
00797 ///   A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
00798 ///
00799 /// where BC(It, k) stands for binomial coefficient.
00800 ///
00801 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
00802                                                 ScalarEvolution &SE) const {
00803   const SCEV *Result = getStart();
00804   for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
00805     // The computation is correct in the face of overflow provided that the
00806     // multiplication is performed _after_ the evaluation of the binomial
00807     // coefficient.
00808     const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
00809     if (isa<SCEVCouldNotCompute>(Coeff))
00810       return Coeff;
00811 
00812     Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
00813   }
00814   return Result;
00815 }
00816 
00817 //===----------------------------------------------------------------------===//
00818 //                    SCEV Expression folder implementations
00819 //===----------------------------------------------------------------------===//
00820 
00821 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
00822                                              Type *Ty) {
00823   assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
00824          "This is not a truncating conversion!");
00825   assert(isSCEVable(Ty) &&
00826          "This is not a conversion to a SCEVable type!");
00827   Ty = getEffectiveSCEVType(Ty);
00828 
00829   FoldingSetNodeID ID;
00830   ID.AddInteger(scTruncate);
00831   ID.AddPointer(Op);
00832   ID.AddPointer(Ty);
00833   void *IP = nullptr;
00834   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
00835 
00836   // Fold if the operand is constant.
00837   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
00838     return getConstant(
00839       cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
00840 
00841   // trunc(trunc(x)) --> trunc(x)
00842   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
00843     return getTruncateExpr(ST->getOperand(), Ty);
00844 
00845   // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
00846   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
00847     return getTruncateOrSignExtend(SS->getOperand(), Ty);
00848 
00849   // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
00850   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
00851     return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
00852 
00853   // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can
00854   // eliminate all the truncates.
00855   if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) {
00856     SmallVector<const SCEV *, 4> Operands;
00857     bool hasTrunc = false;
00858     for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) {
00859       const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty);
00860       hasTrunc = isa<SCEVTruncateExpr>(S);
00861       Operands.push_back(S);
00862     }
00863     if (!hasTrunc)
00864       return getAddExpr(Operands);
00865     UniqueSCEVs.FindNodeOrInsertPos(ID, IP);  // Mutates IP, returns NULL.
00866   }
00867 
00868   // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can
00869   // eliminate all the truncates.
00870   if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) {
00871     SmallVector<const SCEV *, 4> Operands;
00872     bool hasTrunc = false;
00873     for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) {
00874       const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty);
00875       hasTrunc = isa<SCEVTruncateExpr>(S);
00876       Operands.push_back(S);
00877     }
00878     if (!hasTrunc)
00879       return getMulExpr(Operands);
00880     UniqueSCEVs.FindNodeOrInsertPos(ID, IP);  // Mutates IP, returns NULL.
00881   }
00882 
00883   // If the input value is a chrec scev, truncate the chrec's operands.
00884   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
00885     SmallVector<const SCEV *, 4> Operands;
00886     for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
00887       Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
00888     return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
00889   }
00890 
00891   // The cast wasn't folded; create an explicit cast node. We can reuse
00892   // the existing insert position since if we get here, we won't have
00893   // made any changes which would invalidate it.
00894   SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
00895                                                  Op, Ty);
00896   UniqueSCEVs.InsertNode(S, IP);
00897   return S;
00898 }
00899 
00900 const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
00901                                                Type *Ty) {
00902   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
00903          "This is not an extending conversion!");
00904   assert(isSCEVable(Ty) &&
00905          "This is not a conversion to a SCEVable type!");
00906   Ty = getEffectiveSCEVType(Ty);
00907 
00908   // Fold if the operand is constant.
00909   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
00910     return getConstant(
00911       cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
00912 
00913   // zext(zext(x)) --> zext(x)
00914   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
00915     return getZeroExtendExpr(SZ->getOperand(), Ty);
00916 
00917   // Before doing any expensive analysis, check to see if we've already
00918   // computed a SCEV for this Op and Ty.
00919   FoldingSetNodeID ID;
00920   ID.AddInteger(scZeroExtend);
00921   ID.AddPointer(Op);
00922   ID.AddPointer(Ty);
00923   void *IP = nullptr;
00924   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
00925 
00926   // zext(trunc(x)) --> zext(x) or x or trunc(x)
00927   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
00928     // It's possible the bits taken off by the truncate were all zero bits. If
00929     // so, we should be able to simplify this further.
00930     const SCEV *X = ST->getOperand();
00931     ConstantRange CR = getUnsignedRange(X);
00932     unsigned TruncBits = getTypeSizeInBits(ST->getType());
00933     unsigned NewBits = getTypeSizeInBits(Ty);
00934     if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
00935             CR.zextOrTrunc(NewBits)))
00936       return getTruncateOrZeroExtend(X, Ty);
00937   }
00938 
00939   // If the input value is a chrec scev, and we can prove that the value
00940   // did not overflow the old, smaller, value, we can zero extend all of the
00941   // operands (often constants).  This allows analysis of something like
00942   // this:  for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
00943   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
00944     if (AR->isAffine()) {
00945       const SCEV *Start = AR->getStart();
00946       const SCEV *Step = AR->getStepRecurrence(*this);
00947       unsigned BitWidth = getTypeSizeInBits(AR->getType());
00948       const Loop *L = AR->getLoop();
00949 
00950       // If we have special knowledge that this addrec won't overflow,
00951       // we don't need to do any further analysis.
00952       if (AR->getNoWrapFlags(SCEV::FlagNUW))
00953         return getAddRecExpr(getZeroExtendExpr(Start, Ty),
00954                              getZeroExtendExpr(Step, Ty),
00955                              L, AR->getNoWrapFlags());
00956 
00957       // Check whether the backedge-taken count is SCEVCouldNotCompute.
00958       // Note that this serves two purposes: It filters out loops that are
00959       // simply not analyzable, and it covers the case where this code is
00960       // being called from within backedge-taken count analysis, such that
00961       // attempting to ask for the backedge-taken count would likely result
00962       // in infinite recursion. In the later case, the analysis code will
00963       // cope with a conservative value, and it will take care to purge
00964       // that value once it has finished.
00965       const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
00966       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
00967         // Manually compute the final value for AR, checking for
00968         // overflow.
00969 
00970         // Check whether the backedge-taken count can be losslessly casted to
00971         // the addrec's type. The count is always unsigned.
00972         const SCEV *CastedMaxBECount =
00973           getTruncateOrZeroExtend(MaxBECount, Start->getType());
00974         const SCEV *RecastedMaxBECount =
00975           getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
00976         if (MaxBECount == RecastedMaxBECount) {
00977           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
00978           // Check whether Start+Step*MaxBECount has no unsigned overflow.
00979           const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step);
00980           const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul), WideTy);
00981           const SCEV *WideStart = getZeroExtendExpr(Start, WideTy);
00982           const SCEV *WideMaxBECount =
00983             getZeroExtendExpr(CastedMaxBECount, WideTy);
00984           const SCEV *OperandExtendedAdd =
00985             getAddExpr(WideStart,
00986                        getMulExpr(WideMaxBECount,
00987                                   getZeroExtendExpr(Step, WideTy)));
00988           if (ZAdd == OperandExtendedAdd) {
00989             // Cache knowledge of AR NUW, which is propagated to this AddRec.
00990             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
00991             // Return the expression with the addrec on the outside.
00992             return getAddRecExpr(getZeroExtendExpr(Start, Ty),
00993                                  getZeroExtendExpr(Step, Ty),
00994                                  L, AR->getNoWrapFlags());
00995           }
00996           // Similar to above, only this time treat the step value as signed.
00997           // This covers loops that count down.
00998           OperandExtendedAdd =
00999             getAddExpr(WideStart,
01000                        getMulExpr(WideMaxBECount,
01001                                   getSignExtendExpr(Step, WideTy)));
01002           if (ZAdd == OperandExtendedAdd) {
01003             // Cache knowledge of AR NW, which is propagated to this AddRec.
01004             // Negative step causes unsigned wrap, but it still can't self-wrap.
01005             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
01006             // Return the expression with the addrec on the outside.
01007             return getAddRecExpr(getZeroExtendExpr(Start, Ty),
01008                                  getSignExtendExpr(Step, Ty),
01009                                  L, AR->getNoWrapFlags());
01010           }
01011         }
01012 
01013         // If the backedge is guarded by a comparison with the pre-inc value
01014         // the addrec is safe. Also, if the entry is guarded by a comparison
01015         // with the start value and the backedge is guarded by a comparison
01016         // with the post-inc value, the addrec is safe.
01017         if (isKnownPositive(Step)) {
01018           const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
01019                                       getUnsignedRange(Step).getUnsignedMax());
01020           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
01021               (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
01022                isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
01023                                            AR->getPostIncExpr(*this), N))) {
01024             // Cache knowledge of AR NUW, which is propagated to this AddRec.
01025             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
01026             // Return the expression with the addrec on the outside.
01027             return getAddRecExpr(getZeroExtendExpr(Start, Ty),
01028                                  getZeroExtendExpr(Step, Ty),
01029                                  L, AR->getNoWrapFlags());
01030           }
01031         } else if (isKnownNegative(Step)) {
01032           const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
01033                                       getSignedRange(Step).getSignedMin());
01034           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
01035               (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) &&
01036                isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
01037                                            AR->getPostIncExpr(*this), N))) {
01038             // Cache knowledge of AR NW, which is propagated to this AddRec.
01039             // Negative step causes unsigned wrap, but it still can't self-wrap.
01040             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
01041             // Return the expression with the addrec on the outside.
01042             return getAddRecExpr(getZeroExtendExpr(Start, Ty),
01043                                  getSignExtendExpr(Step, Ty),
01044                                  L, AR->getNoWrapFlags());
01045           }
01046         }
01047       }
01048     }
01049 
01050   // The cast wasn't folded; create an explicit cast node.
01051   // Recompute the insert position, as it may have been invalidated.
01052   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
01053   SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
01054                                                    Op, Ty);
01055   UniqueSCEVs.InsertNode(S, IP);
01056   return S;
01057 }
01058 
01059 // Get the limit of a recurrence such that incrementing by Step cannot cause
01060 // signed overflow as long as the value of the recurrence within the loop does
01061 // not exceed this limit before incrementing.
01062 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
01063                                            ICmpInst::Predicate *Pred,
01064                                            ScalarEvolution *SE) {
01065   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
01066   if (SE->isKnownPositive(Step)) {
01067     *Pred = ICmpInst::ICMP_SLT;
01068     return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
01069                            SE->getSignedRange(Step).getSignedMax());
01070   }
01071   if (SE->isKnownNegative(Step)) {
01072     *Pred = ICmpInst::ICMP_SGT;
01073     return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
01074                        SE->getSignedRange(Step).getSignedMin());
01075   }
01076   return nullptr;
01077 }
01078 
01079 // The recurrence AR has been shown to have no signed wrap. Typically, if we can
01080 // prove NSW for AR, then we can just as easily prove NSW for its preincrement
01081 // or postincrement sibling. This allows normalizing a sign extended AddRec as
01082 // such: {sext(Step + Start),+,Step} => {(Step + sext(Start),+,Step} As a
01083 // result, the expression "Step + sext(PreIncAR)" is congruent with
01084 // "sext(PostIncAR)"
01085 static const SCEV *getPreStartForSignExtend(const SCEVAddRecExpr *AR,
01086                                             Type *Ty,
01087                                             ScalarEvolution *SE) {
01088   const Loop *L = AR->getLoop();
01089   const SCEV *Start = AR->getStart();
01090   const SCEV *Step = AR->getStepRecurrence(*SE);
01091 
01092   // Check for a simple looking step prior to loop entry.
01093   const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
01094   if (!SA)
01095     return nullptr;
01096 
01097   // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
01098   // subtraction is expensive. For this purpose, perform a quick and dirty
01099   // difference, by checking for Step in the operand list.
01100   SmallVector<const SCEV *, 4> DiffOps;
01101   for (const SCEV *Op : SA->operands())
01102     if (Op != Step)
01103       DiffOps.push_back(Op);
01104 
01105   if (DiffOps.size() == SA->getNumOperands())
01106     return nullptr;
01107 
01108   // This is a postinc AR. Check for overflow on the preinc recurrence using the
01109   // same three conditions that getSignExtendedExpr checks.
01110 
01111   // 1. NSW flags on the step increment.
01112   const SCEV *PreStart = SE->getAddExpr(DiffOps, SA->getNoWrapFlags());
01113   const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
01114     SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
01115 
01116   if (PreAR && PreAR->getNoWrapFlags(SCEV::FlagNSW))
01117     return PreStart;
01118 
01119   // 2. Direct overflow check on the step operation's expression.
01120   unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
01121   Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
01122   const SCEV *OperandExtendedStart =
01123     SE->getAddExpr(SE->getSignExtendExpr(PreStart, WideTy),
01124                    SE->getSignExtendExpr(Step, WideTy));
01125   if (SE->getSignExtendExpr(Start, WideTy) == OperandExtendedStart) {
01126     // Cache knowledge of PreAR NSW.
01127     if (PreAR)
01128       const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(SCEV::FlagNSW);
01129     // FIXME: this optimization needs a unit test
01130     DEBUG(dbgs() << "SCEV: untested prestart overflow check\n");
01131     return PreStart;
01132   }
01133 
01134   // 3. Loop precondition.
01135   ICmpInst::Predicate Pred;
01136   const SCEV *OverflowLimit = getOverflowLimitForStep(Step, &Pred, SE);
01137 
01138   if (OverflowLimit &&
01139       SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) {
01140     return PreStart;
01141   }
01142   return nullptr;
01143 }
01144 
01145 // Get the normalized sign-extended expression for this AddRec's Start.
01146 static const SCEV *getSignExtendAddRecStart(const SCEVAddRecExpr *AR,
01147                                             Type *Ty,
01148                                             ScalarEvolution *SE) {
01149   const SCEV *PreStart = getPreStartForSignExtend(AR, Ty, SE);
01150   if (!PreStart)
01151     return SE->getSignExtendExpr(AR->getStart(), Ty);
01152 
01153   return SE->getAddExpr(SE->getSignExtendExpr(AR->getStepRecurrence(*SE), Ty),
01154                         SE->getSignExtendExpr(PreStart, Ty));
01155 }
01156 
01157 const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
01158                                                Type *Ty) {
01159   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
01160          "This is not an extending conversion!");
01161   assert(isSCEVable(Ty) &&
01162          "This is not a conversion to a SCEVable type!");
01163   Ty = getEffectiveSCEVType(Ty);
01164 
01165   // Fold if the operand is constant.
01166   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
01167     return getConstant(
01168       cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
01169 
01170   // sext(sext(x)) --> sext(x)
01171   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
01172     return getSignExtendExpr(SS->getOperand(), Ty);
01173 
01174   // sext(zext(x)) --> zext(x)
01175   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
01176     return getZeroExtendExpr(SZ->getOperand(), Ty);
01177 
01178   // Before doing any expensive analysis, check to see if we've already
01179   // computed a SCEV for this Op and Ty.
01180   FoldingSetNodeID ID;
01181   ID.AddInteger(scSignExtend);
01182   ID.AddPointer(Op);
01183   ID.AddPointer(Ty);
01184   void *IP = nullptr;
01185   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
01186 
01187   // If the input value is provably positive, build a zext instead.
01188   if (isKnownNonNegative(Op))
01189     return getZeroExtendExpr(Op, Ty);
01190 
01191   // sext(trunc(x)) --> sext(x) or x or trunc(x)
01192   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
01193     // It's possible the bits taken off by the truncate were all sign bits. If
01194     // so, we should be able to simplify this further.
01195     const SCEV *X = ST->getOperand();
01196     ConstantRange CR = getSignedRange(X);
01197     unsigned TruncBits = getTypeSizeInBits(ST->getType());
01198     unsigned NewBits = getTypeSizeInBits(Ty);
01199     if (CR.truncate(TruncBits).signExtend(NewBits).contains(
01200             CR.sextOrTrunc(NewBits)))
01201       return getTruncateOrSignExtend(X, Ty);
01202   }
01203 
01204   // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2
01205   if (auto SA = dyn_cast<SCEVAddExpr>(Op)) {
01206     if (SA->getNumOperands() == 2) {
01207       auto SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0));
01208       auto SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1));
01209       if (SMul && SC1) {
01210         if (auto SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) {
01211           const APInt &C1 = SC1->getValue()->getValue();
01212           const APInt &C2 = SC2->getValue()->getValue();
01213           if (C1.isStrictlyPositive() && C2.isStrictlyPositive() &&
01214               C2.ugt(C1) && C2.isPowerOf2())
01215             return getAddExpr(getSignExtendExpr(SC1, Ty),
01216                               getSignExtendExpr(SMul, Ty));
01217         }
01218       }
01219     }
01220   }
01221   // If the input value is a chrec scev, and we can prove that the value
01222   // did not overflow the old, smaller, value, we can sign extend all of the
01223   // operands (often constants).  This allows analysis of something like
01224   // this:  for (signed char X = 0; X < 100; ++X) { int Y = X; }
01225   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
01226     if (AR->isAffine()) {
01227       const SCEV *Start = AR->getStart();
01228       const SCEV *Step = AR->getStepRecurrence(*this);
01229       unsigned BitWidth = getTypeSizeInBits(AR->getType());
01230       const Loop *L = AR->getLoop();
01231 
01232       // If we have special knowledge that this addrec won't overflow,
01233       // we don't need to do any further analysis.
01234       if (AR->getNoWrapFlags(SCEV::FlagNSW))
01235         return getAddRecExpr(getSignExtendAddRecStart(AR, Ty, this),
01236                              getSignExtendExpr(Step, Ty),
01237                              L, SCEV::FlagNSW);
01238 
01239       // Check whether the backedge-taken count is SCEVCouldNotCompute.
01240       // Note that this serves two purposes: It filters out loops that are
01241       // simply not analyzable, and it covers the case where this code is
01242       // being called from within backedge-taken count analysis, such that
01243       // attempting to ask for the backedge-taken count would likely result
01244       // in infinite recursion. In the later case, the analysis code will
01245       // cope with a conservative value, and it will take care to purge
01246       // that value once it has finished.
01247       const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
01248       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
01249         // Manually compute the final value for AR, checking for
01250         // overflow.
01251 
01252         // Check whether the backedge-taken count can be losslessly casted to
01253         // the addrec's type. The count is always unsigned.
01254         const SCEV *CastedMaxBECount =
01255           getTruncateOrZeroExtend(MaxBECount, Start->getType());
01256         const SCEV *RecastedMaxBECount =
01257           getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
01258         if (MaxBECount == RecastedMaxBECount) {
01259           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
01260           // Check whether Start+Step*MaxBECount has no signed overflow.
01261           const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
01262           const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul), WideTy);
01263           const SCEV *WideStart = getSignExtendExpr(Start, WideTy);
01264           const SCEV *WideMaxBECount =
01265             getZeroExtendExpr(CastedMaxBECount, WideTy);
01266           const SCEV *OperandExtendedAdd =
01267             getAddExpr(WideStart,
01268                        getMulExpr(WideMaxBECount,
01269                                   getSignExtendExpr(Step, WideTy)));
01270           if (SAdd == OperandExtendedAdd) {
01271             // Cache knowledge of AR NSW, which is propagated to this AddRec.
01272             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
01273             // Return the expression with the addrec on the outside.
01274             return getAddRecExpr(getSignExtendAddRecStart(AR, Ty, this),
01275                                  getSignExtendExpr(Step, Ty),
01276                                  L, AR->getNoWrapFlags());
01277           }
01278           // Similar to above, only this time treat the step value as unsigned.
01279           // This covers loops that count up with an unsigned step.
01280           OperandExtendedAdd =
01281             getAddExpr(WideStart,
01282                        getMulExpr(WideMaxBECount,
01283                                   getZeroExtendExpr(Step, WideTy)));
01284           if (SAdd == OperandExtendedAdd) {
01285             // Cache knowledge of AR NSW, which is propagated to this AddRec.
01286             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
01287             // Return the expression with the addrec on the outside.
01288             return getAddRecExpr(getSignExtendAddRecStart(AR, Ty, this),
01289                                  getZeroExtendExpr(Step, Ty),
01290                                  L, AR->getNoWrapFlags());
01291           }
01292         }
01293 
01294         // If the backedge is guarded by a comparison with the pre-inc value
01295         // the addrec is safe. Also, if the entry is guarded by a comparison
01296         // with the start value and the backedge is guarded by a comparison
01297         // with the post-inc value, the addrec is safe.
01298         ICmpInst::Predicate Pred;
01299         const SCEV *OverflowLimit = getOverflowLimitForStep(Step, &Pred, this);
01300         if (OverflowLimit &&
01301             (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
01302              (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) &&
01303               isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this),
01304                                           OverflowLimit)))) {
01305           // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec.
01306           const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
01307           return getAddRecExpr(getSignExtendAddRecStart(AR, Ty, this),
01308                                getSignExtendExpr(Step, Ty),
01309                                L, AR->getNoWrapFlags());
01310         }
01311       }
01312       // If Start and Step are constants, check if we can apply this
01313       // transformation:
01314       // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2
01315       auto SC1 = dyn_cast<SCEVConstant>(Start);
01316       auto SC2 = dyn_cast<SCEVConstant>(Step);
01317       if (SC1 && SC2) {
01318         const APInt &C1 = SC1->getValue()->getValue();
01319         const APInt &C2 = SC2->getValue()->getValue();
01320         if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) &&
01321             C2.isPowerOf2()) {
01322           Start = getSignExtendExpr(Start, Ty);
01323           const SCEV *NewAR = getAddRecExpr(getConstant(AR->getType(), 0), Step,
01324                                             L, AR->getNoWrapFlags());
01325           return getAddExpr(Start, getSignExtendExpr(NewAR, Ty));
01326         }
01327       }
01328     }
01329 
01330   // The cast wasn't folded; create an explicit cast node.
01331   // Recompute the insert position, as it may have been invalidated.
01332   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
01333   SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
01334                                                    Op, Ty);
01335   UniqueSCEVs.InsertNode(S, IP);
01336   return S;
01337 }
01338 
01339 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
01340 /// unspecified bits out to the given type.
01341 ///
01342 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
01343                                               Type *Ty) {
01344   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
01345          "This is not an extending conversion!");
01346   assert(isSCEVable(Ty) &&
01347          "This is not a conversion to a SCEVable type!");
01348   Ty = getEffectiveSCEVType(Ty);
01349 
01350   // Sign-extend negative constants.
01351   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
01352     if (SC->getValue()->getValue().isNegative())
01353       return getSignExtendExpr(Op, Ty);
01354 
01355   // Peel off a truncate cast.
01356   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
01357     const SCEV *NewOp = T->getOperand();
01358     if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
01359       return getAnyExtendExpr(NewOp, Ty);
01360     return getTruncateOrNoop(NewOp, Ty);
01361   }
01362 
01363   // Next try a zext cast. If the cast is folded, use it.
01364   const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
01365   if (!isa<SCEVZeroExtendExpr>(ZExt))
01366     return ZExt;
01367 
01368   // Next try a sext cast. If the cast is folded, use it.
01369   const SCEV *SExt = getSignExtendExpr(Op, Ty);
01370   if (!isa<SCEVSignExtendExpr>(SExt))
01371     return SExt;
01372 
01373   // Force the cast to be folded into the operands of an addrec.
01374   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
01375     SmallVector<const SCEV *, 4> Ops;
01376     for (const SCEV *Op : AR->operands())
01377       Ops.push_back(getAnyExtendExpr(Op, Ty));
01378     return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
01379   }
01380 
01381   // If the expression is obviously signed, use the sext cast value.
01382   if (isa<SCEVSMaxExpr>(Op))
01383     return SExt;
01384 
01385   // Absent any other information, use the zext cast value.
01386   return ZExt;
01387 }
01388 
01389 /// CollectAddOperandsWithScales - Process the given Ops list, which is
01390 /// a list of operands to be added under the given scale, update the given
01391 /// map. This is a helper function for getAddRecExpr. As an example of
01392 /// what it does, given a sequence of operands that would form an add
01393 /// expression like this:
01394 ///
01395 ///    m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
01396 ///
01397 /// where A and B are constants, update the map with these values:
01398 ///
01399 ///    (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
01400 ///
01401 /// and add 13 + A*B*29 to AccumulatedConstant.
01402 /// This will allow getAddRecExpr to produce this:
01403 ///
01404 ///    13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
01405 ///
01406 /// This form often exposes folding opportunities that are hidden in
01407 /// the original operand list.
01408 ///
01409 /// Return true iff it appears that any interesting folding opportunities
01410 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
01411 /// the common case where no interesting opportunities are present, and
01412 /// is also used as a check to avoid infinite recursion.
01413 ///
01414 static bool
01415 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
01416                              SmallVectorImpl<const SCEV *> &NewOps,
01417                              APInt &AccumulatedConstant,
01418                              const SCEV *const *Ops, size_t NumOperands,
01419                              const APInt &Scale,
01420                              ScalarEvolution &SE) {
01421   bool Interesting = false;
01422 
01423   // Iterate over the add operands. They are sorted, with constants first.
01424   unsigned i = 0;
01425   while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
01426     ++i;
01427     // Pull a buried constant out to the outside.
01428     if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
01429       Interesting = true;
01430     AccumulatedConstant += Scale * C->getValue()->getValue();
01431   }
01432 
01433   // Next comes everything else. We're especially interested in multiplies
01434   // here, but they're in the middle, so just visit the rest with one loop.
01435   for (; i != NumOperands; ++i) {
01436     const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
01437     if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
01438       APInt NewScale =
01439         Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
01440       if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
01441         // A multiplication of a constant with another add; recurse.
01442         const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
01443         Interesting |=
01444           CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
01445                                        Add->op_begin(), Add->getNumOperands(),
01446                                        NewScale, SE);
01447       } else {
01448         // A multiplication of a constant with some other value. Update
01449         // the map.
01450         SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
01451         const SCEV *Key = SE.getMulExpr(MulOps);
01452         std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
01453           M.insert(std::make_pair(Key, NewScale));
01454         if (Pair.second) {
01455           NewOps.push_back(Pair.first->first);
01456         } else {
01457           Pair.first->second += NewScale;
01458           // The map already had an entry for this value, which may indicate
01459           // a folding opportunity.
01460           Interesting = true;
01461         }
01462       }
01463     } else {
01464       // An ordinary operand. Update the map.
01465       std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
01466         M.insert(std::make_pair(Ops[i], Scale));
01467       if (Pair.second) {
01468         NewOps.push_back(Pair.first->first);
01469       } else {
01470         Pair.first->second += Scale;
01471         // The map already had an entry for this value, which may indicate
01472         // a folding opportunity.
01473         Interesting = true;
01474       }
01475     }
01476   }
01477 
01478   return Interesting;
01479 }
01480 
01481 namespace {
01482   struct APIntCompare {
01483     bool operator()(const APInt &LHS, const APInt &RHS) const {
01484       return LHS.ult(RHS);
01485     }
01486   };
01487 }
01488 
01489 /// getAddExpr - Get a canonical add expression, or something simpler if
01490 /// possible.
01491 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
01492                                         SCEV::NoWrapFlags Flags) {
01493   assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
01494          "only nuw or nsw allowed");
01495   assert(!Ops.empty() && "Cannot get empty add!");
01496   if (Ops.size() == 1) return Ops[0];
01497 #ifndef NDEBUG
01498   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
01499   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
01500     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
01501            "SCEVAddExpr operand types don't match!");
01502 #endif
01503 
01504   // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
01505   // And vice-versa.
01506   int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
01507   SCEV::NoWrapFlags SignOrUnsignWrap = maskFlags(Flags, SignOrUnsignMask);
01508   if (SignOrUnsignWrap && (SignOrUnsignWrap != SignOrUnsignMask)) {
01509     bool All = true;
01510     for (SmallVectorImpl<const SCEV *>::const_iterator I = Ops.begin(),
01511          E = Ops.end(); I != E; ++I)
01512       if (!isKnownNonNegative(*I)) {
01513         All = false;
01514         break;
01515       }
01516     if (All) Flags = setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
01517   }
01518 
01519   // Sort by complexity, this groups all similar expression types together.
01520   GroupByComplexity(Ops, LI);
01521 
01522   // If there are any constants, fold them together.
01523   unsigned Idx = 0;
01524   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
01525     ++Idx;
01526     assert(Idx < Ops.size());
01527     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
01528       // We found two constants, fold them together!
01529       Ops[0] = getConstant(LHSC->getValue()->getValue() +
01530                            RHSC->getValue()->getValue());
01531       if (Ops.size() == 2) return Ops[0];
01532       Ops.erase(Ops.begin()+1);  // Erase the folded element
01533       LHSC = cast<SCEVConstant>(Ops[0]);
01534     }
01535 
01536     // If we are left with a constant zero being added, strip it off.
01537     if (LHSC->getValue()->isZero()) {
01538       Ops.erase(Ops.begin());
01539       --Idx;
01540     }
01541 
01542     if (Ops.size() == 1) return Ops[0];
01543   }
01544 
01545   // Okay, check to see if the same value occurs in the operand list more than
01546   // once.  If so, merge them together into an multiply expression.  Since we
01547   // sorted the list, these values are required to be adjacent.
01548   Type *Ty = Ops[0]->getType();
01549   bool FoundMatch = false;
01550   for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
01551     if (Ops[i] == Ops[i+1]) {      //  X + Y + Y  -->  X + Y*2
01552       // Scan ahead to count how many equal operands there are.
01553       unsigned Count = 2;
01554       while (i+Count != e && Ops[i+Count] == Ops[i])
01555         ++Count;
01556       // Merge the values into a multiply.
01557       const SCEV *Scale = getConstant(Ty, Count);
01558       const SCEV *Mul = getMulExpr(Scale, Ops[i]);
01559       if (Ops.size() == Count)
01560         return Mul;
01561       Ops[i] = Mul;
01562       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
01563       --i; e -= Count - 1;
01564       FoundMatch = true;
01565     }
01566   if (FoundMatch)
01567     return getAddExpr(Ops, Flags);
01568 
01569   // Check for truncates. If all the operands are truncated from the same
01570   // type, see if factoring out the truncate would permit the result to be
01571   // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
01572   // if the contents of the resulting outer trunc fold to something simple.
01573   for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
01574     const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
01575     Type *DstType = Trunc->getType();
01576     Type *SrcType = Trunc->getOperand()->getType();
01577     SmallVector<const SCEV *, 8> LargeOps;
01578     bool Ok = true;
01579     // Check all the operands to see if they can be represented in the
01580     // source type of the truncate.
01581     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
01582       if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
01583         if (T->getOperand()->getType() != SrcType) {
01584           Ok = false;
01585           break;
01586         }
01587         LargeOps.push_back(T->getOperand());
01588       } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
01589         LargeOps.push_back(getAnyExtendExpr(C, SrcType));
01590       } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
01591         SmallVector<const SCEV *, 8> LargeMulOps;
01592         for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
01593           if (const SCEVTruncateExpr *T =
01594                 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
01595             if (T->getOperand()->getType() != SrcType) {
01596               Ok = false;
01597               break;
01598             }
01599             LargeMulOps.push_back(T->getOperand());
01600           } else if (const SCEVConstant *C =
01601                        dyn_cast<SCEVConstant>(M->getOperand(j))) {
01602             LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
01603           } else {
01604             Ok = false;
01605             break;
01606           }
01607         }
01608         if (Ok)
01609           LargeOps.push_back(getMulExpr(LargeMulOps));
01610       } else {
01611         Ok = false;
01612         break;
01613       }
01614     }
01615     if (Ok) {
01616       // Evaluate the expression in the larger type.
01617       const SCEV *Fold = getAddExpr(LargeOps, Flags);
01618       // If it folds to something simple, use it. Otherwise, don't.
01619       if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
01620         return getTruncateExpr(Fold, DstType);
01621     }
01622   }
01623 
01624   // Skip past any other cast SCEVs.
01625   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
01626     ++Idx;
01627 
01628   // If there are add operands they would be next.
01629   if (Idx < Ops.size()) {
01630     bool DeletedAdd = false;
01631     while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
01632       // If we have an add, expand the add operands onto the end of the operands
01633       // list.
01634       Ops.erase(Ops.begin()+Idx);
01635       Ops.append(Add->op_begin(), Add->op_end());
01636       DeletedAdd = true;
01637     }
01638 
01639     // If we deleted at least one add, we added operands to the end of the list,
01640     // and they are not necessarily sorted.  Recurse to resort and resimplify
01641     // any operands we just acquired.
01642     if (DeletedAdd)
01643       return getAddExpr(Ops);
01644   }
01645 
01646   // Skip over the add expression until we get to a multiply.
01647   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
01648     ++Idx;
01649 
01650   // Check to see if there are any folding opportunities present with
01651   // operands multiplied by constant values.
01652   if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
01653     uint64_t BitWidth = getTypeSizeInBits(Ty);
01654     DenseMap<const SCEV *, APInt> M;
01655     SmallVector<const SCEV *, 8> NewOps;
01656     APInt AccumulatedConstant(BitWidth, 0);
01657     if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
01658                                      Ops.data(), Ops.size(),
01659                                      APInt(BitWidth, 1), *this)) {
01660       // Some interesting folding opportunity is present, so its worthwhile to
01661       // re-generate the operands list. Group the operands by constant scale,
01662       // to avoid multiplying by the same constant scale multiple times.
01663       std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
01664       for (SmallVectorImpl<const SCEV *>::const_iterator I = NewOps.begin(),
01665            E = NewOps.end(); I != E; ++I)
01666         MulOpLists[M.find(*I)->second].push_back(*I);
01667       // Re-generate the operands list.
01668       Ops.clear();
01669       if (AccumulatedConstant != 0)
01670         Ops.push_back(getConstant(AccumulatedConstant));
01671       for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
01672            I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
01673         if (I->first != 0)
01674           Ops.push_back(getMulExpr(getConstant(I->first),
01675                                    getAddExpr(I->second)));
01676       if (Ops.empty())
01677         return getConstant(Ty, 0);
01678       if (Ops.size() == 1)
01679         return Ops[0];
01680       return getAddExpr(Ops);
01681     }
01682   }
01683 
01684   // If we are adding something to a multiply expression, make sure the
01685   // something is not already an operand of the multiply.  If so, merge it into
01686   // the multiply.
01687   for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
01688     const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
01689     for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
01690       const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
01691       if (isa<SCEVConstant>(MulOpSCEV))
01692         continue;
01693       for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
01694         if (MulOpSCEV == Ops[AddOp]) {
01695           // Fold W + X + (X * Y * Z)  -->  W + (X * ((Y*Z)+1))
01696           const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
01697           if (Mul->getNumOperands() != 2) {
01698             // If the multiply has more than two operands, we must get the
01699             // Y*Z term.
01700             SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
01701                                                 Mul->op_begin()+MulOp);
01702             MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
01703             InnerMul = getMulExpr(MulOps);
01704           }
01705           const SCEV *One = getConstant(Ty, 1);
01706           const SCEV *AddOne = getAddExpr(One, InnerMul);
01707           const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV);
01708           if (Ops.size() == 2) return OuterMul;
01709           if (AddOp < Idx) {
01710             Ops.erase(Ops.begin()+AddOp);
01711             Ops.erase(Ops.begin()+Idx-1);
01712           } else {
01713             Ops.erase(Ops.begin()+Idx);
01714             Ops.erase(Ops.begin()+AddOp-1);
01715           }
01716           Ops.push_back(OuterMul);
01717           return getAddExpr(Ops);
01718         }
01719 
01720       // Check this multiply against other multiplies being added together.
01721       for (unsigned OtherMulIdx = Idx+1;
01722            OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
01723            ++OtherMulIdx) {
01724         const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
01725         // If MulOp occurs in OtherMul, we can fold the two multiplies
01726         // together.
01727         for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
01728              OMulOp != e; ++OMulOp)
01729           if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
01730             // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
01731             const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
01732             if (Mul->getNumOperands() != 2) {
01733               SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
01734                                                   Mul->op_begin()+MulOp);
01735               MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
01736               InnerMul1 = getMulExpr(MulOps);
01737             }
01738             const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
01739             if (OtherMul->getNumOperands() != 2) {
01740               SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
01741                                                   OtherMul->op_begin()+OMulOp);
01742               MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
01743               InnerMul2 = getMulExpr(MulOps);
01744             }
01745             const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
01746             const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
01747             if (Ops.size() == 2) return OuterMul;
01748             Ops.erase(Ops.begin()+Idx);
01749             Ops.erase(Ops.begin()+OtherMulIdx-1);
01750             Ops.push_back(OuterMul);
01751             return getAddExpr(Ops);
01752           }
01753       }
01754     }
01755   }
01756 
01757   // If there are any add recurrences in the operands list, see if any other
01758   // added values are loop invariant.  If so, we can fold them into the
01759   // recurrence.
01760   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
01761     ++Idx;
01762 
01763   // Scan over all recurrences, trying to fold loop invariants into them.
01764   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
01765     // Scan all of the other operands to this add and add them to the vector if
01766     // they are loop invariant w.r.t. the recurrence.
01767     SmallVector<const SCEV *, 8> LIOps;
01768     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
01769     const Loop *AddRecLoop = AddRec->getLoop();
01770     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
01771       if (isLoopInvariant(Ops[i], AddRecLoop)) {
01772         LIOps.push_back(Ops[i]);
01773         Ops.erase(Ops.begin()+i);
01774         --i; --e;
01775       }
01776 
01777     // If we found some loop invariants, fold them into the recurrence.
01778     if (!LIOps.empty()) {
01779       //  NLI + LI + {Start,+,Step}  -->  NLI + {LI+Start,+,Step}
01780       LIOps.push_back(AddRec->getStart());
01781 
01782       SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
01783                                              AddRec->op_end());
01784       AddRecOps[0] = getAddExpr(LIOps);
01785 
01786       // Build the new addrec. Propagate the NUW and NSW flags if both the
01787       // outer add and the inner addrec are guaranteed to have no overflow.
01788       // Always propagate NW.
01789       Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
01790       const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
01791 
01792       // If all of the other operands were loop invariant, we are done.
01793       if (Ops.size() == 1) return NewRec;
01794 
01795       // Otherwise, add the folded AddRec by the non-invariant parts.
01796       for (unsigned i = 0;; ++i)
01797         if (Ops[i] == AddRec) {
01798           Ops[i] = NewRec;
01799           break;
01800         }
01801       return getAddExpr(Ops);
01802     }
01803 
01804     // Okay, if there weren't any loop invariants to be folded, check to see if
01805     // there are multiple AddRec's with the same loop induction variable being
01806     // added together.  If so, we can fold them.
01807     for (unsigned OtherIdx = Idx+1;
01808          OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
01809          ++OtherIdx)
01810       if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
01811         // Other + {A,+,B}<L> + {C,+,D}<L>  -->  Other + {A+C,+,B+D}<L>
01812         SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
01813                                                AddRec->op_end());
01814         for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
01815              ++OtherIdx)
01816           if (const SCEVAddRecExpr *OtherAddRec =
01817                 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]))
01818             if (OtherAddRec->getLoop() == AddRecLoop) {
01819               for (unsigned i = 0, e = OtherAddRec->getNumOperands();
01820                    i != e; ++i) {
01821                 if (i >= AddRecOps.size()) {
01822                   AddRecOps.append(OtherAddRec->op_begin()+i,
01823                                    OtherAddRec->op_end());
01824                   break;
01825                 }
01826                 AddRecOps[i] = getAddExpr(AddRecOps[i],
01827                                           OtherAddRec->getOperand(i));
01828               }
01829               Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
01830             }
01831         // Step size has changed, so we cannot guarantee no self-wraparound.
01832         Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
01833         return getAddExpr(Ops);
01834       }
01835 
01836     // Otherwise couldn't fold anything into this recurrence.  Move onto the
01837     // next one.
01838   }
01839 
01840   // Okay, it looks like we really DO need an add expr.  Check to see if we
01841   // already have one, otherwise create a new one.
01842   FoldingSetNodeID ID;
01843   ID.AddInteger(scAddExpr);
01844   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
01845     ID.AddPointer(Ops[i]);
01846   void *IP = nullptr;
01847   SCEVAddExpr *S =
01848     static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
01849   if (!S) {
01850     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
01851     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
01852     S = new (SCEVAllocator) SCEVAddExpr(ID.Intern(SCEVAllocator),
01853                                         O, Ops.size());
01854     UniqueSCEVs.InsertNode(S, IP);
01855   }
01856   S->setNoWrapFlags(Flags);
01857   return S;
01858 }
01859 
01860 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
01861   uint64_t k = i*j;
01862   if (j > 1 && k / j != i) Overflow = true;
01863   return k;
01864 }
01865 
01866 /// Compute the result of "n choose k", the binomial coefficient.  If an
01867 /// intermediate computation overflows, Overflow will be set and the return will
01868 /// be garbage. Overflow is not cleared on absence of overflow.
01869 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
01870   // We use the multiplicative formula:
01871   //     n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
01872   // At each iteration, we take the n-th term of the numeral and divide by the
01873   // (k-n)th term of the denominator.  This division will always produce an
01874   // integral result, and helps reduce the chance of overflow in the
01875   // intermediate computations. However, we can still overflow even when the
01876   // final result would fit.
01877 
01878   if (n == 0 || n == k) return 1;
01879   if (k > n) return 0;
01880 
01881   if (k > n/2)
01882     k = n-k;
01883 
01884   uint64_t r = 1;
01885   for (uint64_t i = 1; i <= k; ++i) {
01886     r = umul_ov(r, n-(i-1), Overflow);
01887     r /= i;
01888   }
01889   return r;
01890 }
01891 
01892 /// getMulExpr - Get a canonical multiply expression, or something simpler if
01893 /// possible.
01894 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
01895                                         SCEV::NoWrapFlags Flags) {
01896   assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&
01897          "only nuw or nsw allowed");
01898   assert(!Ops.empty() && "Cannot get empty mul!");
01899   if (Ops.size() == 1) return Ops[0];
01900 #ifndef NDEBUG
01901   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
01902   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
01903     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
01904            "SCEVMulExpr operand types don't match!");
01905 #endif
01906 
01907   // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
01908   // And vice-versa.
01909   int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
01910   SCEV::NoWrapFlags SignOrUnsignWrap = maskFlags(Flags, SignOrUnsignMask);
01911   if (SignOrUnsignWrap && (SignOrUnsignWrap != SignOrUnsignMask)) {
01912     bool All = true;
01913     for (SmallVectorImpl<const SCEV *>::const_iterator I = Ops.begin(),
01914          E = Ops.end(); I != E; ++I)
01915       if (!isKnownNonNegative(*I)) {
01916         All = false;
01917         break;
01918       }
01919     if (All) Flags = setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
01920   }
01921 
01922   // Sort by complexity, this groups all similar expression types together.
01923   GroupByComplexity(Ops, LI);
01924 
01925   // If there are any constants, fold them together.
01926   unsigned Idx = 0;
01927   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
01928 
01929     // C1*(C2+V) -> C1*C2 + C1*V
01930     if (Ops.size() == 2)
01931       if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
01932         if (Add->getNumOperands() == 2 &&
01933             isa<SCEVConstant>(Add->getOperand(0)))
01934           return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
01935                             getMulExpr(LHSC, Add->getOperand(1)));
01936 
01937     ++Idx;
01938     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
01939       // We found two constants, fold them together!
01940       ConstantInt *Fold = ConstantInt::get(getContext(),
01941                                            LHSC->getValue()->getValue() *
01942                                            RHSC->getValue()->getValue());
01943       Ops[0] = getConstant(Fold);
01944       Ops.erase(Ops.begin()+1);  // Erase the folded element
01945       if (Ops.size() == 1) return Ops[0];
01946       LHSC = cast<SCEVConstant>(Ops[0]);
01947     }
01948 
01949     // If we are left with a constant one being multiplied, strip it off.
01950     if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
01951       Ops.erase(Ops.begin());
01952       --Idx;
01953     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
01954       // If we have a multiply of zero, it will always be zero.
01955       return Ops[0];
01956     } else if (Ops[0]->isAllOnesValue()) {
01957       // If we have a mul by -1 of an add, try distributing the -1 among the
01958       // add operands.
01959       if (Ops.size() == 2) {
01960         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
01961           SmallVector<const SCEV *, 4> NewOps;
01962           bool AnyFolded = false;
01963           for (SCEVAddRecExpr::op_iterator I = Add->op_begin(),
01964                  E = Add->op_end(); I != E; ++I) {
01965             const SCEV *Mul = getMulExpr(Ops[0], *I);
01966             if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
01967             NewOps.push_back(Mul);
01968           }
01969           if (AnyFolded)
01970             return getAddExpr(NewOps);
01971         }
01972         else if (const SCEVAddRecExpr *
01973                  AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
01974           // Negation preserves a recurrence's no self-wrap property.
01975           SmallVector<const SCEV *, 4> Operands;
01976           for (SCEVAddRecExpr::op_iterator I = AddRec->op_begin(),
01977                  E = AddRec->op_end(); I != E; ++I) {
01978             Operands.push_back(getMulExpr(Ops[0], *I));
01979           }
01980           return getAddRecExpr(Operands, AddRec->getLoop(),
01981                                AddRec->getNoWrapFlags(SCEV::FlagNW));
01982         }
01983       }
01984     }
01985 
01986     if (Ops.size() == 1)
01987       return Ops[0];
01988   }
01989 
01990   // Skip over the add expression until we get to a multiply.
01991   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
01992     ++Idx;
01993 
01994   // If there are mul operands inline them all into this expression.
01995   if (Idx < Ops.size()) {
01996     bool DeletedMul = false;
01997     while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
01998       // If we have an mul, expand the mul operands onto the end of the operands
01999       // list.
02000       Ops.erase(Ops.begin()+Idx);
02001       Ops.append(Mul->op_begin(), Mul->op_end());
02002       DeletedMul = true;
02003     }
02004 
02005     // If we deleted at least one mul, we added operands to the end of the list,
02006     // and they are not necessarily sorted.  Recurse to resort and resimplify
02007     // any operands we just acquired.
02008     if (DeletedMul)
02009       return getMulExpr(Ops);
02010   }
02011 
02012   // If there are any add recurrences in the operands list, see if any other
02013   // added values are loop invariant.  If so, we can fold them into the
02014   // recurrence.
02015   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
02016     ++Idx;
02017 
02018   // Scan over all recurrences, trying to fold loop invariants into them.
02019   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
02020     // Scan all of the other operands to this mul and add them to the vector if
02021     // they are loop invariant w.r.t. the recurrence.
02022     SmallVector<const SCEV *, 8> LIOps;
02023     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
02024     const Loop *AddRecLoop = AddRec->getLoop();
02025     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
02026       if (isLoopInvariant(Ops[i], AddRecLoop)) {
02027         LIOps.push_back(Ops[i]);
02028         Ops.erase(Ops.begin()+i);
02029         --i; --e;
02030       }
02031 
02032     // If we found some loop invariants, fold them into the recurrence.
02033     if (!LIOps.empty()) {
02034       //  NLI * LI * {Start,+,Step}  -->  NLI * {LI*Start,+,LI*Step}
02035       SmallVector<const SCEV *, 4> NewOps;
02036       NewOps.reserve(AddRec->getNumOperands());
02037       const SCEV *Scale = getMulExpr(LIOps);
02038       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
02039         NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
02040 
02041       // Build the new addrec. Propagate the NUW and NSW flags if both the
02042       // outer mul and the inner addrec are guaranteed to have no overflow.
02043       //
02044       // No self-wrap cannot be guaranteed after changing the step size, but
02045       // will be inferred if either NUW or NSW is true.
02046       Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW));
02047       const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
02048 
02049       // If all of the other operands were loop invariant, we are done.
02050       if (Ops.size() == 1) return NewRec;
02051 
02052       // Otherwise, multiply the folded AddRec by the non-invariant parts.
02053       for (unsigned i = 0;; ++i)
02054         if (Ops[i] == AddRec) {
02055           Ops[i] = NewRec;
02056           break;
02057         }
02058       return getMulExpr(Ops);
02059     }
02060 
02061     // Okay, if there weren't any loop invariants to be folded, check to see if
02062     // there are multiple AddRec's with the same loop induction variable being
02063     // multiplied together.  If so, we can fold them.
02064     for (unsigned OtherIdx = Idx+1;
02065          OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
02066          ++OtherIdx) {
02067       if (AddRecLoop != cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop())
02068         continue;
02069 
02070       // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
02071       // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
02072       //       choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
02073       //   ]]],+,...up to x=2n}.
02074       // Note that the arguments to choose() are always integers with values
02075       // known at compile time, never SCEV objects.
02076       //
02077       // The implementation avoids pointless extra computations when the two
02078       // addrec's are of different length (mathematically, it's equivalent to
02079       // an infinite stream of zeros on the right).
02080       bool OpsModified = false;
02081       for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
02082            ++OtherIdx) {
02083         const SCEVAddRecExpr *OtherAddRec =
02084           dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
02085         if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
02086           continue;
02087 
02088         bool Overflow = false;
02089         Type *Ty = AddRec->getType();
02090         bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
02091         SmallVector<const SCEV*, 7> AddRecOps;
02092         for (int x = 0, xe = AddRec->getNumOperands() +
02093                OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
02094           const SCEV *Term = getConstant(Ty, 0);
02095           for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
02096             uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
02097             for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
02098                    ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
02099                  z < ze && !Overflow; ++z) {
02100               uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
02101               uint64_t Coeff;
02102               if (LargerThan64Bits)
02103                 Coeff = umul_ov(Coeff1, Coeff2, Overflow);
02104               else
02105                 Coeff = Coeff1*Coeff2;
02106               const SCEV *CoeffTerm = getConstant(Ty, Coeff);
02107               const SCEV *Term1 = AddRec->getOperand(y-z);
02108               const SCEV *Term2 = OtherAddRec->getOperand(z);
02109               Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1,Term2));
02110             }
02111           }
02112           AddRecOps.push_back(Term);
02113         }
02114         if (!Overflow) {
02115           const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
02116                                                 SCEV::FlagAnyWrap);
02117           if (Ops.size() == 2) return NewAddRec;
02118           Ops[Idx] = NewAddRec;
02119           Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
02120           OpsModified = true;
02121           AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
02122           if (!AddRec)
02123             break;
02124         }
02125       }
02126       if (OpsModified)
02127         return getMulExpr(Ops);
02128     }
02129 
02130     // Otherwise couldn't fold anything into this recurrence.  Move onto the
02131     // next one.
02132   }
02133 
02134   // Okay, it looks like we really DO need an mul expr.  Check to see if we
02135   // already have one, otherwise create a new one.
02136   FoldingSetNodeID ID;
02137   ID.AddInteger(scMulExpr);
02138   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
02139     ID.AddPointer(Ops[i]);
02140   void *IP = nullptr;
02141   SCEVMulExpr *S =
02142     static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
02143   if (!S) {
02144     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
02145     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
02146     S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
02147                                         O, Ops.size());
02148     UniqueSCEVs.InsertNode(S, IP);
02149   }
02150   S->setNoWrapFlags(Flags);
02151   return S;
02152 }
02153 
02154 /// getUDivExpr - Get a canonical unsigned division expression, or something
02155 /// simpler if possible.
02156 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
02157                                          const SCEV *RHS) {
02158   assert(getEffectiveSCEVType(LHS->getType()) ==
02159          getEffectiveSCEVType(RHS->getType()) &&
02160          "SCEVUDivExpr operand types don't match!");
02161 
02162   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
02163     if (RHSC->getValue()->equalsInt(1))
02164       return LHS;                               // X udiv 1 --> x
02165     // If the denominator is zero, the result of the udiv is undefined. Don't
02166     // try to analyze it, because the resolution chosen here may differ from
02167     // the resolution chosen in other parts of the compiler.
02168     if (!RHSC->getValue()->isZero()) {
02169       // Determine if the division can be folded into the operands of
02170       // its operands.
02171       // TODO: Generalize this to non-constants by using known-bits information.
02172       Type *Ty = LHS->getType();
02173       unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
02174       unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
02175       // For non-power-of-two values, effectively round the value up to the
02176       // nearest power of two.
02177       if (!RHSC->getValue()->getValue().isPowerOf2())
02178         ++MaxShiftAmt;
02179       IntegerType *ExtTy =
02180         IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
02181       if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
02182         if (const SCEVConstant *Step =
02183             dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
02184           // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
02185           const APInt &StepInt = Step->getValue()->getValue();
02186           const APInt &DivInt = RHSC->getValue()->getValue();
02187           if (!StepInt.urem(DivInt) &&
02188               getZeroExtendExpr(AR, ExtTy) ==
02189               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
02190                             getZeroExtendExpr(Step, ExtTy),
02191                             AR->getLoop(), SCEV::FlagAnyWrap)) {
02192             SmallVector<const SCEV *, 4> Operands;
02193             for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
02194               Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
02195             return getAddRecExpr(Operands, AR->getLoop(),
02196                                  SCEV::FlagNW);
02197           }
02198           /// Get a canonical UDivExpr for a recurrence.
02199           /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
02200           // We can currently only fold X%N if X is constant.
02201           const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
02202           if (StartC && !DivInt.urem(StepInt) &&
02203               getZeroExtendExpr(AR, ExtTy) ==
02204               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
02205                             getZeroExtendExpr(Step, ExtTy),
02206                             AR->getLoop(), SCEV::FlagAnyWrap)) {
02207             const APInt &StartInt = StartC->getValue()->getValue();
02208             const APInt &StartRem = StartInt.urem(StepInt);
02209             if (StartRem != 0)
02210               LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step,
02211                                   AR->getLoop(), SCEV::FlagNW);
02212           }
02213         }
02214       // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
02215       if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
02216         SmallVector<const SCEV *, 4> Operands;
02217         for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
02218           Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
02219         if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
02220           // Find an operand that's safely divisible.
02221           for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
02222             const SCEV *Op = M->getOperand(i);
02223             const SCEV *Div = getUDivExpr(Op, RHSC);
02224             if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
02225               Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
02226                                                       M->op_end());
02227               Operands[i] = Div;
02228               return getMulExpr(Operands);
02229             }
02230           }
02231       }
02232       // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
02233       if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
02234         SmallVector<const SCEV *, 4> Operands;
02235         for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
02236           Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
02237         if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
02238           Operands.clear();
02239           for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
02240             const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
02241             if (isa<SCEVUDivExpr>(Op) ||
02242                 getMulExpr(Op, RHS) != A->getOperand(i))
02243               break;
02244             Operands.push_back(Op);
02245           }
02246           if (Operands.size() == A->getNumOperands())
02247             return getAddExpr(Operands);
02248         }
02249       }
02250 
02251       // Fold if both operands are constant.
02252       if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
02253         Constant *LHSCV = LHSC->getValue();
02254         Constant *RHSCV = RHSC->getValue();
02255         return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
02256                                                                    RHSCV)));
02257       }
02258     }
02259   }
02260 
02261   FoldingSetNodeID ID;
02262   ID.AddInteger(scUDivExpr);
02263   ID.AddPointer(LHS);
02264   ID.AddPointer(RHS);
02265   void *IP = nullptr;
02266   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
02267   SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
02268                                              LHS, RHS);
02269   UniqueSCEVs.InsertNode(S, IP);
02270   return S;
02271 }
02272 
02273 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
02274   APInt A = C1->getValue()->getValue().abs();
02275   APInt B = C2->getValue()->getValue().abs();
02276   uint32_t ABW = A.getBitWidth();
02277   uint32_t BBW = B.getBitWidth();
02278 
02279   if (ABW > BBW)
02280     B = B.zext(ABW);
02281   else if (ABW < BBW)
02282     A = A.zext(BBW);
02283 
02284   return APIntOps::GreatestCommonDivisor(A, B);
02285 }
02286 
02287 /// getUDivExactExpr - Get a canonical unsigned division expression, or
02288 /// something simpler if possible. There is no representation for an exact udiv
02289 /// in SCEV IR, but we can attempt to remove factors from the LHS and RHS.
02290 /// We can't do this when it's not exact because the udiv may be clearing bits.
02291 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
02292                                               const SCEV *RHS) {
02293   // TODO: we could try to find factors in all sorts of things, but for now we
02294   // just deal with u/exact (multiply, constant). See SCEVDivision towards the
02295   // end of this file for inspiration.
02296 
02297   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
02298   if (!Mul)
02299     return getUDivExpr(LHS, RHS);
02300 
02301   if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
02302     // If the mulexpr multiplies by a constant, then that constant must be the
02303     // first element of the mulexpr.
02304     if (const SCEVConstant *LHSCst =
02305             dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
02306       if (LHSCst == RHSCst) {
02307         SmallVector<const SCEV *, 2> Operands;
02308         Operands.append(Mul->op_begin() + 1, Mul->op_end());
02309         return getMulExpr(Operands);
02310       }
02311 
02312       // We can't just assume that LHSCst divides RHSCst cleanly, it could be
02313       // that there's a factor provided by one of the other terms. We need to
02314       // check.
02315       APInt Factor = gcd(LHSCst, RHSCst);
02316       if (!Factor.isIntN(1)) {
02317         LHSCst = cast<SCEVConstant>(
02318             getConstant(LHSCst->getValue()->getValue().udiv(Factor)));
02319         RHSCst = cast<SCEVConstant>(
02320             getConstant(RHSCst->getValue()->getValue().udiv(Factor)));
02321         SmallVector<const SCEV *, 2> Operands;
02322         Operands.push_back(LHSCst);
02323         Operands.append(Mul->op_begin() + 1, Mul->op_end());
02324         LHS = getMulExpr(Operands);
02325         RHS = RHSCst;
02326         Mul = dyn_cast<SCEVMulExpr>(LHS);
02327         if (!Mul)
02328           return getUDivExactExpr(LHS, RHS);
02329       }
02330     }
02331   }
02332 
02333   for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
02334     if (Mul->getOperand(i) == RHS) {
02335       SmallVector<const SCEV *, 2> Operands;
02336       Operands.append(Mul->op_begin(), Mul->op_begin() + i);
02337       Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
02338       return getMulExpr(Operands);
02339     }
02340   }
02341 
02342   return getUDivExpr(LHS, RHS);
02343 }
02344 
02345 /// getAddRecExpr - Get an add recurrence expression for the specified loop.
02346 /// Simplify the expression as much as possible.
02347 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
02348                                            const Loop *L,
02349                                            SCEV::NoWrapFlags Flags) {
02350   SmallVector<const SCEV *, 4> Operands;
02351   Operands.push_back(Start);
02352   if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
02353     if (StepChrec->getLoop() == L) {
02354       Operands.append(StepChrec->op_begin(), StepChrec->op_end());
02355       return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
02356     }
02357 
02358   Operands.push_back(Step);
02359   return getAddRecExpr(Operands, L, Flags);
02360 }
02361 
02362 /// getAddRecExpr - Get an add recurrence expression for the specified loop.
02363 /// Simplify the expression as much as possible.
02364 const SCEV *
02365 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
02366                                const Loop *L, SCEV::NoWrapFlags Flags) {
02367   if (Operands.size() == 1) return Operands[0];
02368 #ifndef NDEBUG
02369   Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
02370   for (unsigned i = 1, e = Operands.size(); i != e; ++i)
02371     assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
02372            "SCEVAddRecExpr operand types don't match!");
02373   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
02374     assert(isLoopInvariant(Operands[i], L) &&
02375            "SCEVAddRecExpr operand is not loop-invariant!");
02376 #endif
02377 
02378   if (Operands.back()->isZero()) {
02379     Operands.pop_back();
02380     return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0}  -->  X
02381   }
02382 
02383   // It's tempting to want to call getMaxBackedgeTakenCount count here and
02384   // use that information to infer NUW and NSW flags. However, computing a
02385   // BE count requires calling getAddRecExpr, so we may not yet have a
02386   // meaningful BE count at this point (and if we don't, we'd be stuck
02387   // with a SCEVCouldNotCompute as the cached BE count).
02388 
02389   // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
02390   // And vice-versa.
02391   int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
02392   SCEV::NoWrapFlags SignOrUnsignWrap = maskFlags(Flags, SignOrUnsignMask);
02393   if (SignOrUnsignWrap && (SignOrUnsignWrap != SignOrUnsignMask)) {
02394     bool All = true;
02395     for (SmallVectorImpl<const SCEV *>::const_iterator I = Operands.begin(),
02396          E = Operands.end(); I != E; ++I)
02397       if (!isKnownNonNegative(*I)) {
02398         All = false;
02399         break;
02400       }
02401     if (All) Flags = setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
02402   }
02403 
02404   // Canonicalize nested AddRecs in by nesting them in order of loop depth.
02405   if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
02406     const Loop *NestedLoop = NestedAR->getLoop();
02407     if (L->contains(NestedLoop) ?
02408         (L->getLoopDepth() < NestedLoop->getLoopDepth()) :
02409         (!NestedLoop->contains(L) &&
02410          DT->dominates(L->getHeader(), NestedLoop->getHeader()))) {
02411       SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
02412                                                   NestedAR->op_end());
02413       Operands[0] = NestedAR->getStart();
02414       // AddRecs require their operands be loop-invariant with respect to their
02415       // loops. Don't perform this transformation if it would break this
02416       // requirement.
02417       bool AllInvariant = true;
02418       for (unsigned i = 0, e = Operands.size(); i != e; ++i)
02419         if (!isLoopInvariant(Operands[i], L)) {
02420           AllInvariant = false;
02421           break;
02422         }
02423       if (AllInvariant) {
02424         // Create a recurrence for the outer loop with the same step size.
02425         //
02426         // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
02427         // inner recurrence has the same property.
02428         SCEV::NoWrapFlags OuterFlags =
02429           maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
02430 
02431         NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
02432         AllInvariant = true;
02433         for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
02434           if (!isLoopInvariant(NestedOperands[i], NestedLoop)) {
02435             AllInvariant = false;
02436             break;
02437           }
02438         if (AllInvariant) {
02439           // Ok, both add recurrences are valid after the transformation.
02440           //
02441           // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
02442           // the outer recurrence has the same property.
02443           SCEV::NoWrapFlags InnerFlags =
02444             maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
02445           return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
02446         }
02447       }
02448       // Reset Operands to its original state.
02449       Operands[0] = NestedAR;
02450     }
02451   }
02452 
02453   // Okay, it looks like we really DO need an addrec expr.  Check to see if we
02454   // already have one, otherwise create a new one.
02455   FoldingSetNodeID ID;
02456   ID.AddInteger(scAddRecExpr);
02457   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
02458     ID.AddPointer(Operands[i]);
02459   ID.AddPointer(L);
02460   void *IP = nullptr;
02461   SCEVAddRecExpr *S =
02462     static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
02463   if (!S) {
02464     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
02465     std::uninitialized_copy(Operands.begin(), Operands.end(), O);
02466     S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
02467                                            O, Operands.size(), L);
02468     UniqueSCEVs.InsertNode(S, IP);
02469   }
02470   S->setNoWrapFlags(Flags);
02471   return S;
02472 }
02473 
02474 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
02475                                          const SCEV *RHS) {
02476   SmallVector<const SCEV *, 2> Ops;
02477   Ops.push_back(LHS);
02478   Ops.push_back(RHS);
02479   return getSMaxExpr(Ops);
02480 }
02481 
02482 const SCEV *
02483 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
02484   assert(!Ops.empty() && "Cannot get empty smax!");
02485   if (Ops.size() == 1) return Ops[0];
02486 #ifndef NDEBUG
02487   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
02488   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
02489     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
02490            "SCEVSMaxExpr operand types don't match!");
02491 #endif
02492 
02493   // Sort by complexity, this groups all similar expression types together.
02494   GroupByComplexity(Ops, LI);
02495 
02496   // If there are any constants, fold them together.
02497   unsigned Idx = 0;
02498   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
02499     ++Idx;
02500     assert(Idx < Ops.size());
02501     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
02502       // We found two constants, fold them together!
02503       ConstantInt *Fold = ConstantInt::get(getContext(),
02504                               APIntOps::smax(LHSC->getValue()->getValue(),
02505                                              RHSC->getValue()->getValue()));
02506       Ops[0] = getConstant(Fold);
02507       Ops.erase(Ops.begin()+1);  // Erase the folded element
02508       if (Ops.size() == 1) return Ops[0];
02509       LHSC = cast<SCEVConstant>(Ops[0]);
02510     }
02511 
02512     // If we are left with a constant minimum-int, strip it off.
02513     if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
02514       Ops.erase(Ops.begin());
02515       --Idx;
02516     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
02517       // If we have an smax with a constant maximum-int, it will always be
02518       // maximum-int.
02519       return Ops[0];
02520     }
02521 
02522     if (Ops.size() == 1) return Ops[0];
02523   }
02524 
02525   // Find the first SMax
02526   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
02527     ++Idx;
02528 
02529   // Check to see if one of the operands is an SMax. If so, expand its operands
02530   // onto our operand list, and recurse to simplify.
02531   if (Idx < Ops.size()) {
02532     bool DeletedSMax = false;
02533     while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
02534       Ops.erase(Ops.begin()+Idx);
02535       Ops.append(SMax->op_begin(), SMax->op_end());
02536       DeletedSMax = true;
02537     }
02538 
02539     if (DeletedSMax)
02540       return getSMaxExpr(Ops);
02541   }
02542 
02543   // Okay, check to see if the same value occurs in the operand list twice.  If
02544   // so, delete one.  Since we sorted the list, these values are required to
02545   // be adjacent.
02546   for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
02547     //  X smax Y smax Y  -->  X smax Y
02548     //  X smax Y         -->  X, if X is always greater than Y
02549     if (Ops[i] == Ops[i+1] ||
02550         isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
02551       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
02552       --i; --e;
02553     } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
02554       Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
02555       --i; --e;
02556     }
02557 
02558   if (Ops.size() == 1) return Ops[0];
02559 
02560   assert(!Ops.empty() && "Reduced smax down to nothing!");
02561 
02562   // Okay, it looks like we really DO need an smax expr.  Check to see if we
02563   // already have one, otherwise create a new one.
02564   FoldingSetNodeID ID;
02565   ID.AddInteger(scSMaxExpr);
02566   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
02567     ID.AddPointer(Ops[i]);
02568   void *IP = nullptr;
02569   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
02570   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
02571   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
02572   SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
02573                                              O, Ops.size());
02574   UniqueSCEVs.InsertNode(S, IP);
02575   return S;
02576 }
02577 
02578 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
02579                                          const SCEV *RHS) {
02580   SmallVector<const SCEV *, 2> Ops;
02581   Ops.push_back(LHS);
02582   Ops.push_back(RHS);
02583   return getUMaxExpr(Ops);
02584 }
02585 
02586 const SCEV *
02587 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
02588   assert(!Ops.empty() && "Cannot get empty umax!");
02589   if (Ops.size() == 1) return Ops[0];
02590 #ifndef NDEBUG
02591   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
02592   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
02593     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
02594            "SCEVUMaxExpr operand types don't match!");
02595 #endif
02596 
02597   // Sort by complexity, this groups all similar expression types together.
02598   GroupByComplexity(Ops, LI);
02599 
02600   // If there are any constants, fold them together.
02601   unsigned Idx = 0;
02602   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
02603     ++Idx;
02604     assert(Idx < Ops.size());
02605     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
02606       // We found two constants, fold them together!
02607       ConstantInt *Fold = ConstantInt::get(getContext(),
02608                               APIntOps::umax(LHSC->getValue()->getValue(),
02609                                              RHSC->getValue()->getValue()));
02610       Ops[0] = getConstant(Fold);
02611       Ops.erase(Ops.begin()+1);  // Erase the folded element
02612       if (Ops.size() == 1) return Ops[0];
02613       LHSC = cast<SCEVConstant>(Ops[0]);
02614     }
02615 
02616     // If we are left with a constant minimum-int, strip it off.
02617     if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
02618       Ops.erase(Ops.begin());
02619       --Idx;
02620     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
02621       // If we have an umax with a constant maximum-int, it will always be
02622       // maximum-int.
02623       return Ops[0];
02624     }
02625 
02626     if (Ops.size() == 1) return Ops[0];
02627   }
02628 
02629   // Find the first UMax
02630   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
02631     ++Idx;
02632 
02633   // Check to see if one of the operands is a UMax. If so, expand its operands
02634   // onto our operand list, and recurse to simplify.
02635   if (Idx < Ops.size()) {
02636     bool DeletedUMax = false;
02637     while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
02638       Ops.erase(Ops.begin()+Idx);
02639       Ops.append(UMax->op_begin(), UMax->op_end());
02640       DeletedUMax = true;
02641     }
02642 
02643     if (DeletedUMax)
02644       return getUMaxExpr(Ops);
02645   }
02646 
02647   // Okay, check to see if the same value occurs in the operand list twice.  If
02648   // so, delete one.  Since we sorted the list, these values are required to
02649   // be adjacent.
02650   for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
02651     //  X umax Y umax Y  -->  X umax Y
02652     //  X umax Y         -->  X, if X is always greater than Y
02653     if (Ops[i] == Ops[i+1] ||
02654         isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
02655       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
02656       --i; --e;
02657     } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
02658       Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
02659       --i; --e;
02660     }
02661 
02662   if (Ops.size() == 1) return Ops[0];
02663 
02664   assert(!Ops.empty() && "Reduced umax down to nothing!");
02665 
02666   // Okay, it looks like we really DO need a umax expr.  Check to see if we
02667   // already have one, otherwise create a new one.
02668   FoldingSetNodeID ID;
02669   ID.AddInteger(scUMaxExpr);
02670   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
02671     ID.AddPointer(Ops[i]);
02672   void *IP = nullptr;
02673   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
02674   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
02675   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
02676   SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
02677                                              O, Ops.size());
02678   UniqueSCEVs.InsertNode(S, IP);
02679   return S;
02680 }
02681 
02682 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
02683                                          const SCEV *RHS) {
02684   // ~smax(~x, ~y) == smin(x, y).
02685   return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
02686 }
02687 
02688 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
02689                                          const SCEV *RHS) {
02690   // ~umax(~x, ~y) == umin(x, y)
02691   return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
02692 }
02693 
02694 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
02695   // If we have DataLayout, we can bypass creating a target-independent
02696   // constant expression and then folding it back into a ConstantInt.
02697   // This is just a compile-time optimization.
02698   if (DL)
02699     return getConstant(IntTy, DL->getTypeAllocSize(AllocTy));
02700 
02701   Constant *C = ConstantExpr::getSizeOf(AllocTy);
02702   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
02703     if (Constant *Folded = ConstantFoldConstantExpression(CE, DL, TLI))
02704       C = Folded;
02705   Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
02706   assert(Ty == IntTy && "Effective SCEV type doesn't match");
02707   return getTruncateOrZeroExtend(getSCEV(C), Ty);
02708 }
02709 
02710 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
02711                                              StructType *STy,
02712                                              unsigned FieldNo) {
02713   // If we have DataLayout, we can bypass creating a target-independent
02714   // constant expression and then folding it back into a ConstantInt.
02715   // This is just a compile-time optimization.
02716   if (DL) {
02717     return getConstant(IntTy,
02718                        DL->getStructLayout(STy)->getElementOffset(FieldNo));
02719   }
02720 
02721   Constant *C = ConstantExpr::getOffsetOf(STy, FieldNo);
02722   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
02723     if (Constant *Folded = ConstantFoldConstantExpression(CE, DL, TLI))
02724       C = Folded;
02725 
02726   Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(STy));
02727   return getTruncateOrZeroExtend(getSCEV(C), Ty);
02728 }
02729 
02730 const SCEV *ScalarEvolution::getUnknown(Value *V) {
02731   // Don't attempt to do anything other than create a SCEVUnknown object
02732   // here.  createSCEV only calls getUnknown after checking for all other
02733   // interesting possibilities, and any other code that calls getUnknown
02734   // is doing so in order to hide a value from SCEV canonicalization.
02735 
02736   FoldingSetNodeID ID;
02737   ID.AddInteger(scUnknown);
02738   ID.AddPointer(V);
02739   void *IP = nullptr;
02740   if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
02741     assert(cast<SCEVUnknown>(S)->getValue() == V &&
02742            "Stale SCEVUnknown in uniquing map!");
02743     return S;
02744   }
02745   SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
02746                                             FirstUnknown);
02747   FirstUnknown = cast<SCEVUnknown>(S);
02748   UniqueSCEVs.InsertNode(S, IP);
02749   return S;
02750 }
02751 
02752 //===----------------------------------------------------------------------===//
02753 //            Basic SCEV Analysis and PHI Idiom Recognition Code
02754 //
02755 
02756 /// isSCEVable - Test if values of the given type are analyzable within
02757 /// the SCEV framework. This primarily includes integer types, and it
02758 /// can optionally include pointer types if the ScalarEvolution class
02759 /// has access to target-specific information.
02760 bool ScalarEvolution::isSCEVable(Type *Ty) const {
02761   // Integers and pointers are always SCEVable.
02762   return Ty->isIntegerTy() || Ty->isPointerTy();
02763 }
02764 
02765 /// getTypeSizeInBits - Return the size in bits of the specified type,
02766 /// for which isSCEVable must return true.
02767 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
02768   assert(isSCEVable(Ty) && "Type is not SCEVable!");
02769 
02770   // If we have a DataLayout, use it!
02771   if (DL)
02772     return DL->getTypeSizeInBits(Ty);
02773 
02774   // Integer types have fixed sizes.
02775   if (Ty->isIntegerTy())
02776     return Ty->getPrimitiveSizeInBits();
02777 
02778   // The only other support type is pointer. Without DataLayout, conservatively
02779   // assume pointers are 64-bit.
02780   assert(Ty->isPointerTy() && "isSCEVable permitted a non-SCEVable type!");
02781   return 64;
02782 }
02783 
02784 /// getEffectiveSCEVType - Return a type with the same bitwidth as
02785 /// the given type and which represents how SCEV will treat the given
02786 /// type, for which isSCEVable must return true. For pointer types,
02787 /// this is the pointer-sized integer type.
02788 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
02789   assert(isSCEVable(Ty) && "Type is not SCEVable!");
02790 
02791   if (Ty->isIntegerTy()) {
02792     return Ty;
02793   }
02794 
02795   // The only other support type is pointer.
02796   assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
02797 
02798   if (DL)
02799     return DL->getIntPtrType(Ty);
02800 
02801   // Without DataLayout, conservatively assume pointers are 64-bit.
02802   return Type::getInt64Ty(getContext());
02803 }
02804 
02805 const SCEV *ScalarEvolution::getCouldNotCompute() {
02806   return &CouldNotCompute;
02807 }
02808 
02809 namespace {
02810   // Helper class working with SCEVTraversal to figure out if a SCEV contains
02811   // a SCEVUnknown with null value-pointer. FindInvalidSCEVUnknown::FindOne
02812   // is set iff if find such SCEVUnknown.
02813   //
02814   struct FindInvalidSCEVUnknown {
02815     bool FindOne;
02816     FindInvalidSCEVUnknown() { FindOne = false; }
02817     bool follow(const SCEV *S) {
02818       switch (static_cast<SCEVTypes>(S->getSCEVType())) {
02819       case scConstant:
02820         return false;
02821       case scUnknown:
02822         if (!cast<SCEVUnknown>(S)->getValue())
02823           FindOne = true;
02824         return false;
02825       default:
02826         return true;
02827       }
02828     }
02829     bool isDone() const { return FindOne; }
02830   };
02831 }
02832 
02833 bool ScalarEvolution::checkValidity(const SCEV *S) const {
02834   FindInvalidSCEVUnknown F;
02835   SCEVTraversal<FindInvalidSCEVUnknown> ST(F);
02836   ST.visitAll(S);
02837 
02838   return !F.FindOne;
02839 }
02840 
02841 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
02842 /// expression and create a new one.
02843 const SCEV *ScalarEvolution::getSCEV(Value *V) {
02844   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
02845 
02846   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
02847   if (I != ValueExprMap.end()) {
02848     const SCEV *S = I->second;
02849     if (checkValidity(S))
02850       return S;
02851     else
02852       ValueExprMap.erase(I);
02853   }
02854   const SCEV *S = createSCEV(V);
02855 
02856   // The process of creating a SCEV for V may have caused other SCEVs
02857   // to have been created, so it's necessary to insert the new entry
02858   // from scratch, rather than trying to remember the insert position
02859   // above.
02860   ValueExprMap.insert(std::make_pair(SCEVCallbackVH(V, this), S));
02861   return S;
02862 }
02863 
02864 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
02865 ///
02866 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V) {
02867   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
02868     return getConstant(
02869                cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
02870 
02871   Type *Ty = V->getType();
02872   Ty = getEffectiveSCEVType(Ty);
02873   return getMulExpr(V,
02874                   getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))));
02875 }
02876 
02877 /// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
02878 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
02879   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
02880     return getConstant(
02881                 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
02882 
02883   Type *Ty = V->getType();
02884   Ty = getEffectiveSCEVType(Ty);
02885   const SCEV *AllOnes =
02886                    getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
02887   return getMinusSCEV(AllOnes, V);
02888 }
02889 
02890 /// getMinusSCEV - Return LHS-RHS.  Minus is represented in SCEV as A+B*-1.
02891 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
02892                                           SCEV::NoWrapFlags Flags) {
02893   assert(!maskFlags(Flags, SCEV::FlagNUW) && "subtraction does not have NUW");
02894 
02895   // Fast path: X - X --> 0.
02896   if (LHS == RHS)
02897     return getConstant(LHS->getType(), 0);
02898 
02899   // X - Y --> X + -Y
02900   return getAddExpr(LHS, getNegativeSCEV(RHS), Flags);
02901 }
02902 
02903 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
02904 /// input value to the specified type.  If the type must be extended, it is zero
02905 /// extended.
02906 const SCEV *
02907 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) {
02908   Type *SrcTy = V->getType();
02909   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
02910          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
02911          "Cannot truncate or zero extend with non-integer arguments!");
02912   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
02913     return V;  // No conversion
02914   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
02915     return getTruncateExpr(V, Ty);
02916   return getZeroExtendExpr(V, Ty);
02917 }
02918 
02919 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
02920 /// input value to the specified type.  If the type must be extended, it is sign
02921 /// extended.
02922 const SCEV *
02923 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
02924                                          Type *Ty) {
02925   Type *SrcTy = V->getType();
02926   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
02927          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
02928          "Cannot truncate or zero extend with non-integer arguments!");
02929   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
02930     return V;  // No conversion
02931   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
02932     return getTruncateExpr(V, Ty);
02933   return getSignExtendExpr(V, Ty);
02934 }
02935 
02936 /// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
02937 /// input value to the specified type.  If the type must be extended, it is zero
02938 /// extended.  The conversion must not be narrowing.
02939 const SCEV *
02940 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
02941   Type *SrcTy = V->getType();
02942   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
02943          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
02944          "Cannot noop or zero extend with non-integer arguments!");
02945   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
02946          "getNoopOrZeroExtend cannot truncate!");
02947   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
02948     return V;  // No conversion
02949   return getZeroExtendExpr(V, Ty);
02950 }
02951 
02952 /// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
02953 /// input value to the specified type.  If the type must be extended, it is sign
02954 /// extended.  The conversion must not be narrowing.
02955 const SCEV *
02956 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
02957   Type *SrcTy = V->getType();
02958   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
02959          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
02960          "Cannot noop or sign extend with non-integer arguments!");
02961   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
02962          "getNoopOrSignExtend cannot truncate!");
02963   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
02964     return V;  // No conversion
02965   return getSignExtendExpr(V, Ty);
02966 }
02967 
02968 /// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
02969 /// the input value to the specified type. If the type must be extended,
02970 /// it is extended with unspecified bits. The conversion must not be
02971 /// narrowing.
02972 const SCEV *
02973 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
02974   Type *SrcTy = V->getType();
02975   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
02976          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
02977          "Cannot noop or any extend with non-integer arguments!");
02978   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
02979          "getNoopOrAnyExtend cannot truncate!");
02980   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
02981     return V;  // No conversion
02982   return getAnyExtendExpr(V, Ty);
02983 }
02984 
02985 /// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
02986 /// input value to the specified type.  The conversion must not be widening.
02987 const SCEV *
02988 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
02989   Type *SrcTy = V->getType();
02990   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
02991          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
02992          "Cannot truncate or noop with non-integer arguments!");
02993   assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
02994          "getTruncateOrNoop cannot extend!");
02995   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
02996     return V;  // No conversion
02997   return getTruncateExpr(V, Ty);
02998 }
02999 
03000 /// getUMaxFromMismatchedTypes - Promote the operands to the wider of
03001 /// the types using zero-extension, and then perform a umax operation
03002 /// with them.
03003 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
03004                                                         const SCEV *RHS) {
03005   const SCEV *PromotedLHS = LHS;
03006   const SCEV *PromotedRHS = RHS;
03007 
03008   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
03009     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
03010   else
03011     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
03012 
03013   return getUMaxExpr(PromotedLHS, PromotedRHS);
03014 }
03015 
03016 /// getUMinFromMismatchedTypes - Promote the operands to the wider of
03017 /// the types using zero-extension, and then perform a umin operation
03018 /// with them.
03019 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
03020                                                         const SCEV *RHS) {
03021   const SCEV *PromotedLHS = LHS;
03022   const SCEV *PromotedRHS = RHS;
03023 
03024   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
03025     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
03026   else
03027     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
03028 
03029   return getUMinExpr(PromotedLHS, PromotedRHS);
03030 }
03031 
03032 /// getPointerBase - Transitively follow the chain of pointer-type operands
03033 /// until reaching a SCEV that does not have a single pointer operand. This
03034 /// returns a SCEVUnknown pointer for well-formed pointer-type expressions,
03035 /// but corner cases do exist.
03036 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
03037   // A pointer operand may evaluate to a nonpointer expression, such as null.
03038   if (!V->getType()->isPointerTy())
03039     return V;
03040 
03041   if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
03042     return getPointerBase(Cast->getOperand());
03043   }
03044   else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
03045     const SCEV *PtrOp = nullptr;
03046     for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
03047          I != E; ++I) {
03048       if ((*I)->getType()->isPointerTy()) {
03049         // Cannot find the base of an expression with multiple pointer operands.
03050         if (PtrOp)
03051           return V;
03052         PtrOp = *I;
03053       }
03054     }
03055     if (!PtrOp)
03056       return V;
03057     return getPointerBase(PtrOp);
03058   }
03059   return V;
03060 }
03061 
03062 /// PushDefUseChildren - Push users of the given Instruction
03063 /// onto the given Worklist.
03064 static void
03065 PushDefUseChildren(Instruction *I,
03066                    SmallVectorImpl<Instruction *> &Worklist) {
03067   // Push the def-use children onto the Worklist stack.
03068   for (User *U : I->users())
03069     Worklist.push_back(cast<Instruction>(U));
03070 }
03071 
03072 /// ForgetSymbolicValue - This looks up computed SCEV values for all
03073 /// instructions that depend on the given instruction and removes them from
03074 /// the ValueExprMapType map if they reference SymName. This is used during PHI
03075 /// resolution.
03076 void
03077 ScalarEvolution::ForgetSymbolicName(Instruction *PN, const SCEV *SymName) {
03078   SmallVector<Instruction *, 16> Worklist;
03079   PushDefUseChildren(PN, Worklist);
03080 
03081   SmallPtrSet<Instruction *, 8> Visited;
03082   Visited.insert(PN);
03083   while (!Worklist.empty()) {
03084     Instruction *I = Worklist.pop_back_val();
03085     if (!Visited.insert(I)) continue;
03086 
03087     ValueExprMapType::iterator It =
03088       ValueExprMap.find_as(static_cast<Value *>(I));
03089     if (It != ValueExprMap.end()) {
03090       const SCEV *Old = It->second;
03091 
03092       // Short-circuit the def-use traversal if the symbolic name
03093       // ceases to appear in expressions.
03094       if (Old != SymName && !hasOperand(Old, SymName))
03095         continue;
03096 
03097       // SCEVUnknown for a PHI either means that it has an unrecognized
03098       // structure, it's a PHI that's in the progress of being computed
03099       // by createNodeForPHI, or it's a single-value PHI. In the first case,
03100       // additional loop trip count information isn't going to change anything.
03101       // In the second case, createNodeForPHI will perform the necessary
03102       // updates on its own when it gets to that point. In the third, we do
03103       // want to forget the SCEVUnknown.
03104       if (!isa<PHINode>(I) ||
03105           !isa<SCEVUnknown>(Old) ||
03106           (I != PN && Old == SymName)) {
03107         forgetMemoizedResults(Old);
03108         ValueExprMap.erase(It);
03109       }
03110     }
03111 
03112     PushDefUseChildren(I, Worklist);
03113   }
03114 }
03115 
03116 /// createNodeForPHI - PHI nodes have two cases.  Either the PHI node exists in
03117 /// a loop header, making it a potential recurrence, or it doesn't.
03118 ///
03119 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
03120   if (const Loop *L = LI->getLoopFor(PN->getParent()))
03121     if (L->getHeader() == PN->getParent()) {
03122       // The loop may have multiple entrances or multiple exits; we can analyze
03123       // this phi as an addrec if it has a unique entry value and a unique
03124       // backedge value.
03125       Value *BEValueV = nullptr, *StartValueV = nullptr;
03126       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
03127         Value *V = PN->getIncomingValue(i);
03128         if (L->contains(PN->getIncomingBlock(i))) {
03129           if (!BEValueV) {
03130             BEValueV = V;
03131           } else if (BEValueV != V) {
03132             BEValueV = nullptr;
03133             break;
03134           }
03135         } else if (!StartValueV) {
03136           StartValueV = V;
03137         } else if (StartValueV != V) {
03138           StartValueV = nullptr;
03139           break;
03140         }
03141       }
03142       if (BEValueV && StartValueV) {
03143         // While we are analyzing this PHI node, handle its value symbolically.
03144         const SCEV *SymbolicName = getUnknown(PN);
03145         assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
03146                "PHI node already processed?");
03147         ValueExprMap.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
03148 
03149         // Using this symbolic name for the PHI, analyze the value coming around
03150         // the back-edge.
03151         const SCEV *BEValue = getSCEV(BEValueV);
03152 
03153         // NOTE: If BEValue is loop invariant, we know that the PHI node just
03154         // has a special value for the first iteration of the loop.
03155 
03156         // If the value coming around the backedge is an add with the symbolic
03157         // value we just inserted, then we found a simple induction variable!
03158         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
03159           // If there is a single occurrence of the symbolic value, replace it
03160           // with a recurrence.
03161           unsigned FoundIndex = Add->getNumOperands();
03162           for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
03163             if (Add->getOperand(i) == SymbolicName)
03164               if (FoundIndex == e) {
03165                 FoundIndex = i;
03166                 break;
03167               }
03168 
03169           if (FoundIndex != Add->getNumOperands()) {
03170             // Create an add with everything but the specified operand.
03171             SmallVector<const SCEV *, 8> Ops;
03172             for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
03173               if (i != FoundIndex)
03174                 Ops.push_back(Add->getOperand(i));
03175             const SCEV *Accum = getAddExpr(Ops);
03176 
03177             // This is not a valid addrec if the step amount is varying each
03178             // loop iteration, but is not itself an addrec in this loop.
03179             if (isLoopInvariant(Accum, L) ||
03180                 (isa<SCEVAddRecExpr>(Accum) &&
03181                  cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
03182               SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
03183 
03184               // If the increment doesn't overflow, then neither the addrec nor
03185               // the post-increment will overflow.
03186               if (const AddOperator *OBO = dyn_cast<AddOperator>(BEValueV)) {
03187                 if (OBO->hasNoUnsignedWrap())
03188                   Flags = setFlags(Flags, SCEV::FlagNUW);
03189                 if (OBO->hasNoSignedWrap())
03190                   Flags = setFlags(Flags, SCEV::FlagNSW);
03191               } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
03192                 // If the increment is an inbounds GEP, then we know the address
03193                 // space cannot be wrapped around. We cannot make any guarantee
03194                 // about signed or unsigned overflow because pointers are
03195                 // unsigned but we may have a negative index from the base
03196                 // pointer. We can guarantee that no unsigned wrap occurs if the
03197                 // indices form a positive value.
03198                 if (GEP->isInBounds()) {
03199                   Flags = setFlags(Flags, SCEV::FlagNW);
03200 
03201                   const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
03202                   if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
03203                     Flags = setFlags(Flags, SCEV::FlagNUW);
03204                 }
03205               } else if (const SubOperator *OBO =
03206                            dyn_cast<SubOperator>(BEValueV)) {
03207                 if (OBO->hasNoUnsignedWrap())
03208                   Flags = setFlags(Flags, SCEV::FlagNUW);
03209                 if (OBO->hasNoSignedWrap())
03210                   Flags = setFlags(Flags, SCEV::FlagNSW);
03211               }
03212 
03213               const SCEV *StartVal = getSCEV(StartValueV);
03214               const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
03215 
03216               // Since the no-wrap flags are on the increment, they apply to the
03217               // post-incremented value as well.
03218               if (isLoopInvariant(Accum, L))
03219                 (void)getAddRecExpr(getAddExpr(StartVal, Accum),
03220                                     Accum, L, Flags);
03221 
03222               // Okay, for the entire analysis of this edge we assumed the PHI
03223               // to be symbolic.  We now need to go back and purge all of the
03224               // entries for the scalars that use the symbolic expression.
03225               ForgetSymbolicName(PN, SymbolicName);
03226               ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
03227               return PHISCEV;
03228             }
03229           }
03230         } else if (const SCEVAddRecExpr *AddRec =
03231                      dyn_cast<SCEVAddRecExpr>(BEValue)) {
03232           // Otherwise, this could be a loop like this:
03233           //     i = 0;  for (j = 1; ..; ++j) { ....  i = j; }
03234           // In this case, j = {1,+,1}  and BEValue is j.
03235           // Because the other in-value of i (0) fits the evolution of BEValue
03236           // i really is an addrec evolution.
03237           if (AddRec->getLoop() == L && AddRec->isAffine()) {
03238             const SCEV *StartVal = getSCEV(StartValueV);
03239 
03240             // If StartVal = j.start - j.stride, we can use StartVal as the
03241             // initial step of the addrec evolution.
03242             if (StartVal == getMinusSCEV(AddRec->getOperand(0),
03243                                          AddRec->getOperand(1))) {
03244               // FIXME: For constant StartVal, we should be able to infer
03245               // no-wrap flags.
03246               const SCEV *PHISCEV =
03247                 getAddRecExpr(StartVal, AddRec->getOperand(1), L,
03248                               SCEV::FlagAnyWrap);
03249 
03250               // Okay, for the entire analysis of this edge we assumed the PHI
03251               // to be symbolic.  We now need to go back and purge all of the
03252               // entries for the scalars that use the symbolic expression.
03253               ForgetSymbolicName(PN, SymbolicName);
03254               ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
03255               return PHISCEV;
03256             }
03257           }
03258         }
03259       }
03260     }
03261 
03262   // If the PHI has a single incoming value, follow that value, unless the
03263   // PHI's incoming blocks are in a different loop, in which case doing so
03264   // risks breaking LCSSA form. Instcombine would normally zap these, but
03265   // it doesn't have DominatorTree information, so it may miss cases.
03266   if (Value *V = SimplifyInstruction(PN, DL, TLI, DT))
03267     if (LI->replacementPreservesLCSSAForm(PN, V))
03268       return getSCEV(V);
03269 
03270   // If it's not a loop phi, we can't handle it yet.
03271   return getUnknown(PN);
03272 }
03273 
03274 /// createNodeForGEP - Expand GEP instructions into add and multiply
03275 /// operations. This allows them to be analyzed by regular SCEV code.
03276 ///
03277 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
03278   Type *IntPtrTy = getEffectiveSCEVType(GEP->getType());
03279   Value *Base = GEP->getOperand(0);
03280   // Don't attempt to analyze GEPs over unsized objects.
03281   if (!Base->getType()->getPointerElementType()->isSized())
03282     return getUnknown(GEP);
03283 
03284   // Don't blindly transfer the inbounds flag from the GEP instruction to the
03285   // Add expression, because the Instruction may be guarded by control flow
03286   // and the no-overflow bits may not be valid for the expression in any
03287   // context.
03288   SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
03289 
03290   const SCEV *TotalOffset = getConstant(IntPtrTy, 0);
03291   gep_type_iterator GTI = gep_type_begin(GEP);
03292   for (GetElementPtrInst::op_iterator I = std::next(GEP->op_begin()),
03293                                       E = GEP->op_end();
03294        I != E; ++I) {
03295     Value *Index = *I;
03296     // Compute the (potentially symbolic) offset in bytes for this index.
03297     if (StructType *STy = dyn_cast<StructType>(*GTI++)) {
03298       // For a struct, add the member offset.
03299       unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
03300       const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo);
03301 
03302       // Add the field offset to the running total offset.
03303       TotalOffset = getAddExpr(TotalOffset, FieldOffset);
03304     } else {
03305       // For an array, add the element offset, explicitly scaled.
03306       const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, *GTI);
03307       const SCEV *IndexS = getSCEV(Index);
03308       // Getelementptr indices are signed.
03309       IndexS = getTruncateOrSignExtend(IndexS, IntPtrTy);
03310 
03311       // Multiply the index by the element size to compute the element offset.
03312       const SCEV *LocalOffset = getMulExpr(IndexS, ElementSize, Wrap);
03313 
03314       // Add the element offset to the running total offset.
03315       TotalOffset = getAddExpr(TotalOffset, LocalOffset);
03316     }
03317   }
03318 
03319   // Get the SCEV for the GEP base.
03320   const SCEV *BaseS = getSCEV(Base);
03321 
03322   // Add the total offset from all the GEP indices to the base.
03323   return getAddExpr(BaseS, TotalOffset, Wrap);
03324 }
03325 
03326 /// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
03327 /// guaranteed to end in (at every loop iteration).  It is, at the same time,
03328 /// the minimum number of times S is divisible by 2.  For example, given {4,+,8}
03329 /// it returns 2.  If S is guaranteed to be 0, it returns the bitwidth of S.
03330 uint32_t
03331 ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
03332   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
03333     return C->getValue()->getValue().countTrailingZeros();
03334 
03335   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
03336     return std::min(GetMinTrailingZeros(T->getOperand()),
03337                     (uint32_t)getTypeSizeInBits(T->getType()));
03338 
03339   if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
03340     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
03341     return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
03342              getTypeSizeInBits(E->getType()) : OpRes;
03343   }
03344 
03345   if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
03346     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
03347     return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
03348              getTypeSizeInBits(E->getType()) : OpRes;
03349   }
03350 
03351   if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
03352     // The result is the min of all operands results.
03353     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
03354     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
03355       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
03356     return MinOpRes;
03357   }
03358 
03359   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
03360     // The result is the sum of all operands results.
03361     uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
03362     uint32_t BitWidth = getTypeSizeInBits(M->getType());
03363     for (unsigned i = 1, e = M->getNumOperands();
03364          SumOpRes != BitWidth && i != e; ++i)
03365       SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
03366                           BitWidth);
03367     return SumOpRes;
03368   }
03369 
03370   if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
03371     // The result is the min of all operands results.
03372     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
03373     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
03374       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
03375     return MinOpRes;
03376   }
03377 
03378   if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
03379     // The result is the min of all operands results.
03380     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
03381     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
03382       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
03383     return MinOpRes;
03384   }
03385 
03386   if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
03387     // The result is the min of all operands results.
03388     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
03389     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
03390       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
03391     return MinOpRes;
03392   }
03393 
03394   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
03395     // For a SCEVUnknown, ask ValueTracking.
03396     unsigned BitWidth = getTypeSizeInBits(U->getType());
03397     APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
03398     computeKnownBits(U->getValue(), Zeros, Ones);
03399     return Zeros.countTrailingOnes();
03400   }
03401 
03402   // SCEVUDivExpr
03403   return 0;
03404 }
03405 
03406 /// getUnsignedRange - Determine the unsigned range for a particular SCEV.
03407 ///
03408 ConstantRange
03409 ScalarEvolution::getUnsignedRange(const SCEV *S) {
03410   // See if we've computed this range already.
03411   DenseMap<const SCEV *, ConstantRange>::iterator I = UnsignedRanges.find(S);
03412   if (I != UnsignedRanges.end())
03413     return I->second;
03414 
03415   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
03416     return setUnsignedRange(C, ConstantRange(C->getValue()->getValue()));
03417 
03418   unsigned BitWidth = getTypeSizeInBits(S->getType());
03419   ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
03420 
03421   // If the value has known zeros, the maximum unsigned value will have those
03422   // known zeros as well.
03423   uint32_t TZ = GetMinTrailingZeros(S);
03424   if (TZ != 0)
03425     ConservativeResult =
03426       ConstantRange(APInt::getMinValue(BitWidth),
03427                     APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
03428 
03429   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
03430     ConstantRange X = getUnsignedRange(Add->getOperand(0));
03431     for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
03432       X = X.add(getUnsignedRange(Add->getOperand(i)));
03433     return setUnsignedRange(Add, ConservativeResult.intersectWith(X));
03434   }
03435 
03436   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
03437     ConstantRange X = getUnsignedRange(Mul->getOperand(0));
03438     for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
03439       X = X.multiply(getUnsignedRange(Mul->getOperand(i)));
03440     return setUnsignedRange(Mul, ConservativeResult.intersectWith(X));
03441   }
03442 
03443   if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
03444     ConstantRange X = getUnsignedRange(SMax->getOperand(0));
03445     for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
03446       X = X.smax(getUnsignedRange(SMax->getOperand(i)));
03447     return setUnsignedRange(SMax, ConservativeResult.intersectWith(X));
03448   }
03449 
03450   if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
03451     ConstantRange X = getUnsignedRange(UMax->getOperand(0));
03452     for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
03453       X = X.umax(getUnsignedRange(UMax->getOperand(i)));
03454     return setUnsignedRange(UMax, ConservativeResult.intersectWith(X));
03455   }
03456 
03457   if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
03458     ConstantRange X = getUnsignedRange(UDiv->getLHS());
03459     ConstantRange Y = getUnsignedRange(UDiv->getRHS());
03460     return setUnsignedRange(UDiv, ConservativeResult.intersectWith(X.udiv(Y)));
03461   }
03462 
03463   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
03464     ConstantRange X = getUnsignedRange(ZExt->getOperand());
03465     return setUnsignedRange(ZExt,
03466       ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
03467   }
03468 
03469   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
03470     ConstantRange X = getUnsignedRange(SExt->getOperand());
03471     return setUnsignedRange(SExt,
03472       ConservativeResult.intersectWith(X.signExtend(BitWidth)));
03473   }
03474 
03475   if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
03476     ConstantRange X = getUnsignedRange(Trunc->getOperand());
03477     return setUnsignedRange(Trunc,
03478       ConservativeResult.intersectWith(X.truncate(BitWidth)));
03479   }
03480 
03481   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
03482     // If there's no unsigned wrap, the value will never be less than its
03483     // initial value.
03484     if (AddRec->getNoWrapFlags(SCEV::FlagNUW))
03485       if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
03486         if (!C->getValue()->isZero())
03487           ConservativeResult =
03488             ConservativeResult.intersectWith(
03489               ConstantRange(C->getValue()->getValue(), APInt(BitWidth, 0)));
03490 
03491     // TODO: non-affine addrec
03492     if (AddRec->isAffine()) {
03493       Type *Ty = AddRec->getType();
03494       const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
03495       if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
03496           getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
03497         MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
03498 
03499         const SCEV *Start = AddRec->getStart();
03500         const SCEV *Step = AddRec->getStepRecurrence(*this);
03501 
03502         ConstantRange StartRange = getUnsignedRange(Start);
03503         ConstantRange StepRange = getSignedRange(Step);
03504         ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
03505         ConstantRange EndRange =
03506           StartRange.add(MaxBECountRange.multiply(StepRange));
03507 
03508         // Check for overflow. This must be done with ConstantRange arithmetic
03509         // because we could be called from within the ScalarEvolution overflow
03510         // checking code.
03511         ConstantRange ExtStartRange = StartRange.zextOrTrunc(BitWidth*2+1);
03512         ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
03513         ConstantRange ExtMaxBECountRange =
03514           MaxBECountRange.zextOrTrunc(BitWidth*2+1);
03515         ConstantRange ExtEndRange = EndRange.zextOrTrunc(BitWidth*2+1);
03516         if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
03517             ExtEndRange)
03518           return setUnsignedRange(AddRec, ConservativeResult);
03519 
03520         APInt Min = APIntOps::umin(StartRange.getUnsignedMin(),
03521                                    EndRange.getUnsignedMin());
03522         APInt Max = APIntOps::umax(StartRange.getUnsignedMax(),
03523                                    EndRange.getUnsignedMax());
03524         if (Min.isMinValue() && Max.isMaxValue())
03525           return setUnsignedRange(AddRec, ConservativeResult);
03526         return setUnsignedRange(AddRec,
03527           ConservativeResult.intersectWith(ConstantRange(Min, Max+1)));
03528       }
03529     }
03530 
03531     return setUnsignedRange(AddRec, ConservativeResult);
03532   }
03533 
03534   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
03535     // For a SCEVUnknown, ask ValueTracking.
03536     APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
03537     computeKnownBits(U->getValue(), Zeros, Ones, DL);
03538     if (Ones == ~Zeros + 1)
03539       return setUnsignedRange(U, ConservativeResult);
03540     return setUnsignedRange(U,
03541       ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1)));
03542   }
03543 
03544   return setUnsignedRange(S, ConservativeResult);
03545 }
03546 
03547 /// getSignedRange - Determine the signed range for a particular SCEV.
03548 ///
03549 ConstantRange
03550 ScalarEvolution::getSignedRange(const SCEV *S) {
03551   // See if we've computed this range already.
03552   DenseMap<const SCEV *, ConstantRange>::iterator I = SignedRanges.find(S);
03553   if (I != SignedRanges.end())
03554     return I->second;
03555 
03556   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
03557     return setSignedRange(C, ConstantRange(C->getValue()->getValue()));
03558 
03559   unsigned BitWidth = getTypeSizeInBits(S->getType());
03560   ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
03561 
03562   // If the value has known zeros, the maximum signed value will have those
03563   // known zeros as well.
03564   uint32_t TZ = GetMinTrailingZeros(S);
03565   if (TZ != 0)
03566     ConservativeResult =
03567       ConstantRange(APInt::getSignedMinValue(BitWidth),
03568                     APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
03569 
03570   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
03571     ConstantRange X = getSignedRange(Add->getOperand(0));
03572     for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
03573       X = X.add(getSignedRange(Add->getOperand(i)));
03574     return setSignedRange(Add, ConservativeResult.intersectWith(X));
03575   }
03576 
03577   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
03578     ConstantRange X = getSignedRange(Mul->getOperand(0));
03579     for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
03580       X = X.multiply(getSignedRange(Mul->getOperand(i)));
03581     return setSignedRange(Mul, ConservativeResult.intersectWith(X));
03582   }
03583 
03584   if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
03585     ConstantRange X = getSignedRange(SMax->getOperand(0));
03586     for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
03587       X = X.smax(getSignedRange(SMax->getOperand(i)));
03588     return setSignedRange(SMax, ConservativeResult.intersectWith(X));
03589   }
03590 
03591   if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
03592     ConstantRange X = getSignedRange(UMax->getOperand(0));
03593     for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
03594       X = X.umax(getSignedRange(UMax->getOperand(i)));
03595     return setSignedRange(UMax, ConservativeResult.intersectWith(X));
03596   }
03597 
03598   if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
03599     ConstantRange X = getSignedRange(UDiv->getLHS());
03600     ConstantRange Y = getSignedRange(UDiv->getRHS());
03601     return setSignedRange(UDiv, ConservativeResult.intersectWith(X.udiv(Y)));
03602   }
03603 
03604   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
03605     ConstantRange X = getSignedRange(ZExt->getOperand());
03606     return setSignedRange(ZExt,
03607       ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
03608   }
03609 
03610   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
03611     ConstantRange X = getSignedRange(SExt->getOperand());
03612     return setSignedRange(SExt,
03613       ConservativeResult.intersectWith(X.signExtend(BitWidth)));
03614   }
03615 
03616   if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
03617     ConstantRange X = getSignedRange(Trunc->getOperand());
03618     return setSignedRange(Trunc,
03619       ConservativeResult.intersectWith(X.truncate(BitWidth)));
03620   }
03621 
03622   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
03623     // If there's no signed wrap, and all the operands have the same sign or
03624     // zero, the value won't ever change sign.
03625     if (AddRec->getNoWrapFlags(SCEV::FlagNSW)) {
03626       bool AllNonNeg = true;
03627       bool AllNonPos = true;
03628       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
03629         if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
03630         if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
03631       }
03632       if (AllNonNeg)
03633         ConservativeResult = ConservativeResult.intersectWith(
03634           ConstantRange(APInt(BitWidth, 0),
03635                         APInt::getSignedMinValue(BitWidth)));
03636       else if (AllNonPos)
03637         ConservativeResult = ConservativeResult.intersectWith(
03638           ConstantRange(APInt::getSignedMinValue(BitWidth),
03639                         APInt(BitWidth, 1)));
03640     }
03641 
03642     // TODO: non-affine addrec
03643     if (AddRec->isAffine()) {
03644       Type *Ty = AddRec->getType();
03645       const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
03646       if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
03647           getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
03648         MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
03649 
03650         const SCEV *Start = AddRec->getStart();
03651         const SCEV *Step = AddRec->getStepRecurrence(*this);
03652 
03653         ConstantRange StartRange = getSignedRange(Start);
03654         ConstantRange StepRange = getSignedRange(Step);
03655         ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
03656         ConstantRange EndRange =
03657           StartRange.add(MaxBECountRange.multiply(StepRange));
03658 
03659         // Check for overflow. This must be done with ConstantRange arithmetic
03660         // because we could be called from within the ScalarEvolution overflow
03661         // checking code.
03662         ConstantRange ExtStartRange = StartRange.sextOrTrunc(BitWidth*2+1);
03663         ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
03664         ConstantRange ExtMaxBECountRange =
03665           MaxBECountRange.zextOrTrunc(BitWidth*2+1);
03666         ConstantRange ExtEndRange = EndRange.sextOrTrunc(BitWidth*2+1);
03667         if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
03668             ExtEndRange)
03669           return setSignedRange(AddRec, ConservativeResult);
03670 
03671         APInt Min = APIntOps::smin(StartRange.getSignedMin(),
03672                                    EndRange.getSignedMin());
03673         APInt Max = APIntOps::smax(StartRange.getSignedMax(),
03674                                    EndRange.getSignedMax());
03675         if (Min.isMinSignedValue() && Max.isMaxSignedValue())
03676           return setSignedRange(AddRec, ConservativeResult);
03677         return setSignedRange(AddRec,
03678           ConservativeResult.intersectWith(ConstantRange(Min, Max+1)));
03679       }
03680     }
03681 
03682     return setSignedRange(AddRec, ConservativeResult);
03683   }
03684 
03685   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
03686     // For a SCEVUnknown, ask ValueTracking.
03687     if (!U->getValue()->getType()->isIntegerTy() && !DL)
03688       return setSignedRange(U, ConservativeResult);
03689     unsigned NS = ComputeNumSignBits(U->getValue(), DL);
03690     if (NS <= 1)
03691       return setSignedRange(U, ConservativeResult);
03692     return setSignedRange(U, ConservativeResult.intersectWith(
03693       ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
03694                     APInt::getSignedMaxValue(BitWidth).ashr(NS - 1)+1)));
03695   }
03696 
03697   return setSignedRange(S, ConservativeResult);
03698 }
03699 
03700 /// createSCEV - We know that there is no SCEV for the specified value.
03701 /// Analyze the expression.
03702 ///
03703 const SCEV *ScalarEvolution::createSCEV(Value *V) {
03704   if (!isSCEVable(V->getType()))
03705     return getUnknown(V);
03706 
03707   unsigned Opcode = Instruction::UserOp1;
03708   if (Instruction *I = dyn_cast<Instruction>(V)) {
03709     Opcode = I->getOpcode();
03710 
03711     // Don't attempt to analyze instructions in blocks that aren't
03712     // reachable. Such instructions don't matter, and they aren't required
03713     // to obey basic rules for definitions dominating uses which this
03714     // analysis depends on.
03715     if (!DT->isReachableFromEntry(I->getParent()))
03716       return getUnknown(V);
03717   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
03718     Opcode = CE->getOpcode();
03719   else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
03720     return getConstant(CI);
03721   else if (isa<ConstantPointerNull>(V))
03722     return getConstant(V->getType(), 0);
03723   else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
03724     return GA->mayBeOverridden() ? getUnknown(V) : getSCEV(GA->getAliasee());
03725   else
03726     return getUnknown(V);
03727 
03728   Operator *U = cast<Operator>(V);
03729   switch (Opcode) {
03730   case Instruction::Add: {
03731     // The simple thing to do would be to just call getSCEV on both operands
03732     // and call getAddExpr with the result. However if we're looking at a
03733     // bunch of things all added together, this can be quite inefficient,
03734     // because it leads to N-1 getAddExpr calls for N ultimate operands.
03735     // Instead, gather up all the operands and make a single getAddExpr call.
03736     // LLVM IR canonical form means we need only traverse the left operands.
03737     //
03738     // Don't apply this instruction's NSW or NUW flags to the new
03739     // expression. The instruction may be guarded by control flow that the
03740     // no-wrap behavior depends on. Non-control-equivalent instructions can be
03741     // mapped to the same SCEV expression, and it would be incorrect to transfer
03742     // NSW/NUW semantics to those operations.
03743     SmallVector<const SCEV *, 4> AddOps;
03744     AddOps.push_back(getSCEV(U->getOperand(1)));
03745     for (Value *Op = U->getOperand(0); ; Op = U->getOperand(0)) {
03746       unsigned Opcode = Op->getValueID() - Value::InstructionVal;
03747       if (Opcode != Instruction::Add && Opcode != Instruction::Sub)
03748         break;
03749       U = cast<Operator>(Op);
03750       const SCEV *Op1 = getSCEV(U->getOperand(1));
03751       if (Opcode == Instruction::Sub)
03752         AddOps.push_back(getNegativeSCEV(Op1));
03753       else
03754         AddOps.push_back(Op1);
03755     }
03756     AddOps.push_back(getSCEV(U->getOperand(0)));
03757     return getAddExpr(AddOps);
03758   }
03759   case Instruction::Mul: {
03760     // Don't transfer NSW/NUW for the same reason as AddExpr.
03761     SmallVector<const SCEV *, 4> MulOps;
03762     MulOps.push_back(getSCEV(U->getOperand(1)));
03763     for (Value *Op = U->getOperand(0);
03764          Op->getValueID() == Instruction::Mul + Value::InstructionVal;
03765          Op = U->getOperand(0)) {
03766       U = cast<Operator>(Op);
03767       MulOps.push_back(getSCEV(U->getOperand(1)));
03768     }
03769     MulOps.push_back(getSCEV(U->getOperand(0)));
03770     return getMulExpr(MulOps);
03771   }
03772   case Instruction::UDiv:
03773     return getUDivExpr(getSCEV(U->getOperand(0)),
03774                        getSCEV(U->getOperand(1)));
03775   case Instruction::Sub:
03776     return getMinusSCEV(getSCEV(U->getOperand(0)),
03777                         getSCEV(U->getOperand(1)));
03778   case Instruction::And:
03779     // For an expression like x&255 that merely masks off the high bits,
03780     // use zext(trunc(x)) as the SCEV expression.
03781     if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
03782       if (CI->isNullValue())
03783         return getSCEV(U->getOperand(1));
03784       if (CI->isAllOnesValue())
03785         return getSCEV(U->getOperand(0));
03786       const APInt &A = CI->getValue();
03787 
03788       // Instcombine's ShrinkDemandedConstant may strip bits out of
03789       // constants, obscuring what would otherwise be a low-bits mask.
03790       // Use computeKnownBits to compute what ShrinkDemandedConstant
03791       // knew about to reconstruct a low-bits mask value.
03792       unsigned LZ = A.countLeadingZeros();
03793       unsigned TZ = A.countTrailingZeros();
03794       unsigned BitWidth = A.getBitWidth();
03795       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
03796       computeKnownBits(U->getOperand(0), KnownZero, KnownOne, DL);
03797 
03798       APInt EffectiveMask =
03799           APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
03800       if ((LZ != 0 || TZ != 0) && !((~A & ~KnownZero) & EffectiveMask)) {
03801         const SCEV *MulCount = getConstant(
03802             ConstantInt::get(getContext(), APInt::getOneBitSet(BitWidth, TZ)));
03803         return getMulExpr(
03804             getZeroExtendExpr(
03805                 getTruncateExpr(
03806                     getUDivExactExpr(getSCEV(U->getOperand(0)), MulCount),
03807                     IntegerType::get(getContext(), BitWidth - LZ - TZ)),
03808                 U->getType()),
03809             MulCount);
03810       }
03811     }
03812     break;
03813 
03814   case Instruction::Or:
03815     // If the RHS of the Or is a constant, we may have something like:
03816     // X*4+1 which got turned into X*4|1.  Handle this as an Add so loop
03817     // optimizations will transparently handle this case.
03818     //
03819     // In order for this transformation to be safe, the LHS must be of the
03820     // form X*(2^n) and the Or constant must be less than 2^n.
03821     if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
03822       const SCEV *LHS = getSCEV(U->getOperand(0));
03823       const APInt &CIVal = CI->getValue();
03824       if (GetMinTrailingZeros(LHS) >=
03825           (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
03826         // Build a plain add SCEV.
03827         const SCEV *S = getAddExpr(LHS, getSCEV(CI));
03828         // If the LHS of the add was an addrec and it has no-wrap flags,
03829         // transfer the no-wrap flags, since an or won't introduce a wrap.
03830         if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
03831           const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
03832           const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags(
03833             OldAR->getNoWrapFlags());
03834         }
03835         return S;
03836       }
03837     }
03838     break;
03839   case Instruction::Xor:
03840     if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
03841       // If the RHS of the xor is a signbit, then this is just an add.
03842       // Instcombine turns add of signbit into xor as a strength reduction step.
03843       if (CI->getValue().isSignBit())
03844         return getAddExpr(getSCEV(U->getOperand(0)),
03845                           getSCEV(U->getOperand(1)));
03846 
03847       // If the RHS of xor is -1, then this is a not operation.
03848       if (CI->isAllOnesValue())
03849         return getNotSCEV(getSCEV(U->getOperand(0)));
03850 
03851       // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
03852       // This is a variant of the check for xor with -1, and it handles
03853       // the case where instcombine has trimmed non-demanded bits out
03854       // of an xor with -1.
03855       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
03856         if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
03857           if (BO->getOpcode() == Instruction::And &&
03858               LCI->getValue() == CI->getValue())
03859             if (const SCEVZeroExtendExpr *Z =
03860                   dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
03861               Type *UTy = U->getType();
03862               const SCEV *Z0 = Z->getOperand();
03863               Type *Z0Ty = Z0->getType();
03864               unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
03865 
03866               // If C is a low-bits mask, the zero extend is serving to
03867               // mask off the high bits. Complement the operand and
03868               // re-apply the zext.
03869               if (APIntOps::isMask(Z0TySize, CI->getValue()))
03870                 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
03871 
03872               // If C is a single bit, it may be in the sign-bit position
03873               // before the zero-extend. In this case, represent the xor
03874               // using an add, which is equivalent, and re-apply the zext.
03875               APInt Trunc = CI->getValue().trunc(Z0TySize);
03876               if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
03877                   Trunc.isSignBit())
03878                 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
03879                                          UTy);
03880             }
03881     }
03882     break;
03883 
03884   case Instruction::Shl:
03885     // Turn shift left of a constant amount into a multiply.
03886     if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
03887       uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
03888 
03889       // If the shift count is not less than the bitwidth, the result of
03890       // the shift is undefined. Don't try to analyze it, because the
03891       // resolution chosen here may differ from the resolution chosen in
03892       // other parts of the compiler.
03893       if (SA->getValue().uge(BitWidth))
03894         break;
03895 
03896       Constant *X = ConstantInt::get(getContext(),
03897         APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
03898       return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
03899     }
03900     break;
03901 
03902   case Instruction::LShr:
03903     // Turn logical shift right of a constant into a unsigned divide.
03904     if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
03905       uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
03906 
03907       // If the shift count is not less than the bitwidth, the result of
03908       // the shift is undefined. Don't try to analyze it, because the
03909       // resolution chosen here may differ from the resolution chosen in
03910       // other parts of the compiler.
03911       if (SA->getValue().uge(BitWidth))
03912         break;
03913 
03914       Constant *X = ConstantInt::get(getContext(),
03915         APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
03916       return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
03917     }
03918     break;
03919 
03920   case Instruction::AShr:
03921     // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
03922     if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
03923       if (Operator *L = dyn_cast<Operator>(U->getOperand(0)))
03924         if (L->getOpcode() == Instruction::Shl &&
03925             L->getOperand(1) == U->getOperand(1)) {
03926           uint64_t BitWidth = getTypeSizeInBits(U->getType());
03927 
03928           // If the shift count is not less than the bitwidth, the result of
03929           // the shift is undefined. Don't try to analyze it, because the
03930           // resolution chosen here may differ from the resolution chosen in
03931           // other parts of the compiler.
03932           if (CI->getValue().uge(BitWidth))
03933             break;
03934 
03935           uint64_t Amt = BitWidth - CI->getZExtValue();
03936           if (Amt == BitWidth)
03937             return getSCEV(L->getOperand(0));       // shift by zero --> noop
03938           return
03939             getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
03940                                               IntegerType::get(getContext(),
03941                                                                Amt)),
03942                               U->getType());
03943         }
03944     break;
03945 
03946   case Instruction::Trunc:
03947     return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
03948 
03949   case Instruction::ZExt:
03950     return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
03951 
03952   case Instruction::SExt:
03953     return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
03954 
03955   case Instruction::BitCast:
03956     // BitCasts are no-op casts so we just eliminate the cast.
03957     if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
03958       return getSCEV(U->getOperand(0));
03959     break;
03960 
03961   // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
03962   // lead to pointer expressions which cannot safely be expanded to GEPs,
03963   // because ScalarEvolution doesn't respect the GEP aliasing rules when
03964   // simplifying integer expressions.
03965 
03966   case Instruction::GetElementPtr:
03967     return createNodeForGEP(cast<GEPOperator>(U));
03968 
03969   case Instruction::PHI:
03970     return createNodeForPHI(cast<PHINode>(U));
03971 
03972   case Instruction::Select:
03973     // This could be a smax or umax that was lowered earlier.
03974     // Try to recover it.
03975     if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
03976       Value *LHS = ICI->getOperand(0);
03977       Value *RHS = ICI->getOperand(1);
03978       switch (ICI->getPredicate()) {
03979       case ICmpInst::ICMP_SLT:
03980       case ICmpInst::ICMP_SLE:
03981         std::swap(LHS, RHS);
03982         // fall through
03983       case ICmpInst::ICMP_SGT:
03984       case ICmpInst::ICMP_SGE:
03985         // a >s b ? a+x : b+x  ->  smax(a, b)+x
03986         // a >s b ? b+x : a+x  ->  smin(a, b)+x
03987         if (LHS->getType() == U->getType()) {
03988           const SCEV *LS = getSCEV(LHS);
03989           const SCEV *RS = getSCEV(RHS);
03990           const SCEV *LA = getSCEV(U->getOperand(1));
03991           const SCEV *RA = getSCEV(U->getOperand(2));
03992           const SCEV *LDiff = getMinusSCEV(LA, LS);
03993           const SCEV *RDiff = getMinusSCEV(RA, RS);
03994           if (LDiff == RDiff)
03995             return getAddExpr(getSMaxExpr(LS, RS), LDiff);
03996           LDiff = getMinusSCEV(LA, RS);
03997           RDiff = getMinusSCEV(RA, LS);
03998           if (LDiff == RDiff)
03999             return getAddExpr(getSMinExpr(LS, RS), LDiff);
04000         }
04001         break;
04002       case ICmpInst::ICMP_ULT:
04003       case ICmpInst::ICMP_ULE:
04004         std::swap(LHS, RHS);
04005         // fall through
04006       case ICmpInst::ICMP_UGT:
04007       case ICmpInst::ICMP_UGE:
04008         // a >u b ? a+x : b+x  ->  umax(a, b)+x
04009         // a >u b ? b+x : a+x  ->  umin(a, b)+x
04010         if (LHS->getType() == U->getType()) {
04011           const SCEV *LS = getSCEV(LHS);
04012           const SCEV *RS = getSCEV(RHS);
04013           const SCEV *LA = getSCEV(U->getOperand(1));
04014           const SCEV *RA = getSCEV(U->getOperand(2));
04015           const SCEV *LDiff = getMinusSCEV(LA, LS);
04016           const SCEV *RDiff = getMinusSCEV(RA, RS);
04017           if (LDiff == RDiff)
04018             return getAddExpr(getUMaxExpr(LS, RS), LDiff);
04019           LDiff = getMinusSCEV(LA, RS);
04020           RDiff = getMinusSCEV(RA, LS);
04021           if (LDiff == RDiff)
04022             return getAddExpr(getUMinExpr(LS, RS), LDiff);
04023         }
04024         break;
04025       case ICmpInst::ICMP_NE:
04026         // n != 0 ? n+x : 1+x  ->  umax(n, 1)+x
04027         if (LHS->getType() == U->getType() &&
04028             isa<ConstantInt>(RHS) &&
04029             cast<ConstantInt>(RHS)->isZero()) {
04030           const SCEV *One = getConstant(LHS->getType(), 1);
04031           const SCEV *LS = getSCEV(LHS);
04032           const SCEV *LA = getSCEV(U->getOperand(1));
04033           const SCEV *RA = getSCEV(U->getOperand(2));
04034           const SCEV *LDiff = getMinusSCEV(LA, LS);
04035           const SCEV *RDiff = getMinusSCEV(RA, One);
04036           if (LDiff == RDiff)
04037             return getAddExpr(getUMaxExpr(One, LS), LDiff);
04038         }
04039         break;
04040       case ICmpInst::ICMP_EQ:
04041         // n == 0 ? 1+x : n+x  ->  umax(n, 1)+x
04042         if (LHS->getType() == U->getType() &&
04043             isa<ConstantInt>(RHS) &&
04044             cast<ConstantInt>(RHS)->isZero()) {
04045           const SCEV *One = getConstant(LHS->getType(), 1);
04046           const SCEV *LS = getSCEV(LHS);
04047           const SCEV *LA = getSCEV(U->getOperand(1));
04048           const SCEV *RA = getSCEV(U->getOperand(2));
04049           const SCEV *LDiff = getMinusSCEV(LA, One);
04050           const SCEV *RDiff = getMinusSCEV(RA, LS);
04051           if (LDiff == RDiff)
04052             return getAddExpr(getUMaxExpr(One, LS), LDiff);
04053         }
04054         break;
04055       default:
04056         break;
04057       }
04058     }
04059 
04060   default: // We cannot analyze this expression.
04061     break;
04062   }
04063 
04064   return getUnknown(V);
04065 }
04066 
04067 
04068 
04069 //===----------------------------------------------------------------------===//
04070 //                   Iteration Count Computation Code
04071 //
04072 
04073 /// getSmallConstantTripCount - Returns the maximum trip count of this loop as a
04074 /// normal unsigned value. Returns 0 if the trip count is unknown or not
04075 /// constant. Will also return 0 if the maximum trip count is very large (>=
04076 /// 2^32).
04077 ///
04078 /// This "trip count" assumes that control exits via ExitingBlock. More
04079 /// precisely, it is the number of times that control may reach ExitingBlock
04080 /// before taking the branch. For loops with multiple exits, it may not be the
04081 /// number times that the loop header executes because the loop may exit
04082 /// prematurely via another branch.
04083 ///
04084 /// FIXME: We conservatively call getBackedgeTakenCount(L) instead of
04085 /// getExitCount(L, ExitingBlock) to compute a safe trip count considering all
04086 /// loop exits. getExitCount() may return an exact count for this branch
04087 /// assuming no-signed-wrap. The number of well-defined iterations may actually
04088 /// be higher than this trip count if this exit test is skipped and the loop
04089 /// exits via a different branch. Ideally, getExitCount() would know whether it
04090 /// depends on a NSW assumption, and we would only fall back to a conservative
04091 /// trip count in that case.
04092 unsigned ScalarEvolution::
04093 getSmallConstantTripCount(Loop *L, BasicBlock * /*ExitingBlock*/) {
04094   const SCEVConstant *ExitCount =
04095     dyn_cast<SCEVConstant>(getBackedgeTakenCount(L));
04096   if (!ExitCount)
04097     return 0;
04098 
04099   ConstantInt *ExitConst = ExitCount->getValue();
04100 
04101   // Guard against huge trip counts.
04102   if (ExitConst->getValue().getActiveBits() > 32)
04103     return 0;
04104 
04105   // In case of integer overflow, this returns 0, which is correct.
04106   return ((unsigned)ExitConst->getZExtValue()) + 1;
04107 }
04108 
04109 /// getSmallConstantTripMultiple - Returns the largest constant divisor of the
04110 /// trip count of this loop as a normal unsigned value, if possible. This
04111 /// means that the actual trip count is always a multiple of the returned
04112 /// value (don't forget the trip count could very well be zero as well!).
04113 ///
04114 /// Returns 1 if the trip count is unknown or not guaranteed to be the
04115 /// multiple of a constant (which is also the case if the trip count is simply
04116 /// constant, use getSmallConstantTripCount for that case), Will also return 1
04117 /// if the trip count is very large (>= 2^32).
04118 ///
04119 /// As explained in the comments for getSmallConstantTripCount, this assumes
04120 /// that control exits the loop via ExitingBlock.
04121 unsigned ScalarEvolution::
04122 getSmallConstantTripMultiple(Loop *L, BasicBlock * /*ExitingBlock*/) {
04123   const SCEV *ExitCount = getBackedgeTakenCount(L);
04124   if (ExitCount == getCouldNotCompute())
04125     return 1;
04126 
04127   // Get the trip count from the BE count by adding 1.
04128   const SCEV *TCMul = getAddExpr(ExitCount,
04129                                  getConstant(ExitCount->getType(), 1));
04130   // FIXME: SCEV distributes multiplication as V1*C1 + V2*C1. We could attempt
04131   // to factor simple cases.
04132   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(TCMul))
04133     TCMul = Mul->getOperand(0);
04134 
04135   const SCEVConstant *MulC = dyn_cast<SCEVConstant>(TCMul);
04136   if (!MulC)
04137     return 1;
04138 
04139   ConstantInt *Result = MulC->getValue();
04140 
04141   // Guard against huge trip counts (this requires checking
04142   // for zero to handle the case where the trip count == -1 and the
04143   // addition wraps).
04144   if (!Result || Result->getValue().getActiveBits() > 32 ||
04145       Result->getValue().getActiveBits() == 0)
04146     return 1;
04147 
04148   return (unsigned)Result->getZExtValue();
04149 }
04150 
04151 // getExitCount - Get the expression for the number of loop iterations for which
04152 // this loop is guaranteed not to exit via ExitingBlock. Otherwise return
04153 // SCEVCouldNotCompute.
04154 const SCEV *ScalarEvolution::getExitCount(Loop *L, BasicBlock *ExitingBlock) {
04155   return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
04156 }
04157 
04158 /// getBackedgeTakenCount - If the specified loop has a predictable
04159 /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
04160 /// object. The backedge-taken count is the number of times the loop header
04161 /// will be branched to from within the loop. This is one less than the
04162 /// trip count of the loop, since it doesn't count the first iteration,
04163 /// when the header is branched to from outside the loop.
04164 ///
04165 /// Note that it is not valid to call this method on a loop without a
04166 /// loop-invariant backedge-taken count (see
04167 /// hasLoopInvariantBackedgeTakenCount).
04168 ///
04169 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
04170   return getBackedgeTakenInfo(L).getExact(this);
04171 }
04172 
04173 /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
04174 /// return the least SCEV value that is known never to be less than the
04175 /// actual backedge taken count.
04176 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
04177   return getBackedgeTakenInfo(L).getMax(this);
04178 }
04179 
04180 /// PushLoopPHIs - Push PHI nodes in the header of the given loop
04181 /// onto the given Worklist.
04182 static void
04183 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
04184   BasicBlock *Header = L->getHeader();
04185 
04186   // Push all Loop-header PHIs onto the Worklist stack.
04187   for (BasicBlock::iterator I = Header->begin();
04188        PHINode *PN = dyn_cast<PHINode>(I); ++I)
04189     Worklist.push_back(PN);
04190 }
04191 
04192 const ScalarEvolution::BackedgeTakenInfo &
04193 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
04194   // Initially insert an invalid entry for this loop. If the insertion
04195   // succeeds, proceed to actually compute a backedge-taken count and
04196   // update the value. The temporary CouldNotCompute value tells SCEV
04197   // code elsewhere that it shouldn't attempt to request a new
04198   // backedge-taken count, which could result in infinite recursion.
04199   std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
04200     BackedgeTakenCounts.insert(std::make_pair(L, BackedgeTakenInfo()));
04201   if (!Pair.second)
04202     return Pair.first->second;
04203 
04204   // ComputeBackedgeTakenCount may allocate memory for its result. Inserting it
04205   // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
04206   // must be cleared in this scope.
04207   BackedgeTakenInfo Result = ComputeBackedgeTakenCount(L);
04208 
04209   if (Result.getExact(this) != getCouldNotCompute()) {
04210     assert(isLoopInvariant(Result.getExact(this), L) &&
04211            isLoopInvariant(Result.getMax(this), L) &&
04212            "Computed backedge-taken count isn't loop invariant for loop!");
04213     ++NumTripCountsComputed;
04214   }
04215   else if (Result.getMax(this) == getCouldNotCompute() &&
04216            isa<PHINode>(L->getHeader()->begin())) {
04217     // Only count loops that have phi nodes as not being computable.
04218     ++NumTripCountsNotComputed;
04219   }
04220 
04221   // Now that we know more about the trip count for this loop, forget any
04222   // existing SCEV values for PHI nodes in this loop since they are only
04223   // conservative estimates made without the benefit of trip count
04224   // information. This is similar to the code in forgetLoop, except that
04225   // it handles SCEVUnknown PHI nodes specially.
04226   if (Result.hasAnyInfo()) {
04227     SmallVector<Instruction *, 16> Worklist;
04228     PushLoopPHIs(L, Worklist);
04229 
04230     SmallPtrSet<Instruction *, 8> Visited;
04231     while (!Worklist.empty()) {
04232       Instruction *I = Worklist.pop_back_val();
04233       if (!Visited.insert(I)) continue;
04234 
04235       ValueExprMapType::iterator It =
04236         ValueExprMap.find_as(static_cast<Value *>(I));
04237       if (It != ValueExprMap.end()) {
04238         const SCEV *Old = It->second;
04239 
04240         // SCEVUnknown for a PHI either means that it has an unrecognized
04241         // structure, or it's a PHI that's in the progress of being computed
04242         // by createNodeForPHI.  In the former case, additional loop trip
04243         // count information isn't going to change anything. In the later
04244         // case, createNodeForPHI will perform the necessary updates on its
04245         // own when it gets to that point.
04246         if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
04247           forgetMemoizedResults(Old);
04248           ValueExprMap.erase(It);
04249         }
04250         if (PHINode *PN = dyn_cast<PHINode>(I))
04251           ConstantEvolutionLoopExitValue.erase(PN);
04252       }
04253 
04254       PushDefUseChildren(I, Worklist);
04255     }
04256   }
04257 
04258   // Re-lookup the insert position, since the call to
04259   // ComputeBackedgeTakenCount above could result in a
04260   // recusive call to getBackedgeTakenInfo (on a different
04261   // loop), which would invalidate the iterator computed
04262   // earlier.
04263   return BackedgeTakenCounts.find(L)->second = Result;
04264 }
04265 
04266 /// forgetLoop - This method should be called by the client when it has
04267 /// changed a loop in a way that may effect ScalarEvolution's ability to
04268 /// compute a trip count, or if the loop is deleted.
04269 void ScalarEvolution::forgetLoop(const Loop *L) {
04270   // Drop any stored trip count value.
04271   DenseMap<const Loop*, BackedgeTakenInfo>::iterator BTCPos =
04272     BackedgeTakenCounts.find(L);
04273   if (BTCPos != BackedgeTakenCounts.end()) {
04274     BTCPos->second.clear();
04275     BackedgeTakenCounts.erase(BTCPos);
04276   }
04277 
04278   // Drop information about expressions based on loop-header PHIs.
04279   SmallVector<Instruction *, 16> Worklist;
04280   PushLoopPHIs(L, Worklist);
04281 
04282   SmallPtrSet<Instruction *, 8> Visited;
04283   while (!Worklist.empty()) {
04284     Instruction *I = Worklist.pop_back_val();
04285     if (!Visited.insert(I)) continue;
04286 
04287     ValueExprMapType::iterator It =
04288       ValueExprMap.find_as(static_cast<Value *>(I));
04289     if (It != ValueExprMap.end()) {
04290       forgetMemoizedResults(It->second);
04291       ValueExprMap.erase(It);
04292       if (PHINode *PN = dyn_cast<PHINode>(I))
04293         ConstantEvolutionLoopExitValue.erase(PN);
04294     }
04295 
04296     PushDefUseChildren(I, Worklist);
04297   }
04298 
04299   // Forget all contained loops too, to avoid dangling entries in the
04300   // ValuesAtScopes map.
04301   for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
04302     forgetLoop(*I);
04303 }
04304 
04305 /// forgetValue - This method should be called by the client when it has
04306 /// changed a value in a way that may effect its value, or which may
04307 /// disconnect it from a def-use chain linking it to a loop.
04308 void ScalarEvolution::forgetValue(Value *V) {
04309   Instruction *I = dyn_cast<Instruction>(V);
04310   if (!I) return;
04311 
04312   // Drop information about expressions based on loop-header PHIs.
04313   SmallVector<Instruction *, 16> Worklist;
04314   Worklist.push_back(I);
04315 
04316   SmallPtrSet<Instruction *, 8> Visited;
04317   while (!Worklist.empty()) {
04318     I = Worklist.pop_back_val();
04319     if (!Visited.insert(I)) continue;
04320 
04321     ValueExprMapType::iterator It =
04322       ValueExprMap.find_as(static_cast<Value *>(I));
04323     if (It != ValueExprMap.end()) {
04324       forgetMemoizedResults(It->second);
04325       ValueExprMap.erase(It);
04326       if (PHINode *PN = dyn_cast<PHINode>(I))
04327         ConstantEvolutionLoopExitValue.erase(PN);
04328     }
04329 
04330     PushDefUseChildren(I, Worklist);
04331   }
04332 }
04333 
04334 /// getExact - Get the exact loop backedge taken count considering all loop
04335 /// exits. A computable result can only be return for loops with a single exit.
04336 /// Returning the minimum taken count among all exits is incorrect because one
04337 /// of the loop's exit limit's may have been skipped. HowFarToZero assumes that
04338 /// the limit of each loop test is never skipped. This is a valid assumption as
04339 /// long as the loop exits via that test. For precise results, it is the
04340 /// caller's responsibility to specify the relevant loop exit using
04341 /// getExact(ExitingBlock, SE).
04342 const SCEV *
04343 ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE) const {
04344   // If any exits were not computable, the loop is not computable.
04345   if (!ExitNotTaken.isCompleteList()) return SE->getCouldNotCompute();
04346 
04347   // We need exactly one computable exit.
04348   if (!ExitNotTaken.ExitingBlock) return SE->getCouldNotCompute();
04349   assert(ExitNotTaken.ExactNotTaken && "uninitialized not-taken info");
04350 
04351   const SCEV *BECount = nullptr;
04352   for (const ExitNotTakenInfo *ENT = &ExitNotTaken;
04353        ENT != nullptr; ENT = ENT->getNextExit()) {
04354 
04355     assert(ENT->ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV");
04356 
04357     if (!BECount)
04358       BECount = ENT->ExactNotTaken;
04359     else if (BECount != ENT->ExactNotTaken)
04360       return SE->getCouldNotCompute();
04361   }
04362   assert(BECount && "Invalid not taken count for loop exit");
04363   return BECount;
04364 }
04365 
04366 /// getExact - Get the exact not taken count for this loop exit.
04367 const SCEV *
04368 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock,
04369                                              ScalarEvolution *SE) const {
04370   for (const ExitNotTakenInfo *ENT = &ExitNotTaken;
04371        ENT != nullptr; ENT = ENT->getNextExit()) {
04372 
04373     if (ENT->ExitingBlock == ExitingBlock)
04374       return ENT->ExactNotTaken;
04375   }
04376   return SE->getCouldNotCompute();
04377 }
04378 
04379 /// getMax - Get the max backedge taken count for the loop.
04380 const SCEV *
04381 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const {
04382   return Max ? Max : SE->getCouldNotCompute();
04383 }
04384 
04385 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S,
04386                                                     ScalarEvolution *SE) const {
04387   if (Max && Max != SE->getCouldNotCompute() && SE->hasOperand(Max, S))
04388     return true;
04389 
04390   if (!ExitNotTaken.ExitingBlock)
04391     return false;
04392 
04393   for (const ExitNotTakenInfo *ENT = &ExitNotTaken;
04394        ENT != nullptr; ENT = ENT->getNextExit()) {
04395 
04396     if (ENT->ExactNotTaken != SE->getCouldNotCompute()
04397         && SE->hasOperand(ENT->ExactNotTaken, S)) {
04398       return true;
04399     }
04400   }
04401   return false;
04402 }
04403 
04404 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
04405 /// computable exit into a persistent ExitNotTakenInfo array.
04406 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
04407   SmallVectorImpl< std::pair<BasicBlock *, const SCEV *> > &ExitCounts,
04408   bool Complete, const SCEV *MaxCount) : Max(MaxCount) {
04409 
04410   if (!Complete)
04411     ExitNotTaken.setIncomplete();
04412 
04413   unsigned NumExits = ExitCounts.size();
04414   if (NumExits == 0) return;
04415 
04416   ExitNotTaken.ExitingBlock = ExitCounts[0].first;
04417   ExitNotTaken.ExactNotTaken = ExitCounts[0].second;
04418   if (NumExits == 1) return;
04419 
04420   // Handle the rare case of multiple computable exits.
04421   ExitNotTakenInfo *ENT = new ExitNotTakenInfo[NumExits-1];
04422 
04423   ExitNotTakenInfo *PrevENT = &ExitNotTaken;
04424   for (unsigned i = 1; i < NumExits; ++i, PrevENT = ENT, ++ENT) {
04425     PrevENT->setNextExit(ENT);
04426     ENT->ExitingBlock = ExitCounts[i].first;
04427     ENT->ExactNotTaken = ExitCounts[i].second;
04428   }
04429 }
04430 
04431 /// clear - Invalidate this result and free the ExitNotTakenInfo array.
04432 void ScalarEvolution::BackedgeTakenInfo::clear() {
04433   ExitNotTaken.ExitingBlock = nullptr;
04434   ExitNotTaken.ExactNotTaken = nullptr;
04435   delete[] ExitNotTaken.getNextExit();
04436 }
04437 
04438 /// ComputeBackedgeTakenCount - Compute the number of times the backedge
04439 /// of the specified loop will execute.
04440 ScalarEvolution::BackedgeTakenInfo
04441 ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
04442   SmallVector<BasicBlock *, 8> ExitingBlocks;
04443   L->getExitingBlocks(ExitingBlocks);
04444 
04445   SmallVector<std::pair<BasicBlock *, const SCEV *>, 4> ExitCounts;
04446   bool CouldComputeBECount = true;
04447   BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
04448   const SCEV *MustExitMaxBECount = nullptr;
04449   const SCEV *MayExitMaxBECount = nullptr;
04450 
04451   // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
04452   // and compute maxBECount.
04453   for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
04454     BasicBlock *ExitBB = ExitingBlocks[i];
04455     ExitLimit EL = ComputeExitLimit(L, ExitBB);
04456 
04457     // 1. For each exit that can be computed, add an entry to ExitCounts.
04458     // CouldComputeBECount is true only if all exits can be computed.
04459     if (EL.Exact == getCouldNotCompute())
04460       // We couldn't compute an exact value for this exit, so
04461       // we won't be able to compute an exact value for the loop.
04462       CouldComputeBECount = false;
04463     else
04464       ExitCounts.push_back(std::make_pair(ExitBB, EL.Exact));
04465 
04466     // 2. Derive the loop's MaxBECount from each exit's max number of
04467     // non-exiting iterations. Partition the loop exits into two kinds:
04468     // LoopMustExits and LoopMayExits.
04469     //
04470     // A LoopMustExit meets two requirements:
04471     //
04472     // (a) Its ExitLimit.MustExit flag must be set which indicates that the exit
04473     // test condition cannot be skipped (the tested variable has unit stride or
04474     // the test is less-than or greater-than, rather than a strict inequality).
04475     //
04476     // (b) It must dominate the loop latch, hence must be tested on every loop
04477     // iteration.
04478     //
04479     // If any computable LoopMustExit is found, then MaxBECount is the minimum
04480     // EL.Max of computable LoopMustExits. Otherwise, MaxBECount is
04481     // conservatively the maximum EL.Max, where CouldNotCompute is considered
04482     // greater than any computable EL.Max.
04483     if (EL.MustExit && EL.Max != getCouldNotCompute() && Latch &&
04484         DT->dominates(ExitBB, Latch)) {
04485       if (!MustExitMaxBECount)
04486         MustExitMaxBECount = EL.Max;
04487       else {
04488         MustExitMaxBECount =
04489           getUMinFromMismatchedTypes(MustExitMaxBECount, EL.Max);
04490       }
04491     } else if (MayExitMaxBECount != getCouldNotCompute()) {
04492       if (!MayExitMaxBECount || EL.Max == getCouldNotCompute())
04493         MayExitMaxBECount = EL.Max;
04494       else {
04495         MayExitMaxBECount =
04496           getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.Max);
04497       }
04498     }
04499   }
04500   const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
04501     (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
04502   return BackedgeTakenInfo(ExitCounts, CouldComputeBECount, MaxBECount);
04503 }
04504 
04505 /// ComputeExitLimit - Compute the number of times the backedge of the specified
04506 /// loop will execute if it exits via the specified block.
04507 ScalarEvolution::ExitLimit
04508 ScalarEvolution::ComputeExitLimit(const Loop *L, BasicBlock *ExitingBlock) {
04509 
04510   // Okay, we've chosen an exiting block.  See what condition causes us to
04511   // exit at this block and remember the exit block and whether all other targets
04512   // lead to the loop header.
04513   bool MustExecuteLoopHeader = true;
04514   BasicBlock *Exit = nullptr;
04515   for (succ_iterator SI = succ_begin(ExitingBlock), SE = succ_end(ExitingBlock);
04516        SI != SE; ++SI)
04517     if (!L->contains(*SI)) {
04518       if (Exit) // Multiple exit successors.
04519         return getCouldNotCompute();
04520       Exit = *SI;
04521     } else if (*SI != L->getHeader()) {
04522       MustExecuteLoopHeader = false;
04523     }
04524 
04525   // At this point, we know we have a conditional branch that determines whether
04526   // the loop is exited.  However, we don't know if the branch is executed each
04527   // time through the loop.  If not, then the execution count of the branch will
04528   // not be equal to the trip count of the loop.
04529   //
04530   // Currently we check for this by checking to see if the Exit branch goes to
04531   // the loop header.  If so, we know it will always execute the same number of
04532   // times as the loop.  We also handle the case where the exit block *is* the
04533   // loop header.  This is common for un-rotated loops.
04534   //
04535   // If both of those tests fail, walk up the unique predecessor chain to the
04536   // header, stopping if there is an edge that doesn't exit the loop. If the
04537   // header is reached, the execution count of the branch will be equal to the
04538   // trip count of the loop.
04539   //
04540   //  More extensive analysis could be done to handle more cases here.
04541   //
04542   if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) {
04543     // The simple checks failed, try climbing the unique predecessor chain
04544     // up to the header.
04545     bool Ok = false;
04546     for (BasicBlock *BB = ExitingBlock; BB; ) {
04547       BasicBlock *Pred = BB->getUniquePredecessor();
04548       if (!Pred)
04549         return getCouldNotCompute();
04550       TerminatorInst *PredTerm = Pred->getTerminator();
04551       for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
04552         BasicBlock *PredSucc = PredTerm->getSuccessor(i);
04553         if (PredSucc == BB)
04554           continue;
04555         // If the predecessor has a successor that isn't BB and isn't
04556         // outside the loop, assume the worst.
04557         if (L->contains(PredSucc))
04558           return getCouldNotCompute();
04559       }
04560       if (Pred == L->getHeader()) {
04561         Ok = true;
04562         break;
04563       }
04564       BB = Pred;
04565     }
04566     if (!Ok)
04567       return getCouldNotCompute();
04568   }
04569 
04570   TerminatorInst *Term = ExitingBlock->getTerminator();
04571   if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
04572     assert(BI->isConditional() && "If unconditional, it can't be in loop!");
04573     // Proceed to the next level to examine the exit condition expression.
04574     return ComputeExitLimitFromCond(L, BI->getCondition(), BI->getSuccessor(0),
04575                                     BI->getSuccessor(1),
04576                                     /*IsSubExpr=*/false);
04577   }
04578 
04579   if (SwitchInst *SI = dyn_cast<SwitchInst>(Term))
04580     return ComputeExitLimitFromSingleExitSwitch(L, SI, Exit,
04581                                                 /*IsSubExpr=*/false);
04582 
04583   return getCouldNotCompute();
04584 }
04585 
04586 /// ComputeExitLimitFromCond - Compute the number of times the
04587 /// backedge of the specified loop will execute if its exit condition
04588 /// were a conditional branch of ExitCond, TBB, and FBB.
04589 ///
04590 /// @param IsSubExpr is true if ExitCond does not directly control the exit
04591 /// branch. In this case, we cannot assume that the loop only exits when the
04592 /// condition is true and cannot infer that failing to meet the condition prior
04593 /// to integer wraparound results in undefined behavior.
04594 ScalarEvolution::ExitLimit
04595 ScalarEvolution::ComputeExitLimitFromCond(const Loop *L,
04596                                           Value *ExitCond,
04597                                           BasicBlock *TBB,
04598                                           BasicBlock *FBB,
04599                                           bool IsSubExpr) {
04600   // Check if the controlling expression for this loop is an And or Or.
04601   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
04602     if (BO->getOpcode() == Instruction::And) {
04603       // Recurse on the operands of the and.
04604       bool EitherMayExit = L->contains(TBB);
04605       ExitLimit EL0 = ComputeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB,
04606                                                IsSubExpr || EitherMayExit);
04607       ExitLimit EL1 = ComputeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB,
04608                                                IsSubExpr || EitherMayExit);
04609       const SCEV *BECount = getCouldNotCompute();
04610       const SCEV *MaxBECount = getCouldNotCompute();
04611       bool MustExit = false;
04612       if (EitherMayExit) {
04613         // Both conditions must be true for the loop to continue executing.
04614         // Choose the less conservative count.
04615         if (EL0.Exact == getCouldNotCompute() ||
04616             EL1.Exact == getCouldNotCompute())
04617           BECount = getCouldNotCompute();
04618         else
04619           BECount = getUMinFromMismatchedTypes(EL0.Exact, EL1.Exact);
04620         if (EL0.Max == getCouldNotCompute())
04621           MaxBECount = EL1.Max;
04622         else if (EL1.Max == getCouldNotCompute())
04623           MaxBECount = EL0.Max;
04624         else
04625           MaxBECount = getUMinFromMismatchedTypes(EL0.Max, EL1.Max);
04626         MustExit = EL0.MustExit || EL1.MustExit;
04627       } else {
04628         // Both conditions must be true at the same time for the loop to exit.
04629         // For now, be conservative.
04630         assert(L->contains(FBB) && "Loop block has no successor in loop!");
04631         if (EL0.Max == EL1.Max)
04632           MaxBECount = EL0.Max;
04633         if (EL0.Exact == EL1.Exact)
04634           BECount = EL0.Exact;
04635         MustExit = EL0.MustExit && EL1.MustExit;
04636       }
04637 
04638       return ExitLimit(BECount, MaxBECount, MustExit);
04639     }
04640     if (BO->getOpcode() == Instruction::Or) {
04641       // Recurse on the operands of the or.
04642       bool EitherMayExit = L->contains(FBB);
04643       ExitLimit EL0 = ComputeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB,
04644                                                IsSubExpr || EitherMayExit);
04645       ExitLimit EL1 = ComputeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB,
04646                                                IsSubExpr || EitherMayExit);
04647       const SCEV *BECount = getCouldNotCompute();
04648       const SCEV *MaxBECount = getCouldNotCompute();
04649       bool MustExit = false;
04650       if (EitherMayExit) {
04651         // Both conditions must be false for the loop to continue executing.
04652         // Choose the less conservative count.
04653         if (EL0.Exact == getCouldNotCompute() ||
04654             EL1.Exact == getCouldNotCompute())
04655           BECount = getCouldNotCompute();
04656         else
04657           BECount = getUMinFromMismatchedTypes(EL0.Exact, EL1.Exact);
04658         if (EL0.Max == getCouldNotCompute())
04659           MaxBECount = EL1.Max;
04660         else if (EL1.Max == getCouldNotCompute())
04661           MaxBECount = EL0.Max;
04662         else
04663           MaxBECount = getUMinFromMismatchedTypes(EL0.Max, EL1.Max);
04664         MustExit = EL0.MustExit || EL1.MustExit;
04665       } else {
04666         // Both conditions must be false at the same time for the loop to exit.
04667         // For now, be conservative.
04668         assert(L->contains(TBB) && "Loop block has no successor in loop!");
04669         if (EL0.Max == EL1.Max)
04670           MaxBECount = EL0.Max;
04671         if (EL0.Exact == EL1.Exact)
04672           BECount = EL0.Exact;
04673         MustExit = EL0.MustExit && EL1.MustExit;
04674       }
04675 
04676       return ExitLimit(BECount, MaxBECount, MustExit);
04677     }
04678   }
04679 
04680   // With an icmp, it may be feasible to compute an exact backedge-taken count.
04681   // Proceed to the next level to examine the icmp.
04682   if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
04683     return ComputeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, IsSubExpr);
04684 
04685   // Check for a constant condition. These are normally stripped out by
04686   // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
04687   // preserve the CFG and is temporarily leaving constant conditions
04688   // in place.
04689   if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
04690     if (L->contains(FBB) == !CI->getZExtValue())
04691       // The backedge is always taken.
04692       return getCouldNotCompute();
04693     else
04694       // The backedge is never taken.
04695       return getConstant(CI->getType(), 0);
04696   }
04697 
04698   // If it's not an integer or pointer comparison then compute it the hard way.
04699   return ComputeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
04700 }
04701 
04702 /// ComputeExitLimitFromICmp - Compute the number of times the
04703 /// backedge of the specified loop will execute if its exit condition
04704 /// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
04705 ScalarEvolution::ExitLimit
04706 ScalarEvolution::ComputeExitLimitFromICmp(const Loop *L,
04707                                           ICmpInst *ExitCond,
04708                                           BasicBlock *TBB,
04709                                           BasicBlock *FBB,
04710                                           bool IsSubExpr) {
04711 
04712   // If the condition was exit on true, convert the condition to exit on false
04713   ICmpInst::Predicate Cond;
04714   if (!L->contains(FBB))
04715     Cond = ExitCond->getPredicate();
04716   else
04717     Cond = ExitCond->getInversePredicate();
04718 
04719   // Handle common loops like: for (X = "string"; *X; ++X)
04720   if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
04721     if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
04722       ExitLimit ItCnt =
04723         ComputeLoadConstantCompareExitLimit(LI, RHS, L, Cond);
04724       if (ItCnt.hasAnyInfo())
04725         return ItCnt;
04726     }
04727 
04728   const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
04729   const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
04730 
04731   // Try to evaluate any dependencies out of the loop.
04732   LHS = getSCEVAtScope(LHS, L);
04733   RHS = getSCEVAtScope(RHS, L);
04734 
04735   // At this point, we would like to compute how many iterations of the
04736   // loop the predicate will return true for these inputs.
04737   if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
04738     // If there is a loop-invariant, force it into the RHS.
04739     std::swap(LHS, RHS);
04740     Cond = ICmpInst::getSwappedPredicate(Cond);
04741   }
04742 
04743   // Simplify the operands before analyzing them.
04744   (void)SimplifyICmpOperands(Cond, LHS, RHS);
04745 
04746   // If we have a comparison of a chrec against a constant, try to use value
04747   // ranges to answer this query.
04748   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
04749     if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
04750       if (AddRec->getLoop() == L) {
04751         // Form the constant range.
04752         ConstantRange CompRange(
04753             ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
04754 
04755         const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
04756         if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
04757       }
04758 
04759   switch (Cond) {
04760   case ICmpInst::ICMP_NE: {                     // while (X != Y)
04761     // Convert to: while (X-Y != 0)
04762     ExitLimit EL = HowFarToZero(getMinusSCEV(LHS, RHS), L, IsSubExpr);
04763     if (EL.hasAnyInfo()) return EL;
04764     break;
04765   }
04766   case ICmpInst::ICMP_EQ: {                     // while (X == Y)
04767     // Convert to: while (X-Y == 0)
04768     ExitLimit EL = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
04769     if (EL.hasAnyInfo()) return EL;
04770     break;
04771   }
04772   case ICmpInst::ICMP_SLT:
04773   case ICmpInst::ICMP_ULT: {                    // while (X < Y)
04774     bool IsSigned = Cond == ICmpInst::ICMP_SLT;
04775     ExitLimit EL = HowManyLessThans(LHS, RHS, L, IsSigned, IsSubExpr);
04776     if (EL.hasAnyInfo()) return EL;
04777     break;
04778   }
04779   case ICmpInst::ICMP_SGT:
04780   case ICmpInst::ICMP_UGT: {                    // while (X > Y)
04781     bool IsSigned = Cond == ICmpInst::ICMP_SGT;
04782     ExitLimit EL = HowManyGreaterThans(LHS, RHS, L, IsSigned, IsSubExpr);
04783     if (EL.hasAnyInfo()) return EL;
04784     break;
04785   }
04786   default:
04787 #if 0
04788     dbgs() << "ComputeBackedgeTakenCount ";
04789     if (ExitCond->getOperand(0)->getType()->isUnsigned())
04790       dbgs() << "[unsigned] ";
04791     dbgs() << *LHS << "   "
04792          << Instruction::getOpcodeName(Instruction::ICmp)
04793          << "   " << *RHS << "\n";
04794 #endif
04795     break;
04796   }
04797   return ComputeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
04798 }
04799 
04800 ScalarEvolution::ExitLimit
04801 ScalarEvolution::ComputeExitLimitFromSingleExitSwitch(const Loop *L,
04802                                                       SwitchInst *Switch,
04803                                                       BasicBlock *ExitingBlock,
04804                                                       bool IsSubExpr) {
04805   assert(!L->contains(ExitingBlock) && "Not an exiting block!");
04806 
04807   // Give up if the exit is the default dest of a switch.
04808   if (Switch->getDefaultDest() == ExitingBlock)
04809     return getCouldNotCompute();
04810 
04811   assert(L->contains(Switch->getDefaultDest()) &&
04812          "Default case must not exit the loop!");
04813   const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
04814   const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
04815 
04816   // while (X != Y) --> while (X-Y != 0)
04817   ExitLimit EL = HowFarToZero(getMinusSCEV(LHS, RHS), L, IsSubExpr);
04818   if (EL.hasAnyInfo())
04819     return EL;
04820 
04821   return getCouldNotCompute();
04822 }
04823 
04824 static ConstantInt *
04825 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
04826                                 ScalarEvolution &SE) {
04827   const SCEV *InVal = SE.getConstant(C);
04828   const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
04829   assert(isa<SCEVConstant>(Val) &&
04830          "Evaluation of SCEV at constant didn't fold correctly?");
04831   return cast<SCEVConstant>(Val)->getValue();
04832 }
04833 
04834 /// ComputeLoadConstantCompareExitLimit - Given an exit condition of
04835 /// 'icmp op load X, cst', try to see if we can compute the backedge
04836 /// execution count.
04837 ScalarEvolution::ExitLimit
04838 ScalarEvolution::ComputeLoadConstantCompareExitLimit(
04839   LoadInst *LI,
04840   Constant *RHS,
04841   const Loop *L,
04842   ICmpInst::Predicate predicate) {
04843 
04844   if (LI->isVolatile()) return getCouldNotCompute();
04845 
04846   // Check to see if the loaded pointer is a getelementptr of a global.
04847   // TODO: Use SCEV instead of manually grubbing with GEPs.
04848   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
04849   if (!GEP) return getCouldNotCompute();
04850 
04851   // Make sure that it is really a constant global we are gepping, with an
04852   // initializer, and make sure the first IDX is really 0.
04853   GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
04854   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
04855       GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
04856       !cast<Constant>(GEP->getOperand(1))->isNullValue())
04857     return getCouldNotCompute();
04858 
04859   // Okay, we allow one non-constant index into the GEP instruction.
04860   Value *VarIdx = nullptr;
04861   std::vector<Constant*> Indexes;
04862   unsigned VarIdxNum = 0;
04863   for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
04864     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
04865       Indexes.push_back(CI);
04866     } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
04867       if (VarIdx) return getCouldNotCompute();  // Multiple non-constant idx's.
04868       VarIdx = GEP->getOperand(i);
04869       VarIdxNum = i-2;
04870       Indexes.push_back(nullptr);
04871     }
04872 
04873   // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
04874   if (!VarIdx)
04875     return getCouldNotCompute();
04876 
04877   // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
04878   // Check to see if X is a loop variant variable value now.
04879   const SCEV *Idx = getSCEV(VarIdx);
04880   Idx = getSCEVAtScope(Idx, L);
04881 
04882   // We can only recognize very limited forms of loop index expressions, in
04883   // particular, only affine AddRec's like {C1,+,C2}.
04884   const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
04885   if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
04886       !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
04887       !isa<SCEVConstant>(IdxExpr->getOperand(1)))
04888     return getCouldNotCompute();
04889 
04890   unsigned MaxSteps = MaxBruteForceIterations;
04891   for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
04892     ConstantInt *ItCst = ConstantInt::get(
04893                            cast<IntegerType>(IdxExpr->getType()), IterationNum);
04894     ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
04895 
04896     // Form the GEP offset.
04897     Indexes[VarIdxNum] = Val;
04898 
04899     Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
04900                                                          Indexes);
04901     if (!Result) break;  // Cannot compute!
04902 
04903     // Evaluate the condition for this iteration.
04904     Result = ConstantExpr::getICmp(predicate, Result, RHS);
04905     if (!isa<ConstantInt>(Result)) break;  // Couldn't decide for sure
04906     if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
04907 #if 0
04908       dbgs() << "\n***\n*** Computed loop count " << *ItCst
04909              << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
04910              << "***\n";
04911 #endif
04912       ++NumArrayLenItCounts;
04913       return getConstant(ItCst);   // Found terminating iteration!
04914     }
04915   }
04916   return getCouldNotCompute();
04917 }
04918 
04919 
04920 /// CanConstantFold - Return true if we can constant fold an instruction of the
04921 /// specified type, assuming that all operands were constants.
04922 static bool CanConstantFold(const Instruction *I) {
04923   if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
04924       isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
04925       isa<LoadInst>(I))
04926     return true;
04927 
04928   if (const CallInst *CI = dyn_cast<CallInst>(I))
04929     if (const Function *F = CI->getCalledFunction())
04930       return canConstantFoldCallTo(F);
04931   return false;
04932 }
04933 
04934 /// Determine whether this instruction can constant evolve within this loop
04935 /// assuming its operands can all constant evolve.
04936 static bool canConstantEvolve(Instruction *I, const Loop *L) {
04937   // An instruction outside of the loop can't be derived from a loop PHI.
04938   if (!L->contains(I)) return false;
04939 
04940   if (isa<PHINode>(I)) {
04941     if (L->getHeader() == I->getParent())
04942       return true;
04943     else
04944       // We don't currently keep track of the control flow needed to evaluate
04945       // PHIs, so we cannot handle PHIs inside of loops.
04946       return false;
04947   }
04948 
04949   // If we won't be able to constant fold this expression even if the operands
04950   // are constants, bail early.
04951   return CanConstantFold(I);
04952 }
04953 
04954 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
04955 /// recursing through each instruction operand until reaching a loop header phi.
04956 static PHINode *
04957 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
04958                                DenseMap<Instruction *, PHINode *> &PHIMap) {
04959 
04960   // Otherwise, we can evaluate this instruction if all of its operands are
04961   // constant or derived from a PHI node themselves.
04962   PHINode *PHI = nullptr;
04963   for (Instruction::op_iterator OpI = UseInst->op_begin(),
04964          OpE = UseInst->op_end(); OpI != OpE; ++OpI) {
04965 
04966     if (isa<Constant>(*OpI)) continue;
04967 
04968     Instruction *OpInst = dyn_cast<Instruction>(*OpI);
04969     if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
04970 
04971     PHINode *P = dyn_cast<PHINode>(OpInst);
04972     if (!P)
04973       // If this operand is already visited, reuse the prior result.
04974       // We may have P != PHI if this is the deepest point at which the
04975       // inconsistent paths meet.
04976       P = PHIMap.lookup(OpInst);
04977     if (!P) {
04978       // Recurse and memoize the results, whether a phi is found or not.
04979       // This recursive call invalidates pointers into PHIMap.
04980       P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap);
04981       PHIMap[OpInst] = P;
04982     }
04983     if (!P)
04984       return nullptr;  // Not evolving from PHI
04985     if (PHI && PHI != P)
04986       return nullptr;  // Evolving from multiple different PHIs.
04987     PHI = P;
04988   }
04989   // This is a expression evolving from a constant PHI!
04990   return PHI;
04991 }
04992 
04993 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
04994 /// in the loop that V is derived from.  We allow arbitrary operations along the
04995 /// way, but the operands of an operation must either be constants or a value
04996 /// derived from a constant PHI.  If this expression does not fit with these
04997 /// constraints, return null.
04998 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
04999   Instruction *I = dyn_cast<Instruction>(V);
05000   if (!I || !canConstantEvolve(I, L)) return nullptr;
05001 
05002   if (PHINode *PN = dyn_cast<PHINode>(I)) {
05003     return PN;
05004   }
05005 
05006   // Record non-constant instructions contained by the loop.
05007   DenseMap<Instruction *, PHINode *> PHIMap;
05008   return getConstantEvolvingPHIOperands(I, L, PHIMap);
05009 }
05010 
05011 /// EvaluateExpression - Given an expression that passes the
05012 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
05013 /// in the loop has the value PHIVal.  If we can't fold this expression for some
05014 /// reason, return null.
05015 static Constant *EvaluateExpression(Value *V, const Loop *L,
05016                                     DenseMap<Instruction *, Constant *> &Vals,
05017                                     const DataLayout *DL,
05018                                     const TargetLibraryInfo *TLI) {
05019   // Convenient constant check, but redundant for recursive calls.
05020   if (Constant *C = dyn_cast<Constant>(V)) return C;
05021   Instruction *I = dyn_cast<Instruction>(V);
05022   if (!I) return nullptr;
05023 
05024   if (Constant *C = Vals.lookup(I)) return C;
05025 
05026   // An instruction inside the loop depends on a value outside the loop that we
05027   // weren't given a mapping for, or a value such as a call inside the loop.
05028   if (!canConstantEvolve(I, L)) return nullptr;
05029 
05030   // An unmapped PHI can be due to a branch or another loop inside this loop,
05031   // or due to this not being the initial iteration through a loop where we
05032   // couldn't compute the evolution of this particular PHI last time.
05033   if (isa<PHINode>(I)) return nullptr;
05034 
05035   std::vector<Constant*> Operands(I->getNumOperands());
05036 
05037   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
05038     Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
05039     if (!Operand) {
05040       Operands[i] = dyn_cast<Constant>(I->getOperand(i));
05041       if (!Operands[i]) return nullptr;
05042       continue;
05043     }
05044     Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
05045     Vals[Operand] = C;
05046     if (!C) return nullptr;
05047     Operands[i] = C;
05048   }
05049 
05050   if (CmpInst *CI = dyn_cast<CmpInst>(I))
05051     return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
05052                                            Operands[1], DL, TLI);
05053   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
05054     if (!LI->isVolatile())
05055       return ConstantFoldLoadFromConstPtr(Operands[0], DL);
05056   }
05057   return ConstantFoldInstOperands(I->getOpcode(), I->getType(), Operands, DL,
05058                                   TLI);
05059 }
05060 
05061 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
05062 /// in the header of its containing loop, we know the loop executes a
05063 /// constant number of times, and the PHI node is just a recurrence
05064 /// involving constants, fold it.
05065 Constant *
05066 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
05067                                                    const APInt &BEs,
05068                                                    const Loop *L) {
05069   DenseMap<PHINode*, Constant*>::const_iterator I =
05070     ConstantEvolutionLoopExitValue.find(PN);
05071   if (I != ConstantEvolutionLoopExitValue.end())
05072     return I->second;
05073 
05074   if (BEs.ugt(MaxBruteForceIterations))
05075     return ConstantEvolutionLoopExitValue[PN] = nullptr;  // Not going to evaluate it.
05076 
05077   Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
05078 
05079   DenseMap<Instruction *, Constant *> CurrentIterVals;
05080   BasicBlock *Header = L->getHeader();
05081   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
05082 
05083   // Since the loop is canonicalized, the PHI node must have two entries.  One
05084   // entry must be a constant (coming in from outside of the loop), and the
05085   // second must be derived from the same PHI.
05086   bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
05087   PHINode *PHI = nullptr;
05088   for (BasicBlock::iterator I = Header->begin();
05089        (PHI = dyn_cast<PHINode>(I)); ++I) {
05090     Constant *StartCST =
05091       dyn_cast<Constant>(PHI->getIncomingValue(!SecondIsBackedge));
05092     if (!StartCST) continue;
05093     CurrentIterVals[PHI] = StartCST;
05094   }
05095   if (!CurrentIterVals.count(PN))
05096     return RetVal = nullptr;
05097 
05098   Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
05099 
05100   // Execute the loop symbolically to determine the exit value.
05101   if (BEs.getActiveBits() >= 32)
05102     return RetVal = nullptr; // More than 2^32-1 iterations?? Not doing it!
05103 
05104   unsigned NumIterations = BEs.getZExtValue(); // must be in range
05105   unsigned IterationNum = 0;
05106   for (; ; ++IterationNum) {
05107     if (IterationNum == NumIterations)
05108       return RetVal = CurrentIterVals[PN];  // Got exit value!
05109 
05110     // Compute the value of the PHIs for the next iteration.
05111     // EvaluateExpression adds non-phi values to the CurrentIterVals map.
05112     DenseMap<Instruction *, Constant *> NextIterVals;
05113     Constant *NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL,
05114                                            TLI);
05115     if (!NextPHI)
05116       return nullptr;        // Couldn't evaluate!
05117     NextIterVals[PN] = NextPHI;
05118 
05119     bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
05120 
05121     // Also evaluate the other PHI nodes.  However, we don't get to stop if we
05122     // cease to be able to evaluate one of them or if they stop evolving,
05123     // because that doesn't necessarily prevent us from computing PN.
05124     SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
05125     for (DenseMap<Instruction *, Constant *>::const_iterator
05126            I = CurrentIterVals.begin(), E = CurrentIterVals.end(); I != E; ++I){
05127       PHINode *PHI = dyn_cast<PHINode>(I->first);
05128       if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
05129       PHIsToCompute.push_back(std::make_pair(PHI, I->second));
05130     }
05131     // We use two distinct loops because EvaluateExpression may invalidate any
05132     // iterators into CurrentIterVals.
05133     for (SmallVectorImpl<std::pair<PHINode *, Constant*> >::const_iterator
05134              I = PHIsToCompute.begin(), E = PHIsToCompute.end(); I != E; ++I) {
05135       PHINode *PHI = I->first;
05136       Constant *&NextPHI = NextIterVals[PHI];
05137       if (!NextPHI) {   // Not already computed.
05138         Value *BEValue = PHI->getIncomingValue(SecondIsBackedge);
05139         NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, TLI);
05140       }
05141       if (NextPHI != I->second)
05142         StoppedEvolving = false;
05143     }
05144 
05145     // If all entries in CurrentIterVals == NextIterVals then we can stop
05146     // iterating, the loop can't continue to change.
05147     if (StoppedEvolving)
05148       return RetVal = CurrentIterVals[PN];
05149 
05150     CurrentIterVals.swap(NextIterVals);
05151   }
05152 }
05153 
05154 /// ComputeExitCountExhaustively - If the loop is known to execute a
05155 /// constant number of times (the condition evolves only from constants),
05156 /// try to evaluate a few iterations of the loop until we get the exit
05157 /// condition gets a value of ExitWhen (true or false).  If we cannot
05158 /// evaluate the trip count of the loop, return getCouldNotCompute().
05159 const SCEV *ScalarEvolution::ComputeExitCountExhaustively(const Loop *L,
05160                                                           Value *Cond,
05161                                                           bool ExitWhen) {
05162   PHINode *PN = getConstantEvolvingPHI(Cond, L);
05163   if (!PN) return getCouldNotCompute();
05164 
05165   // If the loop is canonicalized, the PHI will have exactly two entries.
05166   // That's the only form we support here.
05167   if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
05168 
05169   DenseMap<Instruction *, Constant *> CurrentIterVals;
05170   BasicBlock *Header = L->getHeader();
05171   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
05172 
05173   // One entry must be a constant (coming in from outside of the loop), and the
05174   // second must be derived from the same PHI.
05175   bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
05176   PHINode *PHI = nullptr;
05177   for (BasicBlock::iterator I = Header->begin();
05178        (PHI = dyn_cast<PHINode>(I)); ++I) {
05179     Constant *StartCST =
05180       dyn_cast<Constant>(PHI->getIncomingValue(!SecondIsBackedge));
05181     if (!StartCST) continue;
05182     CurrentIterVals[PHI] = StartCST;
05183   }
05184   if (!CurrentIterVals.count(PN))
05185     return getCouldNotCompute();
05186 
05187   // Okay, we find a PHI node that defines the trip count of this loop.  Execute
05188   // the loop symbolically to determine when the condition gets a value of
05189   // "ExitWhen".
05190 
05191   unsigned MaxIterations = MaxBruteForceIterations;   // Limit analysis.
05192   for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
05193     ConstantInt *CondVal =
05194       dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, L, CurrentIterVals,
05195                                                        DL, TLI));
05196 
05197     // Couldn't symbolically evaluate.
05198     if (!CondVal) return getCouldNotCompute();
05199 
05200     if (CondVal->getValue() == uint64_t(ExitWhen)) {
05201       ++NumBruteForceTripCountsComputed;
05202       return getConstant(Type::getInt32Ty(getContext()), IterationNum);
05203     }
05204 
05205     // Update all the PHI nodes for the next iteration.
05206     DenseMap<Instruction *, Constant *> NextIterVals;
05207 
05208     // Create a list of which PHIs we need to compute. We want to do this before
05209     // calling EvaluateExpression on them because that may invalidate iterators
05210     // into CurrentIterVals.
05211     SmallVector<PHINode *, 8> PHIsToCompute;
05212     for (DenseMap<Instruction *, Constant *>::const_iterator
05213            I = CurrentIterVals.begin(), E = CurrentIterVals.end(); I != E; ++I){
05214       PHINode *PHI = dyn_cast<PHINode>(I->first);
05215       if (!PHI || PHI->getParent() != Header) continue;
05216       PHIsToCompute.push_back(PHI);
05217     }
05218     for (SmallVectorImpl<PHINode *>::const_iterator I = PHIsToCompute.begin(),
05219              E = PHIsToCompute.end(); I != E; ++I) {
05220       PHINode *PHI = *I;
05221       Constant *&NextPHI = NextIterVals[PHI];
05222       if (NextPHI) continue;    // Already computed!
05223 
05224       Value *BEValue = PHI->getIncomingValue(SecondIsBackedge);
05225       NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, TLI);
05226     }
05227     CurrentIterVals.swap(NextIterVals);
05228   }
05229 
05230   // Too many iterations were needed to evaluate.
05231   return getCouldNotCompute();
05232 }
05233 
05234 /// getSCEVAtScope - Return a SCEV expression for the specified value
05235 /// at the specified scope in the program.  The L value specifies a loop
05236 /// nest to evaluate the expression at, where null is the top-level or a
05237 /// specified loop is immediately inside of the loop.
05238 ///
05239 /// This method can be used to compute the exit value for a variable defined
05240 /// in a loop by querying what the value will hold in the parent loop.
05241 ///
05242 /// In the case that a relevant loop exit value cannot be computed, the
05243 /// original value V is returned.
05244 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
05245   // Check to see if we've folded this expression at this loop before.
05246   SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = ValuesAtScopes[V];
05247   for (unsigned u = 0; u < Values.size(); u++) {
05248     if (Values[u].first == L)
05249       return Values[u].second ? Values[u].second : V;
05250   }
05251   Values.push_back(std::make_pair(L, static_cast<const SCEV *>(nullptr)));
05252   // Otherwise compute it.
05253   const SCEV *C = computeSCEVAtScope(V, L);
05254   SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values2 = ValuesAtScopes[V];
05255   for (unsigned u = Values2.size(); u > 0; u--) {
05256     if (Values2[u - 1].first == L) {
05257       Values2[u - 1].second = C;
05258       break;
05259     }
05260   }
05261   return C;
05262 }
05263 
05264 /// This builds up a Constant using the ConstantExpr interface.  That way, we
05265 /// will return Constants for objects which aren't represented by a
05266 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
05267 /// Returns NULL if the SCEV isn't representable as a Constant.
05268 static Constant *BuildConstantFromSCEV(const SCEV *V) {
05269   switch (static_cast<SCEVTypes>(V->getSCEVType())) {
05270     case scCouldNotCompute:
05271     case scAddRecExpr:
05272       break;
05273     case scConstant:
05274       return cast<SCEVConstant>(V)->getValue();
05275     case scUnknown:
05276       return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
05277     case scSignExtend: {
05278       const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
05279       if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
05280         return ConstantExpr::getSExt(CastOp, SS->getType());
05281       break;
05282     }
05283     case scZeroExtend: {
05284       const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
05285       if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
05286         return ConstantExpr::getZExt(CastOp, SZ->getType());
05287       break;
05288     }
05289     case scTruncate: {
05290       const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
05291       if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
05292         return ConstantExpr::getTrunc(CastOp, ST->getType());
05293       break;
05294     }
05295     case scAddExpr: {
05296       const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
05297       if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
05298         if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
05299           unsigned AS = PTy->getAddressSpace();
05300           Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
05301           C = ConstantExpr::getBitCast(C, DestPtrTy);
05302         }
05303         for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
05304           Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
05305           if (!C2) return nullptr;
05306 
05307           // First pointer!
05308           if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
05309             unsigned AS = C2->getType()->getPointerAddressSpace();
05310             std::swap(C, C2);
05311             Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
05312             // The offsets have been converted to bytes.  We can add bytes to an
05313             // i8* by GEP with the byte count in the first index.
05314             C = ConstantExpr::getBitCast(C, DestPtrTy);
05315           }
05316 
05317           // Don't bother trying to sum two pointers. We probably can't
05318           // statically compute a load that results from it anyway.
05319           if (C2->getType()->isPointerTy())
05320             return nullptr;
05321 
05322           if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
05323             if (PTy->getElementType()->isStructTy())
05324               C2 = ConstantExpr::getIntegerCast(
05325                   C2, Type::getInt32Ty(C->getContext()), true);
05326             C = ConstantExpr::getGetElementPtr(C, C2);
05327           } else
05328             C = ConstantExpr::getAdd(C, C2);
05329         }
05330         return C;
05331       }
05332       break;
05333     }
05334     case scMulExpr: {
05335       const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
05336       if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
05337         // Don't bother with pointers at all.
05338         if (C->getType()->isPointerTy()) return nullptr;
05339         for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
05340           Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
05341           if (!C2 || C2->getType()->isPointerTy()) return nullptr;
05342           C = ConstantExpr::getMul(C, C2);
05343         }
05344         return C;
05345       }
05346       break;
05347     }
05348     case scUDivExpr: {
05349       const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
05350       if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
05351         if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
05352           if (LHS->getType() == RHS->getType())
05353             return ConstantExpr::getUDiv(LHS, RHS);
05354       break;
05355     }
05356     case scSMaxExpr:
05357     case scUMaxExpr:
05358       break; // TODO: smax, umax.
05359   }
05360   return nullptr;
05361 }
05362 
05363 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
05364   if (isa<SCEVConstant>(V)) return V;
05365 
05366   // If this instruction is evolved from a constant-evolving PHI, compute the
05367   // exit value from the loop without using SCEVs.
05368   if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
05369     if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
05370       const Loop *LI = (*this->LI)[I->getParent()];
05371       if (LI && LI->getParentLoop() == L)  // Looking for loop exit value.
05372         if (PHINode *PN = dyn_cast<PHINode>(I))
05373           if (PN->getParent() == LI->getHeader()) {
05374             // Okay, there is no closed form solution for the PHI node.  Check
05375             // to see if the loop that contains it has a known backedge-taken
05376             // count.  If so, we may be able to force computation of the exit
05377             // value.
05378             const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
05379             if (const SCEVConstant *BTCC =
05380                   dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
05381               // Okay, we know how many times the containing loop executes.  If
05382               // this is a constant evolving PHI node, get the final value at
05383               // the specified iteration number.
05384               Constant *RV = getConstantEvolutionLoopExitValue(PN,
05385                                                    BTCC->getValue()->getValue(),
05386                                                                LI);
05387               if (RV) return getSCEV(RV);
05388             }
05389           }
05390 
05391       // Okay, this is an expression that we cannot symbolically evaluate
05392       // into a SCEV.  Check to see if it's possible to symbolically evaluate
05393       // the arguments into constants, and if so, try to constant propagate the
05394       // result.  This is particularly useful for computing loop exit values.
05395       if (CanConstantFold(I)) {
05396         SmallVector<Constant *, 4> Operands;
05397         bool MadeImprovement = false;
05398         for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
05399           Value *Op = I->getOperand(i);
05400           if (Constant *C = dyn_cast<Constant>(Op)) {
05401             Operands.push_back(C);
05402             continue;
05403           }
05404 
05405           // If any of the operands is non-constant and if they are
05406           // non-integer and non-pointer, don't even try to analyze them
05407           // with scev techniques.
05408           if (!isSCEVable(Op->getType()))
05409             return V;
05410 
05411           const SCEV *OrigV = getSCEV(Op);
05412           const SCEV *OpV = getSCEVAtScope(OrigV, L);
05413           MadeImprovement |= OrigV != OpV;
05414 
05415           Constant *C = BuildConstantFromSCEV(OpV);
05416           if (!C) return V;
05417           if (C->getType() != Op->getType())
05418             C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
05419                                                               Op->getType(),
05420                                                               false),
05421                                       C, Op->getType());
05422           Operands.push_back(C);
05423         }
05424 
05425         // Check to see if getSCEVAtScope actually made an improvement.
05426         if (MadeImprovement) {
05427           Constant *C = nullptr;
05428           if (const CmpInst *CI = dyn_cast<CmpInst>(I))
05429             C = ConstantFoldCompareInstOperands(CI->getPredicate(),
05430                                                 Operands[0], Operands[1], DL,
05431                                                 TLI);
05432           else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
05433             if (!LI->isVolatile())
05434               C = ConstantFoldLoadFromConstPtr(Operands[0], DL);
05435           } else
05436             C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
05437                                          Operands, DL, TLI);
05438           if (!C) return V;
05439           return getSCEV(C);
05440         }
05441       }
05442     }
05443 
05444     // This is some other type of SCEVUnknown, just return it.
05445     return V;
05446   }
05447 
05448   if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
05449     // Avoid performing the look-up in the common case where the specified
05450     // expression has no loop-variant portions.
05451     for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
05452       const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
05453       if (OpAtScope != Comm->getOperand(i)) {
05454         // Okay, at least one of these operands is loop variant but might be
05455         // foldable.  Build a new instance of the folded commutative expression.
05456         SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
05457                                             Comm->op_begin()+i);
05458         NewOps.push_back(OpAtScope);
05459 
05460         for (++i; i != e; ++i) {
05461           OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
05462           NewOps.push_back(OpAtScope);
05463         }
05464         if (isa<SCEVAddExpr>(Comm))
05465           return getAddExpr(NewOps);
05466         if (isa<SCEVMulExpr>(Comm))
05467           return getMulExpr(NewOps);
05468         if (isa<SCEVSMaxExpr>(Comm))
05469           return getSMaxExpr(NewOps);
05470         if (isa<SCEVUMaxExpr>(Comm))
05471           return getUMaxExpr(NewOps);
05472         llvm_unreachable("Unknown commutative SCEV type!");
05473       }
05474     }
05475     // If we got here, all operands are loop invariant.
05476     return Comm;
05477   }
05478 
05479   if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
05480     const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
05481     const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
05482     if (LHS == Div->getLHS() && RHS == Div->getRHS())
05483       return Div;   // must be loop invariant
05484     return getUDivExpr(LHS, RHS);
05485   }
05486 
05487   // If this is a loop recurrence for a loop that does not contain L, then we
05488   // are dealing with the final value computed by the loop.
05489   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
05490     // First, attempt to evaluate each operand.
05491     // Avoid performing the look-up in the common case where the specified
05492     // expression has no loop-variant portions.
05493     for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
05494       const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
05495       if (OpAtScope == AddRec->getOperand(i))
05496         continue;
05497 
05498       // Okay, at least one of these operands is loop variant but might be
05499       // foldable.  Build a new instance of the folded commutative expression.
05500       SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
05501                                           AddRec->op_begin()+i);
05502       NewOps.push_back(OpAtScope);
05503       for (++i; i != e; ++i)
05504         NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
05505 
05506       const SCEV *FoldedRec =
05507         getAddRecExpr(NewOps, AddRec->getLoop(),
05508                       AddRec->getNoWrapFlags(SCEV::FlagNW));
05509       AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
05510       // The addrec may be folded to a nonrecurrence, for example, if the
05511       // induction variable is multiplied by zero after constant folding. Go
05512       // ahead and return the folded value.
05513       if (!AddRec)
05514         return FoldedRec;
05515       break;
05516     }
05517 
05518     // If the scope is outside the addrec's loop, evaluate it by using the
05519     // loop exit value of the addrec.
05520     if (!AddRec->getLoop()->contains(L)) {
05521       // To evaluate this recurrence, we need to know how many times the AddRec
05522       // loop iterates.  Compute this now.
05523       const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
05524       if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
05525 
05526       // Then, evaluate the AddRec.
05527       return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
05528     }
05529 
05530     return AddRec;
05531   }
05532 
05533   if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
05534     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
05535     if (Op == Cast->getOperand())
05536       return Cast;  // must be loop invariant
05537     return getZeroExtendExpr(Op, Cast->getType());
05538   }
05539 
05540   if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
05541     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
05542     if (Op == Cast->getOperand())
05543       return Cast;  // must be loop invariant
05544     return getSignExtendExpr(Op, Cast->getType());
05545   }
05546 
05547   if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
05548     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
05549     if (Op == Cast->getOperand())
05550       return Cast;  // must be loop invariant
05551     return getTruncateExpr(Op, Cast->getType());
05552   }
05553 
05554   llvm_unreachable("Unknown SCEV type!");
05555 }
05556 
05557 /// getSCEVAtScope - This is a convenience function which does
05558 /// getSCEVAtScope(getSCEV(V), L).
05559 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
05560   return getSCEVAtScope(getSCEV(V), L);
05561 }
05562 
05563 /// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
05564 /// following equation:
05565 ///
05566 ///     A * X = B (mod N)
05567 ///
05568 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
05569 /// A and B isn't important.
05570 ///
05571 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
05572 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
05573                                                ScalarEvolution &SE) {
05574   uint32_t BW = A.getBitWidth();
05575   assert(BW == B.getBitWidth() && "Bit widths must be the same.");
05576   assert(A != 0 && "A must be non-zero.");
05577 
05578   // 1. D = gcd(A, N)
05579   //
05580   // The gcd of A and N may have only one prime factor: 2. The number of
05581   // trailing zeros in A is its multiplicity
05582   uint32_t Mult2 = A.countTrailingZeros();
05583   // D = 2^Mult2
05584 
05585   // 2. Check if B is divisible by D.
05586   //
05587   // B is divisible by D if and only if the multiplicity of prime factor 2 for B
05588   // is not less than multiplicity of this prime factor for D.
05589   if (B.countTrailingZeros() < Mult2)
05590     return SE.getCouldNotCompute();
05591 
05592   // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
05593   // modulo (N / D).
05594   //
05595   // (N / D) may need BW+1 bits in its representation.  Hence, we'll use this
05596   // bit width during computations.
05597   APInt AD = A.lshr(Mult2).zext(BW + 1);  // AD = A / D
05598   APInt Mod(BW + 1, 0);
05599   Mod.setBit(BW - Mult2);  // Mod = N / D
05600   APInt I = AD.multiplicativeInverse(Mod);
05601 
05602   // 4. Compute the minimum unsigned root of the equation:
05603   // I * (B / D) mod (N / D)
05604   APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
05605 
05606   // The result is guaranteed to be less than 2^BW so we may truncate it to BW
05607   // bits.
05608   return SE.getConstant(Result.trunc(BW));
05609 }
05610 
05611 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the
05612 /// given quadratic chrec {L,+,M,+,N}.  This returns either the two roots (which
05613 /// might be the same) or two SCEVCouldNotCompute objects.
05614 ///
05615 static std::pair<const SCEV *,const SCEV *>
05616 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
05617   assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
05618   const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
05619   const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
05620   const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
05621 
05622   // We currently can only solve this if the coefficients are constants.
05623   if (!LC || !MC || !NC) {
05624     const SCEV *CNC = SE.getCouldNotCompute();
05625     return std::make_pair(CNC, CNC);
05626   }
05627 
05628   uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
05629   const APInt &L = LC->getValue()->getValue();
05630   const APInt &M = MC->getValue()->getValue();
05631   const APInt &N = NC->getValue()->getValue();
05632   APInt Two(BitWidth, 2);
05633   APInt Four(BitWidth, 4);
05634 
05635   {
05636     using namespace APIntOps;
05637     const APInt& C = L;
05638     // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
05639     // The B coefficient is M-N/2
05640     APInt B(M);
05641     B -= sdiv(N,Two);
05642 
05643     // The A coefficient is N/2
05644     APInt A(N.sdiv(Two));
05645 
05646     // Compute the B^2-4ac term.
05647     APInt SqrtTerm(B);
05648     SqrtTerm *= B;
05649     SqrtTerm -= Four * (A * C);
05650 
05651     if (SqrtTerm.isNegative()) {
05652       // The loop is provably infinite.
05653       const SCEV *CNC = SE.getCouldNotCompute();
05654       return std::make_pair(CNC, CNC);
05655     }
05656 
05657     // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
05658     // integer value or else APInt::sqrt() will assert.
05659     APInt SqrtVal(SqrtTerm.sqrt());
05660 
05661     // Compute the two solutions for the quadratic formula.
05662     // The divisions must be performed as signed divisions.
05663     APInt NegB(-B);
05664     APInt TwoA(A << 1);
05665     if (TwoA.isMinValue()) {
05666       const SCEV *CNC = SE.getCouldNotCompute();
05667       return std::make_pair(CNC, CNC);
05668     }
05669 
05670     LLVMContext &Context = SE.getContext();
05671 
05672     ConstantInt *Solution1 =
05673       ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
05674     ConstantInt *Solution2 =
05675       ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
05676 
05677     return std::make_pair(SE.getConstant(Solution1),
05678                           SE.getConstant(Solution2));
05679   } // end APIntOps namespace
05680 }
05681 
05682 /// HowFarToZero - Return the number of times a backedge comparing the specified
05683 /// value to zero will execute.  If not computable, return CouldNotCompute.
05684 ///
05685 /// This is only used for loops with a "x != y" exit test. The exit condition is
05686 /// now expressed as a single expression, V = x-y. So the exit test is
05687 /// effectively V != 0.  We know and take advantage of the fact that this
05688 /// expression only being used in a comparison by zero context.
05689 ScalarEvolution::ExitLimit
05690 ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L, bool IsSubExpr) {
05691   // If the value is a constant
05692   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
05693     // If the value is already zero, the branch will execute zero times.
05694     if (C->getValue()->isZero()) return C;
05695     return getCouldNotCompute();  // Otherwise it will loop infinitely.
05696   }
05697 
05698   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
05699   if (!AddRec || AddRec->getLoop() != L)
05700     return getCouldNotCompute();
05701 
05702   // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
05703   // the quadratic equation to solve it.
05704   if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
05705     std::pair<const SCEV *,const SCEV *> Roots =
05706       SolveQuadraticEquation(AddRec, *this);
05707     const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
05708     const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
05709     if (R1 && R2) {
05710 #if 0
05711       dbgs() << "HFTZ: " << *V << " - sol#1: " << *R1
05712              << "  sol#2: " << *R2 << "\n";
05713 #endif
05714       // Pick the smallest positive root value.
05715       if (ConstantInt *CB =
05716           dyn_cast<ConstantInt>(ConstantExpr::getICmp(CmpInst::ICMP_ULT,
05717                                                       R1->getValue(),
05718                                                       R2->getValue()))) {
05719         if (CB->getZExtValue() == false)
05720           std::swap(R1, R2);   // R1 is the minimum root now.
05721 
05722         // We can only use this value if the chrec ends up with an exact zero
05723         // value at this index.  When solving for "X*X != 5", for example, we
05724         // should not accept a root of 2.
05725         const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
05726         if (Val->isZero())
05727           return R1;  // We found a quadratic root!
05728       }
05729     }
05730     return getCouldNotCompute();
05731   }
05732 
05733   // Otherwise we can only handle this if it is affine.
05734   if (!AddRec->isAffine())
05735     return getCouldNotCompute();
05736 
05737   // If this is an affine expression, the execution count of this branch is
05738   // the minimum unsigned root of the following equation:
05739   //
05740   //     Start + Step*N = 0 (mod 2^BW)
05741   //
05742   // equivalent to:
05743   //
05744   //             Step*N = -Start (mod 2^BW)
05745   //
05746   // where BW is the common bit width of Start and Step.
05747 
05748   // Get the initial value for the loop.
05749   const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
05750   const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
05751 
05752   // For now we handle only constant steps.
05753   //
05754   // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
05755   // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
05756   // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
05757   // We have not yet seen any such cases.
05758   const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
05759   if (!StepC || StepC->getValue()->equalsInt(0))
05760     return getCouldNotCompute();
05761 
05762   // For positive steps (counting up until unsigned overflow):
05763   //   N = -Start/Step (as unsigned)
05764   // For negative steps (counting down to zero):
05765   //   N = Start/-Step
05766   // First compute the unsigned distance from zero in the direction of Step.
05767   bool CountDown = StepC->getValue()->getValue().isNegative();
05768   const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
05769 
05770   // Handle unitary steps, which cannot wraparound.
05771   // 1*N = -Start; -1*N = Start (mod 2^BW), so:
05772   //   N = Distance (as unsigned)
05773   if (StepC->getValue()->equalsInt(1) || StepC->getValue()->isAllOnesValue()) {
05774     ConstantRange CR = getUnsignedRange(Start);
05775     const SCEV *MaxBECount;
05776     if (!CountDown && CR.getUnsignedMin().isMinValue())
05777       // When counting up, the worst starting value is 1, not 0.
05778       MaxBECount = CR.getUnsignedMax().isMinValue()
05779         ? getConstant(APInt::getMinValue(CR.getBitWidth()))
05780         : getConstant(APInt::getMaxValue(CR.getBitWidth()));
05781     else
05782       MaxBECount = getConstant(CountDown ? CR.getUnsignedMax()
05783                                          : -CR.getUnsignedMin());
05784     return ExitLimit(Distance, MaxBECount, /*MustExit=*/true);
05785   }
05786 
05787   // If the recurrence is known not to wraparound, unsigned divide computes the
05788   // back edge count. (Ideally we would have an "isexact" bit for udiv). We know
05789   // that the value will either become zero (and thus the loop terminates), that
05790   // the loop will terminate through some other exit condition first, or that
05791   // the loop has undefined behavior.  This means we can't "miss" the exit
05792   // value, even with nonunit stride, and exit later via the same branch. Note
05793   // that we can skip this exit if loop later exits via a different
05794   // branch. Hence MustExit=false.
05795   //
05796   // This is only valid for expressions that directly compute the loop exit. It
05797   // is invalid for subexpressions in which the loop may exit through this
05798   // branch even if this subexpression is false. In that case, the trip count
05799   // computed by this udiv could be smaller than the number of well-defined
05800   // iterations.
05801   if (!IsSubExpr && AddRec->getNoWrapFlags(SCEV::FlagNW)) {
05802     const SCEV *Exact =
05803       getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
05804     return ExitLimit(Exact, Exact, /*MustExit=*/false);
05805   }
05806 
05807   // If Step is a power of two that evenly divides Start we know that the loop
05808   // will always terminate.  Start may not be a constant so we just have the
05809   // number of trailing zeros available.  This is safe even in presence of
05810   // overflow as the recurrence will overflow to exactly 0.
05811   const APInt &StepV = StepC->getValue()->getValue();
05812   if (StepV.isPowerOf2() &&
05813       GetMinTrailingZeros(getNegativeSCEV(Start)) >= StepV.countTrailingZeros())
05814     return getUDivExactExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
05815 
05816   // Then, try to solve the above equation provided that Start is constant.
05817   if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
05818     return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
05819                                         -StartC->getValue()->getValue(),
05820                                         *this);
05821   return getCouldNotCompute();
05822 }
05823 
05824 /// HowFarToNonZero - Return the number of times a backedge checking the
05825 /// specified value for nonzero will execute.  If not computable, return
05826 /// CouldNotCompute
05827 ScalarEvolution::ExitLimit
05828 ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
05829   // Loops that look like: while (X == 0) are very strange indeed.  We don't
05830   // handle them yet except for the trivial case.  This could be expanded in the
05831   // future as needed.
05832 
05833   // If the value is a constant, check to see if it is known to be non-zero
05834   // already.  If so, the backedge will execute zero times.
05835   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
05836     if (!C->getValue()->isNullValue())
05837       return getConstant(C->getType(), 0);
05838     return getCouldNotCompute();  // Otherwise it will loop infinitely.
05839   }
05840 
05841   // We could implement others, but I really doubt anyone writes loops like
05842   // this, and if they did, they would already be constant folded.
05843   return getCouldNotCompute();
05844 }
05845 
05846 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
05847 /// (which may not be an immediate predecessor) which has exactly one
05848 /// successor from which BB is reachable, or null if no such block is
05849 /// found.
05850 ///
05851 std::pair<BasicBlock *, BasicBlock *>
05852 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
05853   // If the block has a unique predecessor, then there is no path from the
05854   // predecessor to the block that does not go through the direct edge
05855   // from the predecessor to the block.
05856   if (BasicBlock *Pred = BB->getSinglePredecessor())
05857     return std::make_pair(Pred, BB);
05858 
05859   // A loop's header is defined to be a block that dominates the loop.
05860   // If the header has a unique predecessor outside the loop, it must be
05861   // a block that has exactly one successor that can reach the loop.
05862   if (Loop *L = LI->getLoopFor(BB))
05863     return std::make_pair(L->getLoopPredecessor(), L->getHeader());
05864 
05865   return std::pair<BasicBlock *, BasicBlock *>();
05866 }
05867 
05868 /// HasSameValue - SCEV structural equivalence is usually sufficient for
05869 /// testing whether two expressions are equal, however for the purposes of
05870 /// looking for a condition guarding a loop, it can be useful to be a little
05871 /// more general, since a front-end may have replicated the controlling
05872 /// expression.
05873 ///
05874 static bool HasSameValue(const SCEV *A, const SCEV *B) {
05875   // Quick check to see if they are the same SCEV.
05876   if (A == B) return true;
05877 
05878   // Otherwise, if they're both SCEVUnknown, it's possible that they hold
05879   // two different instructions with the same value. Check for this case.
05880   if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
05881     if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
05882       if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
05883         if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
05884           if (AI->isIdenticalTo(BI) && !AI->mayReadFromMemory())
05885             return true;
05886 
05887   // Otherwise assume they may have a different value.
05888   return false;
05889 }
05890 
05891 /// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with
05892 /// predicate Pred. Return true iff any changes were made.
05893 ///
05894 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
05895                                            const SCEV *&LHS, const SCEV *&RHS,
05896                                            unsigned Depth) {
05897   bool Changed = false;
05898 
05899   // If we hit the max recursion limit bail out.
05900   if (Depth >= 3)
05901     return false;
05902 
05903   // Canonicalize a constant to the right side.
05904   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
05905     // Check for both operands constant.
05906     if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
05907       if (ConstantExpr::getICmp(Pred,
05908                                 LHSC->getValue(),
05909                                 RHSC->getValue())->isNullValue())
05910         goto trivially_false;
05911       else
05912         goto trivially_true;
05913     }
05914     // Otherwise swap the operands to put the constant on the right.
05915     std::swap(LHS, RHS);
05916     Pred = ICmpInst::getSwappedPredicate(Pred);
05917     Changed = true;
05918   }
05919 
05920   // If we're comparing an addrec with a value which is loop-invariant in the
05921   // addrec's loop, put the addrec on the left. Also make a dominance check,
05922   // as both operands could be addrecs loop-invariant in each other's loop.
05923   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
05924     const Loop *L = AR->getLoop();
05925     if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
05926       std::swap(LHS, RHS);
05927       Pred = ICmpInst::getSwappedPredicate(Pred);
05928       Changed = true;
05929     }
05930   }
05931 
05932   // If there's a constant operand, canonicalize comparisons with boundary
05933   // cases, and canonicalize *-or-equal comparisons to regular comparisons.
05934   if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
05935     const APInt &RA = RC->getValue()->getValue();
05936     switch (Pred) {
05937     default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
05938     case ICmpInst::ICMP_EQ:
05939     case ICmpInst::ICMP_NE:
05940       // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
05941       if (!RA)
05942         if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
05943           if (const SCEVMulExpr *ME = dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
05944             if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
05945                 ME->getOperand(0)->isAllOnesValue()) {
05946               RHS = AE->getOperand(1);
05947               LHS = ME->getOperand(1);
05948               Changed = true;
05949             }
05950       break;
05951     case ICmpInst::ICMP_UGE:
05952       if ((RA - 1).isMinValue()) {
05953         Pred = ICmpInst::ICMP_NE;
05954         RHS = getConstant(RA - 1);
05955         Changed = true;
05956         break;
05957       }
05958       if (RA.isMaxValue()) {
05959         Pred = ICmpInst::ICMP_EQ;
05960         Changed = true;
05961         break;
05962       }
05963       if (RA.isMinValue()) goto trivially_true;
05964 
05965       Pred = ICmpInst::ICMP_UGT;
05966       RHS = getConstant(RA - 1);
05967       Changed = true;
05968       break;
05969     case ICmpInst::ICMP_ULE:
05970       if ((RA + 1).isMaxValue()) {
05971         Pred = ICmpInst::ICMP_NE;
05972         RHS = getConstant(RA + 1);
05973         Changed = true;
05974         break;
05975       }
05976       if (RA.isMinValue()) {
05977         Pred = ICmpInst::ICMP_EQ;
05978         Changed = true;
05979         break;
05980       }
05981       if (RA.isMaxValue()) goto trivially_true;
05982 
05983       Pred = ICmpInst::ICMP_ULT;
05984       RHS = getConstant(RA + 1);
05985       Changed = true;
05986       break;
05987     case ICmpInst::ICMP_SGE:
05988       if ((RA - 1).isMinSignedValue()) {
05989         Pred = ICmpInst::ICMP_NE;
05990         RHS = getConstant(RA - 1);
05991         Changed = true;
05992         break;
05993       }
05994       if (RA.isMaxSignedValue()) {
05995         Pred = ICmpInst::ICMP_EQ;
05996         Changed = true;
05997         break;
05998       }
05999       if (RA.isMinSignedValue()) goto trivially_true;
06000 
06001       Pred = ICmpInst::ICMP_SGT;
06002       RHS = getConstant(RA - 1);
06003       Changed = true;
06004       break;
06005     case ICmpInst::ICMP_SLE:
06006       if ((RA + 1).isMaxSignedValue()) {
06007         Pred = ICmpInst::ICMP_NE;
06008         RHS = getConstant(RA + 1);
06009         Changed = true;
06010         break;
06011       }
06012       if (RA.isMinSignedValue()) {
06013         Pred = ICmpInst::ICMP_EQ;
06014         Changed = true;
06015         break;
06016       }
06017       if (RA.isMaxSignedValue()) goto trivially_true;
06018 
06019       Pred = ICmpInst::ICMP_SLT;
06020       RHS = getConstant(RA + 1);
06021       Changed = true;
06022       break;
06023     case ICmpInst::ICMP_UGT:
06024       if (RA.isMinValue()) {
06025         Pred = ICmpInst::ICMP_NE;
06026         Changed = true;
06027         break;
06028       }
06029       if ((RA + 1).isMaxValue()) {
06030         Pred = ICmpInst::ICMP_EQ;
06031         RHS = getConstant(RA + 1);
06032         Changed = true;
06033         break;
06034       }
06035       if (RA.isMaxValue()) goto trivially_false;
06036       break;
06037     case ICmpInst::ICMP_ULT:
06038       if (RA.isMaxValue()) {
06039         Pred = ICmpInst::ICMP_NE;
06040         Changed = true;
06041         break;
06042       }
06043       if ((RA - 1).isMinValue()) {
06044         Pred = ICmpInst::ICMP_EQ;
06045         RHS = getConstant(RA - 1);
06046         Changed = true;
06047         break;
06048       }
06049       if (RA.isMinValue()) goto trivially_false;
06050       break;
06051     case ICmpInst::ICMP_SGT:
06052       if (RA.isMinSignedValue()) {
06053         Pred = ICmpInst::ICMP_NE;
06054         Changed = true;
06055         break;
06056       }
06057       if ((RA + 1).isMaxSignedValue()) {
06058         Pred = ICmpInst::ICMP_EQ;
06059         RHS = getConstant(RA + 1);
06060         Changed = true;
06061         break;
06062       }
06063       if (RA.isMaxSignedValue()) goto trivially_false;
06064       break;
06065     case ICmpInst::ICMP_SLT:
06066       if (RA.isMaxSignedValue()) {
06067         Pred = ICmpInst::ICMP_NE;
06068         Changed = true;
06069         break;
06070       }
06071       if ((RA - 1).isMinSignedValue()) {
06072        Pred = ICmpInst::ICMP_EQ;
06073        RHS = getConstant(RA - 1);
06074         Changed = true;
06075        break;
06076       }
06077       if (RA.isMinSignedValue()) goto trivially_false;
06078       break;
06079     }
06080   }
06081 
06082   // Check for obvious equality.
06083   if (HasSameValue(LHS, RHS)) {
06084     if (ICmpInst::isTrueWhenEqual(Pred))
06085       goto trivially_true;
06086     if (ICmpInst::isFalseWhenEqual(Pred))
06087       goto trivially_false;
06088   }
06089 
06090   // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
06091   // adding or subtracting 1 from one of the operands.
06092   switch (Pred) {
06093   case ICmpInst::ICMP_SLE:
06094     if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) {
06095       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
06096                        SCEV::FlagNSW);
06097       Pred = ICmpInst::ICMP_SLT;
06098       Changed = true;
06099     } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) {
06100       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
06101                        SCEV::FlagNSW);
06102       Pred = ICmpInst::ICMP_SLT;
06103       Changed = true;
06104     }
06105     break;
06106   case ICmpInst::ICMP_SGE:
06107     if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) {
06108       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
06109                        SCEV::FlagNSW);
06110       Pred = ICmpInst::ICMP_SGT;
06111       Changed = true;
06112     } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) {
06113       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
06114                        SCEV::FlagNSW);
06115       Pred = ICmpInst::ICMP_SGT;
06116       Changed = true;
06117     }
06118     break;
06119   case ICmpInst::ICMP_ULE:
06120     if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) {
06121       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
06122                        SCEV::FlagNUW);
06123       Pred = ICmpInst::ICMP_ULT;
06124       Changed = true;
06125     } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) {
06126       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
06127                        SCEV::FlagNUW);
06128       Pred = ICmpInst::ICMP_ULT;
06129       Changed = true;
06130     }
06131     break;
06132   case ICmpInst::ICMP_UGE:
06133     if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) {
06134       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
06135                        SCEV::FlagNUW);
06136       Pred = ICmpInst::ICMP_UGT;
06137       Changed = true;
06138     } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) {
06139       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
06140                        SCEV::FlagNUW);
06141       Pred = ICmpInst::ICMP_UGT;
06142       Changed = true;
06143     }
06144     break;
06145   default:
06146     break;
06147   }
06148 
06149   // TODO: More simplifications are possible here.
06150 
06151   // Recursively simplify until we either hit a recursion limit or nothing
06152   // changes.
06153   if (Changed)
06154     return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
06155 
06156   return Changed;
06157 
06158 trivially_true:
06159   // Return 0 == 0.
06160   LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
06161   Pred = ICmpInst::ICMP_EQ;
06162   return true;
06163 
06164 trivially_false:
06165   // Return 0 != 0.
06166   LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
06167   Pred = ICmpInst::ICMP_NE;
06168   return true;
06169 }
06170 
06171 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
06172   return getSignedRange(S).getSignedMax().isNegative();
06173 }
06174 
06175 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
06176   return getSignedRange(S).getSignedMin().isStrictlyPositive();
06177 }
06178 
06179 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
06180   return !getSignedRange(S).getSignedMin().isNegative();
06181 }
06182 
06183 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
06184   return !getSignedRange(S).getSignedMax().isStrictlyPositive();
06185 }
06186 
06187 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
06188   return isKnownNegative(S) || isKnownPositive(S);
06189 }
06190 
06191 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
06192                                        const SCEV *LHS, const SCEV *RHS) {
06193   // Canonicalize the inputs first.
06194   (void)SimplifyICmpOperands(Pred, LHS, RHS);
06195 
06196   // If LHS or RHS is an addrec, check to see if the condition is true in
06197   // every iteration of the loop.
06198   // If LHS and RHS are both addrec, both conditions must be true in
06199   // every iteration of the loop.
06200   const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
06201   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
06202   bool LeftGuarded = false;
06203   bool RightGuarded = false;
06204   if (LAR) {
06205     const Loop *L = LAR->getLoop();
06206     if (isLoopEntryGuardedByCond(L, Pred, LAR->getStart(), RHS) &&
06207         isLoopBackedgeGuardedByCond(L, Pred, LAR->getPostIncExpr(*this), RHS)) {
06208       if (!RAR) return true;
06209       LeftGuarded = true;
06210     }
06211   }
06212   if (RAR) {
06213     const Loop *L = RAR->getLoop();
06214     if (isLoopEntryGuardedByCond(L, Pred, LHS, RAR->getStart()) &&
06215         isLoopBackedgeGuardedByCond(L, Pred, LHS, RAR->getPostIncExpr(*this))) {
06216       if (!LAR) return true;
06217       RightGuarded = true;
06218     }
06219   }
06220   if (LeftGuarded && RightGuarded)
06221     return true;
06222 
06223   // Otherwise see what can be done with known constant ranges.
06224   return isKnownPredicateWithRanges(Pred, LHS, RHS);
06225 }
06226 
06227 bool
06228 ScalarEvolution::isKnownPredicateWithRanges(ICmpInst::Predicate Pred,
06229                                             const SCEV *LHS, const SCEV *RHS) {
06230   if (HasSameValue(LHS, RHS))
06231     return ICmpInst::isTrueWhenEqual(Pred);
06232 
06233   // This code is split out from isKnownPredicate because it is called from
06234   // within isLoopEntryGuardedByCond.
06235   switch (Pred) {
06236   default:
06237     llvm_unreachable("Unexpected ICmpInst::Predicate value!");
06238   case ICmpInst::ICMP_SGT:
06239     std::swap(LHS, RHS);
06240   case ICmpInst::ICMP_SLT: {
06241     ConstantRange LHSRange = getSignedRange(LHS);
06242     ConstantRange RHSRange = getSignedRange(RHS);
06243     if (LHSRange.getSignedMax().slt(RHSRange.getSignedMin()))
06244       return true;
06245     if (LHSRange.getSignedMin().sge(RHSRange.getSignedMax()))
06246       return false;
06247     break;
06248   }
06249   case ICmpInst::ICMP_SGE:
06250     std::swap(LHS, RHS);
06251   case ICmpInst::ICMP_SLE: {
06252     ConstantRange LHSRange = getSignedRange(LHS);
06253     ConstantRange RHSRange = getSignedRange(RHS);
06254     if (LHSRange.getSignedMax().sle(RHSRange.getSignedMin()))
06255       return true;
06256     if (LHSRange.getSignedMin().sgt(RHSRange.getSignedMax()))
06257       return false;
06258     break;
06259   }
06260   case ICmpInst::ICMP_UGT:
06261     std::swap(LHS, RHS);
06262   case ICmpInst::ICMP_ULT: {
06263     ConstantRange LHSRange = getUnsignedRange(LHS);
06264     ConstantRange RHSRange = getUnsignedRange(RHS);
06265     if (LHSRange.getUnsignedMax().ult(RHSRange.getUnsignedMin()))
06266       return true;
06267     if (LHSRange.getUnsignedMin().uge(RHSRange.getUnsignedMax()))
06268       return false;
06269     break;
06270   }
06271   case ICmpInst::ICMP_UGE:
06272     std::swap(LHS, RHS);
06273   case ICmpInst::ICMP_ULE: {
06274     ConstantRange LHSRange = getUnsignedRange(LHS);
06275     ConstantRange RHSRange = getUnsignedRange(RHS);
06276     if (LHSRange.getUnsignedMax().ule(RHSRange.getUnsignedMin()))
06277       return true;
06278     if (LHSRange.getUnsignedMin().ugt(RHSRange.getUnsignedMax()))
06279       return false;
06280     break;
06281   }
06282   case ICmpInst::ICMP_NE: {
06283     if (getUnsignedRange(LHS).intersectWith(getUnsignedRange(RHS)).isEmptySet())
06284       return true;
06285     if (getSignedRange(LHS).intersectWith(getSignedRange(RHS)).isEmptySet())
06286       return true;
06287 
06288     const SCEV *Diff = getMinusSCEV(LHS, RHS);
06289     if (isKnownNonZero(Diff))
06290       return true;
06291     break;
06292   }
06293   case ICmpInst::ICMP_EQ:
06294     // The check at the top of the function catches the case where
06295     // the values are known to be equal.
06296     break;
06297   }
06298   return false;
06299 }
06300 
06301 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
06302 /// protected by a conditional between LHS and RHS.  This is used to
06303 /// to eliminate casts.
06304 bool
06305 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
06306                                              ICmpInst::Predicate Pred,
06307                                              const SCEV *LHS, const SCEV *RHS) {
06308   // Interpret a null as meaning no loop, where there is obviously no guard
06309   // (interprocedural conditions notwithstanding).
06310   if (!L) return true;
06311 
06312   BasicBlock *Latch = L->getLoopLatch();
06313   if (!Latch)
06314     return false;
06315 
06316   BranchInst *LoopContinuePredicate =
06317     dyn_cast<BranchInst>(Latch->getTerminator());
06318   if (!LoopContinuePredicate ||
06319       LoopContinuePredicate->isUnconditional())
06320     return false;
06321 
06322   return isImpliedCond(Pred, LHS, RHS,
06323                        LoopContinuePredicate->getCondition(),
06324                        LoopContinuePredicate->getSuccessor(0) != L->getHeader());
06325 }
06326 
06327 /// isLoopEntryGuardedByCond - Test whether entry to the loop is protected
06328 /// by a conditional between LHS and RHS.  This is used to help avoid max
06329 /// expressions in loop trip counts, and to eliminate casts.
06330 bool
06331 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
06332                                           ICmpInst::Predicate Pred,
06333                                           const SCEV *LHS, const SCEV *RHS) {
06334   // Interpret a null as meaning no loop, where there is obviously no guard
06335   // (interprocedural conditions notwithstanding).
06336   if (!L) return false;
06337 
06338   // Starting at the loop predecessor, climb up the predecessor chain, as long
06339   // as there are predecessors that can be found that have unique successors
06340   // leading to the original header.
06341   for (std::pair<BasicBlock *, BasicBlock *>
06342          Pair(L->getLoopPredecessor(), L->getHeader());
06343        Pair.first;
06344        Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
06345 
06346     BranchInst *LoopEntryPredicate =
06347       dyn_cast<BranchInst>(Pair.first->getTerminator());
06348     if (!LoopEntryPredicate ||
06349         LoopEntryPredicate->isUnconditional())
06350       continue;
06351 
06352     if (isImpliedCond(Pred, LHS, RHS,
06353                       LoopEntryPredicate->getCondition(),
06354                       LoopEntryPredicate->getSuccessor(0) != Pair.second))
06355       return true;
06356   }
06357 
06358   return false;
06359 }
06360 
06361 /// RAII wrapper to prevent recursive application of isImpliedCond.
06362 /// ScalarEvolution's PendingLoopPredicates set must be empty unless we are
06363 /// currently evaluating isImpliedCond.
06364 struct MarkPendingLoopPredicate {
06365   Value *Cond;
06366   DenseSet<Value*> &LoopPreds;
06367   bool Pending;
06368 
06369   MarkPendingLoopPredicate(Value *C, DenseSet<Value*> &LP)
06370     : Cond(C), LoopPreds(LP) {
06371     Pending = !LoopPreds.insert(Cond).second;
06372   }
06373   ~MarkPendingLoopPredicate() {
06374     if (!Pending)
06375       LoopPreds.erase(Cond);
06376   }
06377 };
06378 
06379 /// isImpliedCond - Test whether the condition described by Pred, LHS,
06380 /// and RHS is true whenever the given Cond value evaluates to true.
06381 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
06382                                     const SCEV *LHS, const SCEV *RHS,
06383                                     Value *FoundCondValue,
06384                                     bool Inverse) {
06385   MarkPendingLoopPredicate Mark(FoundCondValue, PendingLoopPredicates);
06386   if (Mark.Pending)
06387     return false;
06388 
06389   // Recursively handle And and Or conditions.
06390   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
06391     if (BO->getOpcode() == Instruction::And) {
06392       if (!Inverse)
06393         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
06394                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
06395     } else if (BO->getOpcode() == Instruction::Or) {
06396       if (Inverse)
06397         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
06398                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
06399     }
06400   }
06401 
06402   ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
06403   if (!ICI) return false;
06404 
06405   // Bail if the ICmp's operands' types are wider than the needed type
06406   // before attempting to call getSCEV on them. This avoids infinite
06407   // recursion, since the analysis of widening casts can require loop
06408   // exit condition information for overflow checking, which would
06409   // lead back here.
06410   if (getTypeSizeInBits(LHS->getType()) <
06411       getTypeSizeInBits(ICI->getOperand(0)->getType()))
06412     return false;
06413 
06414   // Now that we found a conditional branch that dominates the loop or controls
06415   // the loop latch. Check to see if it is the comparison we are looking for.
06416   ICmpInst::Predicate FoundPred;
06417   if (Inverse)
06418     FoundPred = ICI->getInversePredicate();
06419   else
06420     FoundPred = ICI->getPredicate();
06421 
06422   const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
06423   const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
06424 
06425   // Balance the types. The case where FoundLHS' type is wider than
06426   // LHS' type is checked for above.
06427   if (getTypeSizeInBits(LHS->getType()) >
06428       getTypeSizeInBits(FoundLHS->getType())) {
06429     if (CmpInst::isSigned(FoundPred)) {
06430       FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
06431       FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
06432     } else {
06433       FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
06434       FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
06435     }
06436   }
06437 
06438   // Canonicalize the query to match the way instcombine will have
06439   // canonicalized the comparison.
06440   if (SimplifyICmpOperands(Pred, LHS, RHS))
06441     if (LHS == RHS)
06442       return CmpInst::isTrueWhenEqual(Pred);
06443   if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
06444     if (FoundLHS == FoundRHS)
06445       return CmpInst::isFalseWhenEqual(FoundPred);
06446 
06447   // Check to see if we can make the LHS or RHS match.
06448   if (LHS == FoundRHS || RHS == FoundLHS) {
06449     if (isa<SCEVConstant>(RHS)) {
06450       std::swap(FoundLHS, FoundRHS);
06451       FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
06452     } else {
06453       std::swap(LHS, RHS);
06454       Pred = ICmpInst::getSwappedPredicate(Pred);
06455     }
06456   }
06457 
06458   // Check whether the found predicate is the same as the desired predicate.
06459   if (FoundPred == Pred)
06460     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
06461 
06462   // Check whether swapping the found predicate makes it the same as the
06463   // desired predicate.
06464   if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
06465     if (isa<SCEVConstant>(RHS))
06466       return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
06467     else
06468       return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
06469                                    RHS, LHS, FoundLHS, FoundRHS);
06470   }
06471 
06472   // Check whether the actual condition is beyond sufficient.
06473   if (FoundPred == ICmpInst::ICMP_EQ)
06474     if (ICmpInst::isTrueWhenEqual(Pred))
06475       if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
06476         return true;
06477   if (Pred == ICmpInst::ICMP_NE)
06478     if (!ICmpInst::isTrueWhenEqual(FoundPred))
06479       if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
06480         return true;
06481 
06482   // Otherwise assume the worst.
06483   return false;
06484 }
06485 
06486 /// isImpliedCondOperands - Test whether the condition described by Pred,
06487 /// LHS, and RHS is true whenever the condition described by Pred, FoundLHS,
06488 /// and FoundRHS is true.
06489 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
06490                                             const SCEV *LHS, const SCEV *RHS,
06491                                             const SCEV *FoundLHS,
06492                                             const SCEV *FoundRHS) {
06493   return isImpliedCondOperandsHelper(Pred, LHS, RHS,
06494                                      FoundLHS, FoundRHS) ||
06495          // ~x < ~y --> x > y
06496          isImpliedCondOperandsHelper(Pred, LHS, RHS,
06497                                      getNotSCEV(FoundRHS),
06498                                      getNotSCEV(FoundLHS));
06499 }
06500 
06501 /// isImpliedCondOperandsHelper - Test whether the condition described by
06502 /// Pred, LHS, and RHS is true whenever the condition described by Pred,
06503 /// FoundLHS, and FoundRHS is true.
06504 bool
06505 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
06506                                              const SCEV *LHS, const SCEV *RHS,
06507                                              const SCEV *FoundLHS,
06508                                              const SCEV *FoundRHS) {
06509   switch (Pred) {
06510   default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
06511   case ICmpInst::ICMP_EQ:
06512   case ICmpInst::ICMP_NE:
06513     if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
06514       return true;
06515     break;
06516   case ICmpInst::ICMP_SLT:
06517   case ICmpInst::ICMP_SLE:
06518     if (isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
06519         isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, RHS, FoundRHS))
06520       return true;
06521     break;
06522   case ICmpInst::ICMP_SGT:
06523   case ICmpInst::ICMP_SGE:
06524     if (isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
06525         isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, RHS, FoundRHS))
06526       return true;
06527     break;
06528   case ICmpInst::ICMP_ULT:
06529   case ICmpInst::ICMP_ULE:
06530     if (isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
06531         isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, RHS, FoundRHS))
06532       return true;
06533     break;
06534   case ICmpInst::ICMP_UGT:
06535   case ICmpInst::ICMP_UGE:
06536     if (isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
06537         isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, RHS, FoundRHS))
06538       return true;
06539     break;
06540   }
06541 
06542   return false;
06543 }
06544 
06545 // Verify if an linear IV with positive stride can overflow when in a 
06546 // less-than comparison, knowing the invariant term of the comparison, the 
06547 // stride and the knowledge of NSW/NUW flags on the recurrence.
06548 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
06549                                          bool IsSigned, bool NoWrap) {
06550   if (NoWrap) return false;
06551 
06552   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
06553   const SCEV *One = getConstant(Stride->getType(), 1);
06554 
06555   if (IsSigned) {
06556     APInt MaxRHS = getSignedRange(RHS).getSignedMax();
06557     APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
06558     APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
06559                                 .getSignedMax();
06560 
06561     // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
06562     return (MaxValue - MaxStrideMinusOne).slt(MaxRHS);
06563   }
06564 
06565   APInt MaxRHS = getUnsignedRange(RHS).getUnsignedMax();
06566   APInt MaxValue = APInt::getMaxValue(BitWidth);
06567   APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
06568                               .getUnsignedMax();
06569 
06570   // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
06571   return (MaxValue - MaxStrideMinusOne).ult(MaxRHS);
06572 }
06573 
06574 // Verify if an linear IV with negative stride can overflow when in a 
06575 // greater-than comparison, knowing the invariant term of the comparison,
06576 // the stride and the knowledge of NSW/NUW flags on the recurrence.
06577 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
06578                                          bool IsSigned, bool NoWrap) {
06579   if (NoWrap) return false;
06580 
06581   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
06582   const SCEV *One = getConstant(Stride->getType(), 1);
06583 
06584   if (IsSigned) {
06585     APInt MinRHS = getSignedRange(RHS).getSignedMin();
06586     APInt MinValue = APInt::getSignedMinValue(BitWidth);
06587     APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
06588                                .getSignedMax();
06589 
06590     // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
06591     return (MinValue + MaxStrideMinusOne).sgt(MinRHS);
06592   }
06593 
06594   APInt MinRHS = getUnsignedRange(RHS).getUnsignedMin();
06595   APInt MinValue = APInt::getMinValue(BitWidth);
06596   APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
06597                             .getUnsignedMax();
06598 
06599   // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
06600   return (MinValue + MaxStrideMinusOne).ugt(MinRHS);
06601 }
06602 
06603 // Compute the backedge taken count knowing the interval difference, the
06604 // stride and presence of the equality in the comparison.
06605 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step, 
06606                                             bool Equality) {
06607   const SCEV *One = getConstant(Step->getType(), 1);
06608   Delta = Equality ? getAddExpr(Delta, Step)
06609                    : getAddExpr(Delta, getMinusSCEV(Step, One));
06610   return getUDivExpr(Delta, Step);
06611 }
06612 
06613 /// HowManyLessThans - Return the number of times a backedge containing the
06614 /// specified less-than comparison will execute.  If not computable, return
06615 /// CouldNotCompute.
06616 ///
06617 /// @param IsSubExpr is true when the LHS < RHS condition does not directly
06618 /// control the branch. In this case, we can only compute an iteration count for
06619 /// a subexpression that cannot overflow before evaluating true.
06620 ScalarEvolution::ExitLimit
06621 ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
06622                                   const Loop *L, bool IsSigned,
06623                                   bool IsSubExpr) {
06624   // We handle only IV < Invariant
06625   if (!isLoopInvariant(RHS, L))
06626     return getCouldNotCompute();
06627 
06628   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
06629 
06630   // Avoid weird loops
06631   if (!IV || IV->getLoop() != L || !IV->isAffine())
06632     return getCouldNotCompute();
06633 
06634   bool NoWrap = !IsSubExpr &&
06635                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
06636 
06637   const SCEV *Stride = IV->getStepRecurrence(*this);
06638 
06639   // Avoid negative or zero stride values
06640   if (!isKnownPositive(Stride))
06641     return getCouldNotCompute();
06642 
06643   // Avoid proven overflow cases: this will ensure that the backedge taken count
06644   // will not generate any unsigned overflow. Relaxed no-overflow conditions
06645   // exploit NoWrapFlags, allowing to optimize in presence of undefined 
06646   // behaviors like the case of C language.
06647   if (!Stride->isOne() && doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap))
06648     return getCouldNotCompute();
06649 
06650   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT
06651                                       : ICmpInst::ICMP_ULT;
06652   const SCEV *Start = IV->getStart();
06653   const SCEV *End = RHS;
06654   if (!isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS))
06655     End = IsSigned ? getSMaxExpr(RHS, Start)
06656                    : getUMaxExpr(RHS, Start);
06657 
06658   const SCEV *BECount = computeBECount(getMinusSCEV(End, Start), Stride, false);
06659 
06660   APInt MinStart = IsSigned ? getSignedRange(Start).getSignedMin()
06661                             : getUnsignedRange(Start).getUnsignedMin();
06662 
06663   APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin()
06664                              : getUnsignedRange(Stride).getUnsignedMin();
06665 
06666   unsigned BitWidth = getTypeSizeInBits(LHS->getType());
06667   APInt Limit = IsSigned ? APInt::getSignedMaxValue(BitWidth) - (MinStride - 1)
06668                          : APInt::getMaxValue(BitWidth) - (MinStride - 1);
06669 
06670   // Although End can be a MAX expression we estimate MaxEnd considering only
06671   // the case End = RHS. This is safe because in the other case (End - Start)
06672   // is zero, leading to a zero maximum backedge taken count.
06673   APInt MaxEnd =
06674     IsSigned ? APIntOps::smin(getSignedRange(RHS).getSignedMax(), Limit)
06675              : APIntOps::umin(getUnsignedRange(RHS).getUnsignedMax(), Limit);
06676 
06677   const SCEV *MaxBECount;
06678   if (isa<SCEVConstant>(BECount))
06679     MaxBECount = BECount;
06680   else
06681     MaxBECount = computeBECount(getConstant(MaxEnd - MinStart),
06682                                 getConstant(MinStride), false);
06683 
06684   if (isa<SCEVCouldNotCompute>(MaxBECount))
06685     MaxBECount = BECount;
06686 
06687   return ExitLimit(BECount, MaxBECount, /*MustExit=*/true);
06688 }
06689 
06690 ScalarEvolution::ExitLimit
06691 ScalarEvolution::HowManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
06692                                      const Loop *L, bool IsSigned,
06693                                      bool IsSubExpr) {
06694   // We handle only IV > Invariant
06695   if (!isLoopInvariant(RHS, L))
06696     return getCouldNotCompute();
06697 
06698   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
06699 
06700   // Avoid weird loops
06701   if (!IV || IV->getLoop() != L || !IV->isAffine())
06702     return getCouldNotCompute();
06703 
06704   bool NoWrap = !IsSubExpr &&
06705                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
06706 
06707   const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
06708 
06709   // Avoid negative or zero stride values
06710   if (!isKnownPositive(Stride))
06711     return getCouldNotCompute();
06712 
06713   // Avoid proven overflow cases: this will ensure that the backedge taken count
06714   // will not generate any unsigned overflow. Relaxed no-overflow conditions
06715   // exploit NoWrapFlags, allowing to optimize in presence of undefined 
06716   // behaviors like the case of C language.
06717   if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap))
06718     return getCouldNotCompute();
06719 
06720   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT
06721                                       : ICmpInst::ICMP_UGT;
06722 
06723   const SCEV *Start = IV->getStart();
06724   const SCEV *End = RHS;
06725   if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS))
06726     End = IsSigned ? getSMinExpr(RHS, Start)
06727                    : getUMinExpr(RHS, Start);
06728 
06729   const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false);
06730 
06731   APInt MaxStart = IsSigned ? getSignedRange(Start).getSignedMax()
06732                             : getUnsignedRange(Start).getUnsignedMax();
06733 
06734   APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin()
06735                              : getUnsignedRange(Stride).getUnsignedMin();
06736 
06737   unsigned BitWidth = getTypeSizeInBits(LHS->getType());
06738   APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
06739                          : APInt::getMinValue(BitWidth) + (MinStride - 1);
06740 
06741   // Although End can be a MIN expression we estimate MinEnd considering only
06742   // the case End = RHS. This is safe because in the other case (Start - End)
06743   // is zero, leading to a zero maximum backedge taken count.
06744   APInt MinEnd =
06745     IsSigned ? APIntOps::smax(getSignedRange(RHS).getSignedMin(), Limit)
06746              : APIntOps::umax(getUnsignedRange(RHS).getUnsignedMin(), Limit);
06747 
06748 
06749   const SCEV *MaxBECount = getCouldNotCompute();
06750   if (isa<SCEVConstant>(BECount))
06751     MaxBECount = BECount;
06752   else
06753     MaxBECount = computeBECount(getConstant(MaxStart - MinEnd), 
06754                                 getConstant(MinStride), false);
06755 
06756   if (isa<SCEVCouldNotCompute>(MaxBECount))
06757     MaxBECount = BECount;
06758 
06759   return ExitLimit(BECount, MaxBECount, /*MustExit=*/true);
06760 }
06761 
06762 /// getNumIterationsInRange - Return the number of iterations of this loop that
06763 /// produce values in the specified constant range.  Another way of looking at
06764 /// this is that it returns the first iteration number where the value is not in
06765 /// the condition, thus computing the exit count. If the iteration count can't
06766 /// be computed, an instance of SCEVCouldNotCompute is returned.
06767 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
06768                                                     ScalarEvolution &SE) const {
06769   if (Range.isFullSet())  // Infinite loop.
06770     return SE.getCouldNotCompute();
06771 
06772   // If the start is a non-zero constant, shift the range to simplify things.
06773   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
06774     if (!SC->getValue()->isZero()) {
06775       SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
06776       Operands[0] = SE.getConstant(SC->getType(), 0);
06777       const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
06778                                              getNoWrapFlags(FlagNW));
06779       if (const SCEVAddRecExpr *ShiftedAddRec =
06780             dyn_cast<SCEVAddRecExpr>(Shifted))
06781         return ShiftedAddRec->getNumIterationsInRange(
06782                            Range.subtract(SC->getValue()->getValue()), SE);
06783       // This is strange and shouldn't happen.
06784       return SE.getCouldNotCompute();
06785     }
06786 
06787   // The only time we can solve this is when we have all constant indices.
06788   // Otherwise, we cannot determine the overflow conditions.
06789   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
06790     if (!isa<SCEVConstant>(getOperand(i)))
06791       return SE.getCouldNotCompute();
06792 
06793 
06794   // Okay at this point we know that all elements of the chrec are constants and
06795   // that the start element is zero.
06796 
06797   // First check to see if the range contains zero.  If not, the first
06798   // iteration exits.
06799   unsigned BitWidth = SE.getTypeSizeInBits(getType());
06800   if (!Range.contains(APInt(BitWidth, 0)))
06801     return SE.getConstant(getType(), 0);
06802 
06803   if (isAffine()) {
06804     // If this is an affine expression then we have this situation:
06805     //   Solve {0,+,A} in Range  ===  Ax in Range
06806 
06807     // We know that zero is in the range.  If A is positive then we know that
06808     // the upper value of the range must be the first possible exit value.
06809     // If A is negative then the lower of the range is the last possible loop
06810     // value.  Also note that we already checked for a full range.
06811     APInt One(BitWidth,1);
06812     APInt A     = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
06813     APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
06814 
06815     // The exit value should be (End+A)/A.
06816     APInt ExitVal = (End + A).udiv(A);
06817     ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
06818 
06819     // Evaluate at the exit value.  If we really did fall out of the valid
06820     // range, then we computed our trip count, otherwise wrap around or other
06821     // things must have happened.
06822     ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
06823     if (Range.contains(Val->getValue()))
06824       return SE.getCouldNotCompute();  // Something strange happened
06825 
06826     // Ensure that the previous value is in the range.  This is a sanity check.
06827     assert(Range.contains(
06828            EvaluateConstantChrecAtConstant(this,
06829            ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
06830            "Linear scev computation is off in a bad way!");
06831     return SE.getConstant(ExitValue);
06832   } else if (isQuadratic()) {
06833     // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
06834     // quadratic equation to solve it.  To do this, we must frame our problem in
06835     // terms of figuring out when zero is crossed, instead of when
06836     // Range.getUpper() is crossed.
06837     SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
06838     NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
06839     const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(),
06840                                              // getNoWrapFlags(FlagNW)
06841                                              FlagAnyWrap);
06842 
06843     // Next, solve the constructed addrec
06844     std::pair<const SCEV *,const SCEV *> Roots =
06845       SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
06846     const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
06847     const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
06848     if (R1) {
06849       // Pick the smallest positive root value.
06850       if (ConstantInt *CB =
06851           dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
06852                          R1->getValue(), R2->getValue()))) {
06853         if (CB->getZExtValue() == false)
06854           std::swap(R1, R2);   // R1 is the minimum root now.
06855 
06856         // Make sure the root is not off by one.  The returned iteration should
06857         // not be in the range, but the previous one should be.  When solving
06858         // for "X*X < 5", for example, we should not return a root of 2.
06859         ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
06860                                                              R1->getValue(),
06861                                                              SE);
06862         if (Range.contains(R1Val->getValue())) {
06863           // The next iteration must be out of the range...
06864           ConstantInt *NextVal =
06865                 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()+1);
06866 
06867           R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
06868           if (!Range.contains(R1Val->getValue()))
06869             return SE.getConstant(NextVal);
06870           return SE.getCouldNotCompute();  // Something strange happened
06871         }
06872 
06873         // If R1 was not in the range, then it is a good return value.  Make
06874         // sure that R1-1 WAS in the range though, just in case.
06875         ConstantInt *NextVal =
06876                ConstantInt::get(SE.getContext(), R1->getValue()->getValue()-1);
06877         R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
06878         if (Range.contains(R1Val->getValue()))
06879           return R1;
06880         return SE.getCouldNotCompute();  // Something strange happened
06881       }
06882     }
06883   }
06884 
06885   return SE.getCouldNotCompute();
06886 }
06887 
06888 namespace {
06889 struct FindUndefs {
06890   bool Found;
06891   FindUndefs() : Found(false) {}
06892 
06893   bool follow(const SCEV *S) {
06894     if (const SCEVUnknown *C = dyn_cast<SCEVUnknown>(S)) {
06895       if (isa<UndefValue>(C->getValue()))
06896         Found = true;
06897     } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
06898       if (isa<UndefValue>(C->getValue()))
06899         Found = true;
06900     }
06901 
06902     // Keep looking if we haven't found it yet.
06903     return !Found;
06904   }
06905   bool isDone() const {
06906     // Stop recursion if we have found an undef.
06907     return Found;
06908   }
06909 };
06910 }
06911 
06912 // Return true when S contains at least an undef value.
06913 static inline bool
06914 containsUndefs(const SCEV *S) {
06915   FindUndefs F;
06916   SCEVTraversal<FindUndefs> ST(F);
06917   ST.visitAll(S);
06918 
06919   return F.Found;
06920 }
06921 
06922 namespace {
06923 // Collect all steps of SCEV expressions.
06924 struct SCEVCollectStrides {
06925   ScalarEvolution &SE;
06926   SmallVectorImpl<const SCEV *> &Strides;
06927 
06928   SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S)
06929       : SE(SE), Strides(S) {}
06930 
06931   bool follow(const SCEV *S) {
06932     if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
06933       Strides.push_back(AR->getStepRecurrence(SE));
06934     return true;
06935   }
06936   bool isDone() const { return false; }
06937 };
06938 
06939 // Collect all SCEVUnknown and SCEVMulExpr expressions.
06940 struct SCEVCollectTerms {
06941   SmallVectorImpl<const SCEV *> &Terms;
06942 
06943   SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T)
06944       : Terms(T) {}
06945 
06946   bool follow(const SCEV *S) {
06947     if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S)) {
06948       if (!containsUndefs(S))
06949         Terms.push_back(S);
06950 
06951       // Stop recursion: once we collected a term, do not walk its operands.
06952       return false;
06953     }
06954 
06955     // Keep looking.
06956     return true;
06957   }
06958   bool isDone() const { return false; }
06959 };
06960 }
06961 
06962 /// Find parametric terms in this SCEVAddRecExpr.
06963