LLVM API Documentation

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