xref: /llvm-project/llvm/lib/Analysis/ScalarEvolution.cpp (revision e3e1a35f68f0053e24725e30f4f6a4496efab324)
1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains the implementation of the scalar evolution analysis
11 // engine, which is used primarily to analyze expressions involving induction
12 // variables in loops.
13 //
14 // There are several aspects to this library.  First is the representation of
15 // scalar expressions, which are represented as subclasses of the SCEV class.
16 // These classes are used to represent certain types of subexpressions that we
17 // can handle. We only create one SCEV of a particular shape, so
18 // pointer-comparisons for equality are legal.
19 //
20 // One important aspect of the SCEV objects is that they are never cyclic, even
21 // if there is a cycle in the dataflow for an expression (ie, a PHI node).  If
22 // the PHI node is one of the idioms that we can represent (e.g., a polynomial
23 // recurrence) then we represent it directly as a recurrence node, otherwise we
24 // represent it as a SCEVUnknown node.
25 //
26 // In addition to being able to represent expressions of various types, we also
27 // have folders that are used to build the *canonical* representation for a
28 // particular expression.  These folders are capable of using a variety of
29 // rewrite rules to simplify the expressions.
30 //
31 // Once the folders are defined, we can implement the more interesting
32 // higher-level code, such as the code that recognizes PHI nodes of various
33 // types, computes the execution count of a loop, etc.
34 //
35 // TODO: We should use these routines and value representations to implement
36 // dependence analysis!
37 //
38 //===----------------------------------------------------------------------===//
39 //
40 // There are several good references for the techniques used in this analysis.
41 //
42 //  Chains of recurrences -- a method to expedite the evaluation
43 //  of closed-form functions
44 //  Olaf Bachmann, Paul S. Wang, Eugene V. Zima
45 //
46 //  On computational properties of chains of recurrences
47 //  Eugene V. Zima
48 //
49 //  Symbolic Evaluation of Chains of Recurrences for Loop Optimization
50 //  Robert A. van Engelen
51 //
52 //  Efficient Symbolic Analysis for Optimizing Compilers
53 //  Robert A. van Engelen
54 //
55 //  Using the chains of recurrences algebra for data dependence testing and
56 //  induction variable substitution
57 //  MS Thesis, Johnie Birch
58 //
59 //===----------------------------------------------------------------------===//
60 
61 #include "llvm/Analysis/ScalarEvolution.h"
62 #include "llvm/ADT/Optional.h"
63 #include "llvm/ADT/STLExtras.h"
64 #include "llvm/ADT/ScopeExit.h"
65 #include "llvm/ADT/Sequence.h"
66 #include "llvm/ADT/SmallPtrSet.h"
67 #include "llvm/ADT/Statistic.h"
68 #include "llvm/Analysis/AssumptionCache.h"
69 #include "llvm/Analysis/ConstantFolding.h"
70 #include "llvm/Analysis/InstructionSimplify.h"
71 #include "llvm/Analysis/LoopInfo.h"
72 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
73 #include "llvm/Analysis/TargetLibraryInfo.h"
74 #include "llvm/Analysis/ValueTracking.h"
75 #include "llvm/IR/ConstantRange.h"
76 #include "llvm/IR/Constants.h"
77 #include "llvm/IR/DataLayout.h"
78 #include "llvm/IR/DerivedTypes.h"
79 #include "llvm/IR/Dominators.h"
80 #include "llvm/IR/GetElementPtrTypeIterator.h"
81 #include "llvm/IR/GlobalAlias.h"
82 #include "llvm/IR/GlobalVariable.h"
83 #include "llvm/IR/InstIterator.h"
84 #include "llvm/IR/Instructions.h"
85 #include "llvm/IR/LLVMContext.h"
86 #include "llvm/IR/Metadata.h"
87 #include "llvm/IR/Operator.h"
88 #include "llvm/IR/PatternMatch.h"
89 #include "llvm/Support/CommandLine.h"
90 #include "llvm/Support/Debug.h"
91 #include "llvm/Support/ErrorHandling.h"
92 #include "llvm/Support/KnownBits.h"
93 #include "llvm/Support/MathExtras.h"
94 #include "llvm/Support/raw_ostream.h"
95 #include "llvm/Support/SaveAndRestore.h"
96 #include <algorithm>
97 using namespace llvm;
98 
99 #define DEBUG_TYPE "scalar-evolution"
100 
101 STATISTIC(NumArrayLenItCounts,
102           "Number of trip counts computed with array length");
103 STATISTIC(NumTripCountsComputed,
104           "Number of loops with predictable loop counts");
105 STATISTIC(NumTripCountsNotComputed,
106           "Number of loops without predictable loop counts");
107 STATISTIC(NumBruteForceTripCountsComputed,
108           "Number of loops with trip counts computed by force");
109 
110 static cl::opt<unsigned>
111 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
112                         cl::desc("Maximum number of iterations SCEV will "
113                                  "symbolically execute a constant "
114                                  "derived loop"),
115                         cl::init(100));
116 
117 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean.
118 static cl::opt<bool>
119 VerifySCEV("verify-scev",
120            cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
121 static cl::opt<bool>
122     VerifySCEVMap("verify-scev-maps",
123                   cl::desc("Verify no dangling value in ScalarEvolution's "
124                            "ExprValueMap (slow)"));
125 
126 static cl::opt<unsigned> MulOpsInlineThreshold(
127     "scev-mulops-inline-threshold", cl::Hidden,
128     cl::desc("Threshold for inlining multiplication operands into a SCEV"),
129     cl::init(1000));
130 
131 static cl::opt<unsigned> AddOpsInlineThreshold(
132     "scev-addops-inline-threshold", cl::Hidden,
133     cl::desc("Threshold for inlining multiplication operands into a SCEV"),
134     cl::init(500));
135 
136 static cl::opt<unsigned> MaxSCEVCompareDepth(
137     "scalar-evolution-max-scev-compare-depth", cl::Hidden,
138     cl::desc("Maximum depth of recursive SCEV complexity comparisons"),
139     cl::init(32));
140 
141 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth(
142     "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden,
143     cl::desc("Maximum depth of recursive SCEV operations implication analysis"),
144     cl::init(2));
145 
146 static cl::opt<unsigned> MaxValueCompareDepth(
147     "scalar-evolution-max-value-compare-depth", cl::Hidden,
148     cl::desc("Maximum depth of recursive value complexity comparisons"),
149     cl::init(2));
150 
151 static cl::opt<unsigned>
152     MaxAddExprDepth("scalar-evolution-max-addexpr-depth", cl::Hidden,
153                     cl::desc("Maximum depth of recursive AddExpr"),
154                     cl::init(32));
155 
156 static cl::opt<unsigned> MaxConstantEvolvingDepth(
157     "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
158     cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
159 
160 //===----------------------------------------------------------------------===//
161 //                           SCEV class definitions
162 //===----------------------------------------------------------------------===//
163 
164 //===----------------------------------------------------------------------===//
165 // Implementation of the SCEV class.
166 //
167 
168 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
169 LLVM_DUMP_METHOD void SCEV::dump() const {
170   print(dbgs());
171   dbgs() << '\n';
172 }
173 #endif
174 
175 void SCEV::print(raw_ostream &OS) const {
176   switch (static_cast<SCEVTypes>(getSCEVType())) {
177   case scConstant:
178     cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
179     return;
180   case scTruncate: {
181     const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
182     const SCEV *Op = Trunc->getOperand();
183     OS << "(trunc " << *Op->getType() << " " << *Op << " to "
184        << *Trunc->getType() << ")";
185     return;
186   }
187   case scZeroExtend: {
188     const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
189     const SCEV *Op = ZExt->getOperand();
190     OS << "(zext " << *Op->getType() << " " << *Op << " to "
191        << *ZExt->getType() << ")";
192     return;
193   }
194   case scSignExtend: {
195     const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
196     const SCEV *Op = SExt->getOperand();
197     OS << "(sext " << *Op->getType() << " " << *Op << " to "
198        << *SExt->getType() << ")";
199     return;
200   }
201   case scAddRecExpr: {
202     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
203     OS << "{" << *AR->getOperand(0);
204     for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
205       OS << ",+," << *AR->getOperand(i);
206     OS << "}<";
207     if (AR->hasNoUnsignedWrap())
208       OS << "nuw><";
209     if (AR->hasNoSignedWrap())
210       OS << "nsw><";
211     if (AR->hasNoSelfWrap() &&
212         !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
213       OS << "nw><";
214     AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
215     OS << ">";
216     return;
217   }
218   case scAddExpr:
219   case scMulExpr:
220   case scUMaxExpr:
221   case scSMaxExpr: {
222     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
223     const char *OpStr = nullptr;
224     switch (NAry->getSCEVType()) {
225     case scAddExpr: OpStr = " + "; break;
226     case scMulExpr: OpStr = " * "; break;
227     case scUMaxExpr: OpStr = " umax "; break;
228     case scSMaxExpr: OpStr = " smax "; break;
229     }
230     OS << "(";
231     for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
232          I != E; ++I) {
233       OS << **I;
234       if (std::next(I) != E)
235         OS << OpStr;
236     }
237     OS << ")";
238     switch (NAry->getSCEVType()) {
239     case scAddExpr:
240     case scMulExpr:
241       if (NAry->hasNoUnsignedWrap())
242         OS << "<nuw>";
243       if (NAry->hasNoSignedWrap())
244         OS << "<nsw>";
245     }
246     return;
247   }
248   case scUDivExpr: {
249     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
250     OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
251     return;
252   }
253   case scUnknown: {
254     const SCEVUnknown *U = cast<SCEVUnknown>(this);
255     Type *AllocTy;
256     if (U->isSizeOf(AllocTy)) {
257       OS << "sizeof(" << *AllocTy << ")";
258       return;
259     }
260     if (U->isAlignOf(AllocTy)) {
261       OS << "alignof(" << *AllocTy << ")";
262       return;
263     }
264 
265     Type *CTy;
266     Constant *FieldNo;
267     if (U->isOffsetOf(CTy, FieldNo)) {
268       OS << "offsetof(" << *CTy << ", ";
269       FieldNo->printAsOperand(OS, false);
270       OS << ")";
271       return;
272     }
273 
274     // Otherwise just print it normally.
275     U->getValue()->printAsOperand(OS, false);
276     return;
277   }
278   case scCouldNotCompute:
279     OS << "***COULDNOTCOMPUTE***";
280     return;
281   }
282   llvm_unreachable("Unknown SCEV kind!");
283 }
284 
285 Type *SCEV::getType() const {
286   switch (static_cast<SCEVTypes>(getSCEVType())) {
287   case scConstant:
288     return cast<SCEVConstant>(this)->getType();
289   case scTruncate:
290   case scZeroExtend:
291   case scSignExtend:
292     return cast<SCEVCastExpr>(this)->getType();
293   case scAddRecExpr:
294   case scMulExpr:
295   case scUMaxExpr:
296   case scSMaxExpr:
297     return cast<SCEVNAryExpr>(this)->getType();
298   case scAddExpr:
299     return cast<SCEVAddExpr>(this)->getType();
300   case scUDivExpr:
301     return cast<SCEVUDivExpr>(this)->getType();
302   case scUnknown:
303     return cast<SCEVUnknown>(this)->getType();
304   case scCouldNotCompute:
305     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
306   }
307   llvm_unreachable("Unknown SCEV kind!");
308 }
309 
310 bool SCEV::isZero() const {
311   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
312     return SC->getValue()->isZero();
313   return false;
314 }
315 
316 bool SCEV::isOne() const {
317   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
318     return SC->getValue()->isOne();
319   return false;
320 }
321 
322 bool SCEV::isAllOnesValue() const {
323   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
324     return SC->getValue()->isAllOnesValue();
325   return false;
326 }
327 
328 bool SCEV::isNonConstantNegative() const {
329   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
330   if (!Mul) return false;
331 
332   // If there is a constant factor, it will be first.
333   const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
334   if (!SC) return false;
335 
336   // Return true if the value is negative, this matches things like (-42 * V).
337   return SC->getAPInt().isNegative();
338 }
339 
340 SCEVCouldNotCompute::SCEVCouldNotCompute() :
341   SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {}
342 
343 bool SCEVCouldNotCompute::classof(const SCEV *S) {
344   return S->getSCEVType() == scCouldNotCompute;
345 }
346 
347 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
348   FoldingSetNodeID ID;
349   ID.AddInteger(scConstant);
350   ID.AddPointer(V);
351   void *IP = nullptr;
352   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
353   SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
354   UniqueSCEVs.InsertNode(S, IP);
355   return S;
356 }
357 
358 const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
359   return getConstant(ConstantInt::get(getContext(), Val));
360 }
361 
362 const SCEV *
363 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
364   IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
365   return getConstant(ConstantInt::get(ITy, V, isSigned));
366 }
367 
368 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
369                            unsigned SCEVTy, const SCEV *op, Type *ty)
370   : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
371 
372 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
373                                    const SCEV *op, Type *ty)
374   : SCEVCastExpr(ID, scTruncate, op, ty) {
375   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
376          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
377          "Cannot truncate non-integer value!");
378 }
379 
380 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
381                                        const SCEV *op, Type *ty)
382   : SCEVCastExpr(ID, scZeroExtend, op, ty) {
383   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
384          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
385          "Cannot zero extend non-integer value!");
386 }
387 
388 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
389                                        const SCEV *op, Type *ty)
390   : SCEVCastExpr(ID, scSignExtend, op, ty) {
391   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
392          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
393          "Cannot sign extend non-integer value!");
394 }
395 
396 void SCEVUnknown::deleted() {
397   // Clear this SCEVUnknown from various maps.
398   SE->forgetMemoizedResults(this);
399 
400   // Remove this SCEVUnknown from the uniquing map.
401   SE->UniqueSCEVs.RemoveNode(this);
402 
403   // Release the value.
404   setValPtr(nullptr);
405 }
406 
407 void SCEVUnknown::allUsesReplacedWith(Value *New) {
408   // Clear this SCEVUnknown from various maps.
409   SE->forgetMemoizedResults(this);
410 
411   // Remove this SCEVUnknown from the uniquing map.
412   SE->UniqueSCEVs.RemoveNode(this);
413 
414   // Update this SCEVUnknown to point to the new value. This is needed
415   // because there may still be outstanding SCEVs which still point to
416   // this SCEVUnknown.
417   setValPtr(New);
418 }
419 
420 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
421   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
422     if (VCE->getOpcode() == Instruction::PtrToInt)
423       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
424         if (CE->getOpcode() == Instruction::GetElementPtr &&
425             CE->getOperand(0)->isNullValue() &&
426             CE->getNumOperands() == 2)
427           if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
428             if (CI->isOne()) {
429               AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
430                                  ->getElementType();
431               return true;
432             }
433 
434   return false;
435 }
436 
437 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
438   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
439     if (VCE->getOpcode() == Instruction::PtrToInt)
440       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
441         if (CE->getOpcode() == Instruction::GetElementPtr &&
442             CE->getOperand(0)->isNullValue()) {
443           Type *Ty =
444             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
445           if (StructType *STy = dyn_cast<StructType>(Ty))
446             if (!STy->isPacked() &&
447                 CE->getNumOperands() == 3 &&
448                 CE->getOperand(1)->isNullValue()) {
449               if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
450                 if (CI->isOne() &&
451                     STy->getNumElements() == 2 &&
452                     STy->getElementType(0)->isIntegerTy(1)) {
453                   AllocTy = STy->getElementType(1);
454                   return true;
455                 }
456             }
457         }
458 
459   return false;
460 }
461 
462 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
463   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
464     if (VCE->getOpcode() == Instruction::PtrToInt)
465       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
466         if (CE->getOpcode() == Instruction::GetElementPtr &&
467             CE->getNumOperands() == 3 &&
468             CE->getOperand(0)->isNullValue() &&
469             CE->getOperand(1)->isNullValue()) {
470           Type *Ty =
471             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
472           // Ignore vector types here so that ScalarEvolutionExpander doesn't
473           // emit getelementptrs that index into vectors.
474           if (Ty->isStructTy() || Ty->isArrayTy()) {
475             CTy = Ty;
476             FieldNo = CE->getOperand(2);
477             return true;
478           }
479         }
480 
481   return false;
482 }
483 
484 //===----------------------------------------------------------------------===//
485 //                               SCEV Utilities
486 //===----------------------------------------------------------------------===//
487 
488 /// Compare the two values \p LV and \p RV in terms of their "complexity" where
489 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order
490 /// operands in SCEV expressions.  \p EqCache is a set of pairs of values that
491 /// have been previously deemed to be "equally complex" by this routine.  It is
492 /// intended to avoid exponential time complexity in cases like:
493 ///
494 ///   %a = f(%x, %y)
495 ///   %b = f(%a, %a)
496 ///   %c = f(%b, %b)
497 ///
498 ///   %d = f(%x, %y)
499 ///   %e = f(%d, %d)
500 ///   %f = f(%e, %e)
501 ///
502 ///   CompareValueComplexity(%f, %c)
503 ///
504 /// Since we do not continue running this routine on expression trees once we
505 /// have seen unequal values, there is no need to track them in the cache.
506 static int
507 CompareValueComplexity(SmallSet<std::pair<Value *, Value *>, 8> &EqCache,
508                        const LoopInfo *const LI, Value *LV, Value *RV,
509                        unsigned Depth) {
510   if (Depth > MaxValueCompareDepth || EqCache.count({LV, RV}))
511     return 0;
512 
513   // Order pointer values after integer values. This helps SCEVExpander form
514   // GEPs.
515   bool LIsPointer = LV->getType()->isPointerTy(),
516        RIsPointer = RV->getType()->isPointerTy();
517   if (LIsPointer != RIsPointer)
518     return (int)LIsPointer - (int)RIsPointer;
519 
520   // Compare getValueID values.
521   unsigned LID = LV->getValueID(), RID = RV->getValueID();
522   if (LID != RID)
523     return (int)LID - (int)RID;
524 
525   // Sort arguments by their position.
526   if (const auto *LA = dyn_cast<Argument>(LV)) {
527     const auto *RA = cast<Argument>(RV);
528     unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
529     return (int)LArgNo - (int)RArgNo;
530   }
531 
532   if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
533     const auto *RGV = cast<GlobalValue>(RV);
534 
535     const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
536       auto LT = GV->getLinkage();
537       return !(GlobalValue::isPrivateLinkage(LT) ||
538                GlobalValue::isInternalLinkage(LT));
539     };
540 
541     // Use the names to distinguish the two values, but only if the
542     // names are semantically important.
543     if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
544       return LGV->getName().compare(RGV->getName());
545   }
546 
547   // For instructions, compare their loop depth, and their operand count.  This
548   // is pretty loose.
549   if (const auto *LInst = dyn_cast<Instruction>(LV)) {
550     const auto *RInst = cast<Instruction>(RV);
551 
552     // Compare loop depths.
553     const BasicBlock *LParent = LInst->getParent(),
554                      *RParent = RInst->getParent();
555     if (LParent != RParent) {
556       unsigned LDepth = LI->getLoopDepth(LParent),
557                RDepth = LI->getLoopDepth(RParent);
558       if (LDepth != RDepth)
559         return (int)LDepth - (int)RDepth;
560     }
561 
562     // Compare the number of operands.
563     unsigned LNumOps = LInst->getNumOperands(),
564              RNumOps = RInst->getNumOperands();
565     if (LNumOps != RNumOps)
566       return (int)LNumOps - (int)RNumOps;
567 
568     for (unsigned Idx : seq(0u, LNumOps)) {
569       int Result =
570           CompareValueComplexity(EqCache, LI, LInst->getOperand(Idx),
571                                  RInst->getOperand(Idx), Depth + 1);
572       if (Result != 0)
573         return Result;
574     }
575   }
576 
577   EqCache.insert({LV, RV});
578   return 0;
579 }
580 
581 // Return negative, zero, or positive, if LHS is less than, equal to, or greater
582 // than RHS, respectively. A three-way result allows recursive comparisons to be
583 // more efficient.
584 static int CompareSCEVComplexity(
585     SmallSet<std::pair<const SCEV *, const SCEV *>, 8> &EqCacheSCEV,
586     const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS,
587     unsigned Depth = 0) {
588   // Fast-path: SCEVs are uniqued so we can do a quick equality check.
589   if (LHS == RHS)
590     return 0;
591 
592   // Primarily, sort the SCEVs by their getSCEVType().
593   unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
594   if (LType != RType)
595     return (int)LType - (int)RType;
596 
597   if (Depth > MaxSCEVCompareDepth || EqCacheSCEV.count({LHS, RHS}))
598     return 0;
599   // Aside from the getSCEVType() ordering, the particular ordering
600   // isn't very important except that it's beneficial to be consistent,
601   // so that (a + b) and (b + a) don't end up as different expressions.
602   switch (static_cast<SCEVTypes>(LType)) {
603   case scUnknown: {
604     const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
605     const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
606 
607     SmallSet<std::pair<Value *, Value *>, 8> EqCache;
608     int X = CompareValueComplexity(EqCache, LI, LU->getValue(), RU->getValue(),
609                                    Depth + 1);
610     if (X == 0)
611       EqCacheSCEV.insert({LHS, RHS});
612     return X;
613   }
614 
615   case scConstant: {
616     const SCEVConstant *LC = cast<SCEVConstant>(LHS);
617     const SCEVConstant *RC = cast<SCEVConstant>(RHS);
618 
619     // Compare constant values.
620     const APInt &LA = LC->getAPInt();
621     const APInt &RA = RC->getAPInt();
622     unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
623     if (LBitWidth != RBitWidth)
624       return (int)LBitWidth - (int)RBitWidth;
625     return LA.ult(RA) ? -1 : 1;
626   }
627 
628   case scAddRecExpr: {
629     const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
630     const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
631 
632     // Compare addrec loop depths.
633     const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
634     if (LLoop != RLoop) {
635       unsigned LDepth = LLoop->getLoopDepth(), RDepth = RLoop->getLoopDepth();
636       if (LDepth != RDepth)
637         return (int)LDepth - (int)RDepth;
638     }
639 
640     // Addrec complexity grows with operand count.
641     unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
642     if (LNumOps != RNumOps)
643       return (int)LNumOps - (int)RNumOps;
644 
645     // Lexicographically compare.
646     for (unsigned i = 0; i != LNumOps; ++i) {
647       int X = CompareSCEVComplexity(EqCacheSCEV, LI, LA->getOperand(i),
648                                     RA->getOperand(i), Depth + 1);
649       if (X != 0)
650         return X;
651     }
652     EqCacheSCEV.insert({LHS, RHS});
653     return 0;
654   }
655 
656   case scAddExpr:
657   case scMulExpr:
658   case scSMaxExpr:
659   case scUMaxExpr: {
660     const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
661     const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
662 
663     // Lexicographically compare n-ary expressions.
664     unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
665     if (LNumOps != RNumOps)
666       return (int)LNumOps - (int)RNumOps;
667 
668     for (unsigned i = 0; i != LNumOps; ++i) {
669       if (i >= RNumOps)
670         return 1;
671       int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getOperand(i),
672                                     RC->getOperand(i), Depth + 1);
673       if (X != 0)
674         return X;
675     }
676     EqCacheSCEV.insert({LHS, RHS});
677     return 0;
678   }
679 
680   case scUDivExpr: {
681     const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
682     const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
683 
684     // Lexicographically compare udiv expressions.
685     int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getLHS(), RC->getLHS(),
686                                   Depth + 1);
687     if (X != 0)
688       return X;
689     X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getRHS(), RC->getRHS(),
690                               Depth + 1);
691     if (X == 0)
692       EqCacheSCEV.insert({LHS, RHS});
693     return X;
694   }
695 
696   case scTruncate:
697   case scZeroExtend:
698   case scSignExtend: {
699     const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
700     const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
701 
702     // Compare cast expressions by operand.
703     int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getOperand(),
704                                   RC->getOperand(), Depth + 1);
705     if (X == 0)
706       EqCacheSCEV.insert({LHS, RHS});
707     return X;
708   }
709 
710   case scCouldNotCompute:
711     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
712   }
713   llvm_unreachable("Unknown SCEV kind!");
714 }
715 
716 /// Given a list of SCEV objects, order them by their complexity, and group
717 /// objects of the same complexity together by value.  When this routine is
718 /// finished, we know that any duplicates in the vector are consecutive and that
719 /// complexity is monotonically increasing.
720 ///
721 /// Note that we go take special precautions to ensure that we get deterministic
722 /// results from this routine.  In other words, we don't want the results of
723 /// this to depend on where the addresses of various SCEV objects happened to
724 /// land in memory.
725 ///
726 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
727                               LoopInfo *LI) {
728   if (Ops.size() < 2) return;  // Noop
729 
730   SmallSet<std::pair<const SCEV *, const SCEV *>, 8> EqCache;
731   if (Ops.size() == 2) {
732     // This is the common case, which also happens to be trivially simple.
733     // Special case it.
734     const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
735     if (CompareSCEVComplexity(EqCache, LI, RHS, LHS) < 0)
736       std::swap(LHS, RHS);
737     return;
738   }
739 
740   // Do the rough sort by complexity.
741   std::stable_sort(Ops.begin(), Ops.end(),
742                    [&EqCache, LI](const SCEV *LHS, const SCEV *RHS) {
743                      return CompareSCEVComplexity(EqCache, LI, LHS, RHS) < 0;
744                    });
745 
746   // Now that we are sorted by complexity, group elements of the same
747   // complexity.  Note that this is, at worst, N^2, but the vector is likely to
748   // be extremely short in practice.  Note that we take this approach because we
749   // do not want to depend on the addresses of the objects we are grouping.
750   for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
751     const SCEV *S = Ops[i];
752     unsigned Complexity = S->getSCEVType();
753 
754     // If there are any objects of the same complexity and same value as this
755     // one, group them.
756     for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
757       if (Ops[j] == S) { // Found a duplicate.
758         // Move it to immediately after i'th element.
759         std::swap(Ops[i+1], Ops[j]);
760         ++i;   // no need to rescan it.
761         if (i == e-2) return;  // Done!
762       }
763     }
764   }
765 }
766 
767 // Returns the size of the SCEV S.
768 static inline int sizeOfSCEV(const SCEV *S) {
769   struct FindSCEVSize {
770     int Size;
771     FindSCEVSize() : Size(0) {}
772 
773     bool follow(const SCEV *S) {
774       ++Size;
775       // Keep looking at all operands of S.
776       return true;
777     }
778     bool isDone() const {
779       return false;
780     }
781   };
782 
783   FindSCEVSize F;
784   SCEVTraversal<FindSCEVSize> ST(F);
785   ST.visitAll(S);
786   return F.Size;
787 }
788 
789 namespace {
790 
791 struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> {
792 public:
793   // Computes the Quotient and Remainder of the division of Numerator by
794   // Denominator.
795   static void divide(ScalarEvolution &SE, const SCEV *Numerator,
796                      const SCEV *Denominator, const SCEV **Quotient,
797                      const SCEV **Remainder) {
798     assert(Numerator && Denominator && "Uninitialized SCEV");
799 
800     SCEVDivision D(SE, Numerator, Denominator);
801 
802     // Check for the trivial case here to avoid having to check for it in the
803     // rest of the code.
804     if (Numerator == Denominator) {
805       *Quotient = D.One;
806       *Remainder = D.Zero;
807       return;
808     }
809 
810     if (Numerator->isZero()) {
811       *Quotient = D.Zero;
812       *Remainder = D.Zero;
813       return;
814     }
815 
816     // A simple case when N/1. The quotient is N.
817     if (Denominator->isOne()) {
818       *Quotient = Numerator;
819       *Remainder = D.Zero;
820       return;
821     }
822 
823     // Split the Denominator when it is a product.
824     if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) {
825       const SCEV *Q, *R;
826       *Quotient = Numerator;
827       for (const SCEV *Op : T->operands()) {
828         divide(SE, *Quotient, Op, &Q, &R);
829         *Quotient = Q;
830 
831         // Bail out when the Numerator is not divisible by one of the terms of
832         // the Denominator.
833         if (!R->isZero()) {
834           *Quotient = D.Zero;
835           *Remainder = Numerator;
836           return;
837         }
838       }
839       *Remainder = D.Zero;
840       return;
841     }
842 
843     D.visit(Numerator);
844     *Quotient = D.Quotient;
845     *Remainder = D.Remainder;
846   }
847 
848   // Except in the trivial case described above, we do not know how to divide
849   // Expr by Denominator for the following functions with empty implementation.
850   void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {}
851   void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {}
852   void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {}
853   void visitUDivExpr(const SCEVUDivExpr *Numerator) {}
854   void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {}
855   void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {}
856   void visitUnknown(const SCEVUnknown *Numerator) {}
857   void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {}
858 
859   void visitConstant(const SCEVConstant *Numerator) {
860     if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) {
861       APInt NumeratorVal = Numerator->getAPInt();
862       APInt DenominatorVal = D->getAPInt();
863       uint32_t NumeratorBW = NumeratorVal.getBitWidth();
864       uint32_t DenominatorBW = DenominatorVal.getBitWidth();
865 
866       if (NumeratorBW > DenominatorBW)
867         DenominatorVal = DenominatorVal.sext(NumeratorBW);
868       else if (NumeratorBW < DenominatorBW)
869         NumeratorVal = NumeratorVal.sext(DenominatorBW);
870 
871       APInt QuotientVal(NumeratorVal.getBitWidth(), 0);
872       APInt RemainderVal(NumeratorVal.getBitWidth(), 0);
873       APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal);
874       Quotient = SE.getConstant(QuotientVal);
875       Remainder = SE.getConstant(RemainderVal);
876       return;
877     }
878   }
879 
880   void visitAddRecExpr(const SCEVAddRecExpr *Numerator) {
881     const SCEV *StartQ, *StartR, *StepQ, *StepR;
882     if (!Numerator->isAffine())
883       return cannotDivide(Numerator);
884     divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR);
885     divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR);
886     // Bail out if the types do not match.
887     Type *Ty = Denominator->getType();
888     if (Ty != StartQ->getType() || Ty != StartR->getType() ||
889         Ty != StepQ->getType() || Ty != StepR->getType())
890       return cannotDivide(Numerator);
891     Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(),
892                                 Numerator->getNoWrapFlags());
893     Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(),
894                                  Numerator->getNoWrapFlags());
895   }
896 
897   void visitAddExpr(const SCEVAddExpr *Numerator) {
898     SmallVector<const SCEV *, 2> Qs, Rs;
899     Type *Ty = Denominator->getType();
900 
901     for (const SCEV *Op : Numerator->operands()) {
902       const SCEV *Q, *R;
903       divide(SE, Op, Denominator, &Q, &R);
904 
905       // Bail out if types do not match.
906       if (Ty != Q->getType() || Ty != R->getType())
907         return cannotDivide(Numerator);
908 
909       Qs.push_back(Q);
910       Rs.push_back(R);
911     }
912 
913     if (Qs.size() == 1) {
914       Quotient = Qs[0];
915       Remainder = Rs[0];
916       return;
917     }
918 
919     Quotient = SE.getAddExpr(Qs);
920     Remainder = SE.getAddExpr(Rs);
921   }
922 
923   void visitMulExpr(const SCEVMulExpr *Numerator) {
924     SmallVector<const SCEV *, 2> Qs;
925     Type *Ty = Denominator->getType();
926 
927     bool FoundDenominatorTerm = false;
928     for (const SCEV *Op : Numerator->operands()) {
929       // Bail out if types do not match.
930       if (Ty != Op->getType())
931         return cannotDivide(Numerator);
932 
933       if (FoundDenominatorTerm) {
934         Qs.push_back(Op);
935         continue;
936       }
937 
938       // Check whether Denominator divides one of the product operands.
939       const SCEV *Q, *R;
940       divide(SE, Op, Denominator, &Q, &R);
941       if (!R->isZero()) {
942         Qs.push_back(Op);
943         continue;
944       }
945 
946       // Bail out if types do not match.
947       if (Ty != Q->getType())
948         return cannotDivide(Numerator);
949 
950       FoundDenominatorTerm = true;
951       Qs.push_back(Q);
952     }
953 
954     if (FoundDenominatorTerm) {
955       Remainder = Zero;
956       if (Qs.size() == 1)
957         Quotient = Qs[0];
958       else
959         Quotient = SE.getMulExpr(Qs);
960       return;
961     }
962 
963     if (!isa<SCEVUnknown>(Denominator))
964       return cannotDivide(Numerator);
965 
966     // The Remainder is obtained by replacing Denominator by 0 in Numerator.
967     ValueToValueMap RewriteMap;
968     RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
969         cast<SCEVConstant>(Zero)->getValue();
970     Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
971 
972     if (Remainder->isZero()) {
973       // The Quotient is obtained by replacing Denominator by 1 in Numerator.
974       RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
975           cast<SCEVConstant>(One)->getValue();
976       Quotient =
977           SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
978       return;
979     }
980 
981     // Quotient is (Numerator - Remainder) divided by Denominator.
982     const SCEV *Q, *R;
983     const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder);
984     // This SCEV does not seem to simplify: fail the division here.
985     if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator))
986       return cannotDivide(Numerator);
987     divide(SE, Diff, Denominator, &Q, &R);
988     if (R != Zero)
989       return cannotDivide(Numerator);
990     Quotient = Q;
991   }
992 
993 private:
994   SCEVDivision(ScalarEvolution &S, const SCEV *Numerator,
995                const SCEV *Denominator)
996       : SE(S), Denominator(Denominator) {
997     Zero = SE.getZero(Denominator->getType());
998     One = SE.getOne(Denominator->getType());
999 
1000     // We generally do not know how to divide Expr by Denominator. We
1001     // initialize the division to a "cannot divide" state to simplify the rest
1002     // of the code.
1003     cannotDivide(Numerator);
1004   }
1005 
1006   // Convenience function for giving up on the division. We set the quotient to
1007   // be equal to zero and the remainder to be equal to the numerator.
1008   void cannotDivide(const SCEV *Numerator) {
1009     Quotient = Zero;
1010     Remainder = Numerator;
1011   }
1012 
1013   ScalarEvolution &SE;
1014   const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One;
1015 };
1016 
1017 }
1018 
1019 //===----------------------------------------------------------------------===//
1020 //                      Simple SCEV method implementations
1021 //===----------------------------------------------------------------------===//
1022 
1023 /// Compute BC(It, K).  The result has width W.  Assume, K > 0.
1024 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
1025                                        ScalarEvolution &SE,
1026                                        Type *ResultTy) {
1027   // Handle the simplest case efficiently.
1028   if (K == 1)
1029     return SE.getTruncateOrZeroExtend(It, ResultTy);
1030 
1031   // We are using the following formula for BC(It, K):
1032   //
1033   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
1034   //
1035   // Suppose, W is the bitwidth of the return value.  We must be prepared for
1036   // overflow.  Hence, we must assure that the result of our computation is
1037   // equal to the accurate one modulo 2^W.  Unfortunately, division isn't
1038   // safe in modular arithmetic.
1039   //
1040   // However, this code doesn't use exactly that formula; the formula it uses
1041   // is something like the following, where T is the number of factors of 2 in
1042   // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
1043   // exponentiation:
1044   //
1045   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
1046   //
1047   // This formula is trivially equivalent to the previous formula.  However,
1048   // this formula can be implemented much more efficiently.  The trick is that
1049   // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
1050   // arithmetic.  To do exact division in modular arithmetic, all we have
1051   // to do is multiply by the inverse.  Therefore, this step can be done at
1052   // width W.
1053   //
1054   // The next issue is how to safely do the division by 2^T.  The way this
1055   // is done is by doing the multiplication step at a width of at least W + T
1056   // bits.  This way, the bottom W+T bits of the product are accurate. Then,
1057   // when we perform the division by 2^T (which is equivalent to a right shift
1058   // by T), the bottom W bits are accurate.  Extra bits are okay; they'll get
1059   // truncated out after the division by 2^T.
1060   //
1061   // In comparison to just directly using the first formula, this technique
1062   // is much more efficient; using the first formula requires W * K bits,
1063   // but this formula less than W + K bits. Also, the first formula requires
1064   // a division step, whereas this formula only requires multiplies and shifts.
1065   //
1066   // It doesn't matter whether the subtraction step is done in the calculation
1067   // width or the input iteration count's width; if the subtraction overflows,
1068   // the result must be zero anyway.  We prefer here to do it in the width of
1069   // the induction variable because it helps a lot for certain cases; CodeGen
1070   // isn't smart enough to ignore the overflow, which leads to much less
1071   // efficient code if the width of the subtraction is wider than the native
1072   // register width.
1073   //
1074   // (It's possible to not widen at all by pulling out factors of 2 before
1075   // the multiplication; for example, K=2 can be calculated as
1076   // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
1077   // extra arithmetic, so it's not an obvious win, and it gets
1078   // much more complicated for K > 3.)
1079 
1080   // Protection from insane SCEVs; this bound is conservative,
1081   // but it probably doesn't matter.
1082   if (K > 1000)
1083     return SE.getCouldNotCompute();
1084 
1085   unsigned W = SE.getTypeSizeInBits(ResultTy);
1086 
1087   // Calculate K! / 2^T and T; we divide out the factors of two before
1088   // multiplying for calculating K! / 2^T to avoid overflow.
1089   // Other overflow doesn't matter because we only care about the bottom
1090   // W bits of the result.
1091   APInt OddFactorial(W, 1);
1092   unsigned T = 1;
1093   for (unsigned i = 3; i <= K; ++i) {
1094     APInt Mult(W, i);
1095     unsigned TwoFactors = Mult.countTrailingZeros();
1096     T += TwoFactors;
1097     Mult.lshrInPlace(TwoFactors);
1098     OddFactorial *= Mult;
1099   }
1100 
1101   // We need at least W + T bits for the multiplication step
1102   unsigned CalculationBits = W + T;
1103 
1104   // Calculate 2^T, at width T+W.
1105   APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
1106 
1107   // Calculate the multiplicative inverse of K! / 2^T;
1108   // this multiplication factor will perform the exact division by
1109   // K! / 2^T.
1110   APInt Mod = APInt::getSignedMinValue(W+1);
1111   APInt MultiplyFactor = OddFactorial.zext(W+1);
1112   MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
1113   MultiplyFactor = MultiplyFactor.trunc(W);
1114 
1115   // Calculate the product, at width T+W
1116   IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
1117                                                       CalculationBits);
1118   const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
1119   for (unsigned i = 1; i != K; ++i) {
1120     const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
1121     Dividend = SE.getMulExpr(Dividend,
1122                              SE.getTruncateOrZeroExtend(S, CalculationTy));
1123   }
1124 
1125   // Divide by 2^T
1126   const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
1127 
1128   // Truncate the result, and divide by K! / 2^T.
1129 
1130   return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1131                        SE.getTruncateOrZeroExtend(DivResult, ResultTy));
1132 }
1133 
1134 /// Return the value of this chain of recurrences at the specified iteration
1135 /// number.  We can evaluate this recurrence by multiplying each element in the
1136 /// chain by the binomial coefficient corresponding to it.  In other words, we
1137 /// can evaluate {A,+,B,+,C,+,D} as:
1138 ///
1139 ///   A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
1140 ///
1141 /// where BC(It, k) stands for binomial coefficient.
1142 ///
1143 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
1144                                                 ScalarEvolution &SE) const {
1145   const SCEV *Result = getStart();
1146   for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1147     // The computation is correct in the face of overflow provided that the
1148     // multiplication is performed _after_ the evaluation of the binomial
1149     // coefficient.
1150     const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
1151     if (isa<SCEVCouldNotCompute>(Coeff))
1152       return Coeff;
1153 
1154     Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
1155   }
1156   return Result;
1157 }
1158 
1159 //===----------------------------------------------------------------------===//
1160 //                    SCEV Expression folder implementations
1161 //===----------------------------------------------------------------------===//
1162 
1163 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
1164                                              Type *Ty) {
1165   assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1166          "This is not a truncating conversion!");
1167   assert(isSCEVable(Ty) &&
1168          "This is not a conversion to a SCEVable type!");
1169   Ty = getEffectiveSCEVType(Ty);
1170 
1171   FoldingSetNodeID ID;
1172   ID.AddInteger(scTruncate);
1173   ID.AddPointer(Op);
1174   ID.AddPointer(Ty);
1175   void *IP = nullptr;
1176   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1177 
1178   // Fold if the operand is constant.
1179   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1180     return getConstant(
1181       cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1182 
1183   // trunc(trunc(x)) --> trunc(x)
1184   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
1185     return getTruncateExpr(ST->getOperand(), Ty);
1186 
1187   // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1188   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1189     return getTruncateOrSignExtend(SS->getOperand(), Ty);
1190 
1191   // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1192   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1193     return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
1194 
1195   // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can
1196   // eliminate all the truncates, or we replace other casts with truncates.
1197   if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) {
1198     SmallVector<const SCEV *, 4> Operands;
1199     bool hasTrunc = false;
1200     for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) {
1201       const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty);
1202       if (!isa<SCEVCastExpr>(SA->getOperand(i)))
1203         hasTrunc = isa<SCEVTruncateExpr>(S);
1204       Operands.push_back(S);
1205     }
1206     if (!hasTrunc)
1207       return getAddExpr(Operands);
1208     UniqueSCEVs.FindNodeOrInsertPos(ID, IP);  // Mutates IP, returns NULL.
1209   }
1210 
1211   // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can
1212   // eliminate all the truncates, or we replace other casts with truncates.
1213   if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) {
1214     SmallVector<const SCEV *, 4> Operands;
1215     bool hasTrunc = false;
1216     for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) {
1217       const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty);
1218       if (!isa<SCEVCastExpr>(SM->getOperand(i)))
1219         hasTrunc = isa<SCEVTruncateExpr>(S);
1220       Operands.push_back(S);
1221     }
1222     if (!hasTrunc)
1223       return getMulExpr(Operands);
1224     UniqueSCEVs.FindNodeOrInsertPos(ID, IP);  // Mutates IP, returns NULL.
1225   }
1226 
1227   // If the input value is a chrec scev, truncate the chrec's operands.
1228   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1229     SmallVector<const SCEV *, 4> Operands;
1230     for (const SCEV *Op : AddRec->operands())
1231       Operands.push_back(getTruncateExpr(Op, Ty));
1232     return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1233   }
1234 
1235   // The cast wasn't folded; create an explicit cast node. We can reuse
1236   // the existing insert position since if we get here, we won't have
1237   // made any changes which would invalidate it.
1238   SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1239                                                  Op, Ty);
1240   UniqueSCEVs.InsertNode(S, IP);
1241   return S;
1242 }
1243 
1244 // Get the limit of a recurrence such that incrementing by Step cannot cause
1245 // signed overflow as long as the value of the recurrence within the
1246 // loop does not exceed this limit before incrementing.
1247 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1248                                                  ICmpInst::Predicate *Pred,
1249                                                  ScalarEvolution *SE) {
1250   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1251   if (SE->isKnownPositive(Step)) {
1252     *Pred = ICmpInst::ICMP_SLT;
1253     return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1254                            SE->getSignedRange(Step).getSignedMax());
1255   }
1256   if (SE->isKnownNegative(Step)) {
1257     *Pred = ICmpInst::ICMP_SGT;
1258     return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1259                            SE->getSignedRange(Step).getSignedMin());
1260   }
1261   return nullptr;
1262 }
1263 
1264 // Get the limit of a recurrence such that incrementing by Step cannot cause
1265 // unsigned overflow as long as the value of the recurrence within the loop does
1266 // not exceed this limit before incrementing.
1267 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1268                                                    ICmpInst::Predicate *Pred,
1269                                                    ScalarEvolution *SE) {
1270   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1271   *Pred = ICmpInst::ICMP_ULT;
1272 
1273   return SE->getConstant(APInt::getMinValue(BitWidth) -
1274                          SE->getUnsignedRange(Step).getUnsignedMax());
1275 }
1276 
1277 namespace {
1278 
1279 struct ExtendOpTraitsBase {
1280   typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(
1281       const SCEV *, Type *, ScalarEvolution::ExtendCacheTy &Cache);
1282 };
1283 
1284 // Used to make code generic over signed and unsigned overflow.
1285 template <typename ExtendOp> struct ExtendOpTraits {
1286   // Members present:
1287   //
1288   // static const SCEV::NoWrapFlags WrapType;
1289   //
1290   // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1291   //
1292   // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1293   //                                           ICmpInst::Predicate *Pred,
1294   //                                           ScalarEvolution *SE);
1295 };
1296 
1297 template <>
1298 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1299   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1300 
1301   static const GetExtendExprTy GetExtendExpr;
1302 
1303   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1304                                              ICmpInst::Predicate *Pred,
1305                                              ScalarEvolution *SE) {
1306     return getSignedOverflowLimitForStep(Step, Pred, SE);
1307   }
1308 };
1309 
1310 const ExtendOpTraitsBase::GetExtendExprTy
1311     ExtendOpTraits<SCEVSignExtendExpr>::GetExtendExpr =
1312         &ScalarEvolution::getSignExtendExprCached;
1313 
1314 template <>
1315 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1316   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1317 
1318   static const GetExtendExprTy GetExtendExpr;
1319 
1320   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1321                                              ICmpInst::Predicate *Pred,
1322                                              ScalarEvolution *SE) {
1323     return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1324   }
1325 };
1326 
1327 const ExtendOpTraitsBase::GetExtendExprTy
1328     ExtendOpTraits<SCEVZeroExtendExpr>::GetExtendExpr =
1329         &ScalarEvolution::getZeroExtendExprCached;
1330 }
1331 
1332 // The recurrence AR has been shown to have no signed/unsigned wrap or something
1333 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1334 // easily prove NSW/NUW for its preincrement or postincrement sibling. This
1335 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1336 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1337 // expression "Step + sext/zext(PreIncAR)" is congruent with
1338 // "sext/zext(PostIncAR)"
1339 template <typename ExtendOpTy>
1340 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1341                                         ScalarEvolution *SE,
1342                                         ScalarEvolution::ExtendCacheTy &Cache) {
1343   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1344   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1345 
1346   const Loop *L = AR->getLoop();
1347   const SCEV *Start = AR->getStart();
1348   const SCEV *Step = AR->getStepRecurrence(*SE);
1349 
1350   // Check for a simple looking step prior to loop entry.
1351   const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1352   if (!SA)
1353     return nullptr;
1354 
1355   // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1356   // subtraction is expensive. For this purpose, perform a quick and dirty
1357   // difference, by checking for Step in the operand list.
1358   SmallVector<const SCEV *, 4> DiffOps;
1359   for (const SCEV *Op : SA->operands())
1360     if (Op != Step)
1361       DiffOps.push_back(Op);
1362 
1363   if (DiffOps.size() == SA->getNumOperands())
1364     return nullptr;
1365 
1366   // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1367   // `Step`:
1368 
1369   // 1. NSW/NUW flags on the step increment.
1370   auto PreStartFlags =
1371     ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
1372   const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1373   const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1374       SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1375 
1376   // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1377   // "S+X does not sign/unsign-overflow".
1378   //
1379 
1380   const SCEV *BECount = SE->getBackedgeTakenCount(L);
1381   if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1382       !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1383     return PreStart;
1384 
1385   // 2. Direct overflow check on the step operation's expression.
1386   unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1387   Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1388   const SCEV *OperandExtendedStart =
1389       SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Cache),
1390                      (SE->*GetExtendExpr)(Step, WideTy, Cache));
1391   if ((SE->*GetExtendExpr)(Start, WideTy, Cache) == OperandExtendedStart) {
1392     if (PreAR && AR->getNoWrapFlags(WrapType)) {
1393       // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1394       // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1395       // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`.  Cache this fact.
1396       const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType);
1397     }
1398     return PreStart;
1399   }
1400 
1401   // 3. Loop precondition.
1402   ICmpInst::Predicate Pred;
1403   const SCEV *OverflowLimit =
1404       ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1405 
1406   if (OverflowLimit &&
1407       SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1408     return PreStart;
1409 
1410   return nullptr;
1411 }
1412 
1413 // Get the normalized zero or sign extended expression for this AddRec's Start.
1414 template <typename ExtendOpTy>
1415 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1416                                         ScalarEvolution *SE,
1417                                         ScalarEvolution::ExtendCacheTy &Cache) {
1418   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1419 
1420   const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Cache);
1421   if (!PreStart)
1422     return (SE->*GetExtendExpr)(AR->getStart(), Ty, Cache);
1423 
1424   return SE->getAddExpr(
1425       (SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty, Cache),
1426       (SE->*GetExtendExpr)(PreStart, Ty, Cache));
1427 }
1428 
1429 // Try to prove away overflow by looking at "nearby" add recurrences.  A
1430 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1431 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1432 //
1433 // Formally:
1434 //
1435 //     {S,+,X} == {S-T,+,X} + T
1436 //  => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1437 //
1438 // If ({S-T,+,X} + T) does not overflow  ... (1)
1439 //
1440 //  RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1441 //
1442 // If {S-T,+,X} does not overflow  ... (2)
1443 //
1444 //  RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1445 //      == {Ext(S-T)+Ext(T),+,Ext(X)}
1446 //
1447 // If (S-T)+T does not overflow  ... (3)
1448 //
1449 //  RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1450 //      == {Ext(S),+,Ext(X)} == LHS
1451 //
1452 // Thus, if (1), (2) and (3) are true for some T, then
1453 //   Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1454 //
1455 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1456 // does not overflow" restricted to the 0th iteration.  Therefore we only need
1457 // to check for (1) and (2).
1458 //
1459 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1460 // is `Delta` (defined below).
1461 //
1462 template <typename ExtendOpTy>
1463 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1464                                                 const SCEV *Step,
1465                                                 const Loop *L) {
1466   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1467 
1468   // We restrict `Start` to a constant to prevent SCEV from spending too much
1469   // time here.  It is correct (but more expensive) to continue with a
1470   // non-constant `Start` and do a general SCEV subtraction to compute
1471   // `PreStart` below.
1472   //
1473   const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1474   if (!StartC)
1475     return false;
1476 
1477   APInt StartAI = StartC->getAPInt();
1478 
1479   for (unsigned Delta : {-2, -1, 1, 2}) {
1480     const SCEV *PreStart = getConstant(StartAI - Delta);
1481 
1482     FoldingSetNodeID ID;
1483     ID.AddInteger(scAddRecExpr);
1484     ID.AddPointer(PreStart);
1485     ID.AddPointer(Step);
1486     ID.AddPointer(L);
1487     void *IP = nullptr;
1488     const auto *PreAR =
1489       static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1490 
1491     // Give up if we don't already have the add recurrence we need because
1492     // actually constructing an add recurrence is relatively expensive.
1493     if (PreAR && PreAR->getNoWrapFlags(WrapType)) {  // proves (2)
1494       const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1495       ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1496       const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1497           DeltaS, &Pred, this);
1498       if (Limit && isKnownPredicate(Pred, PreAR, Limit))  // proves (1)
1499         return true;
1500     }
1501   }
1502 
1503   return false;
1504 }
1505 
1506 const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty) {
1507   // Use the local cache to prevent exponential behavior of
1508   // getZeroExtendExprImpl.
1509   ExtendCacheTy Cache;
1510   return getZeroExtendExprCached(Op, Ty, Cache);
1511 }
1512 
1513 /// Query \p Cache before calling getZeroExtendExprImpl. If there is no
1514 /// related entry in the \p Cache, call getZeroExtendExprImpl and save
1515 /// the result in the \p Cache.
1516 const SCEV *ScalarEvolution::getZeroExtendExprCached(const SCEV *Op, Type *Ty,
1517                                                      ExtendCacheTy &Cache) {
1518   auto It = Cache.find({Op, Ty});
1519   if (It != Cache.end())
1520     return It->second;
1521   const SCEV *ZExt = getZeroExtendExprImpl(Op, Ty, Cache);
1522   auto InsertResult = Cache.insert({{Op, Ty}, ZExt});
1523   assert(InsertResult.second && "Expect the key was not in the cache");
1524   (void)InsertResult;
1525   return ZExt;
1526 }
1527 
1528 /// The real implementation of getZeroExtendExpr.
1529 const SCEV *ScalarEvolution::getZeroExtendExprImpl(const SCEV *Op, Type *Ty,
1530                                                    ExtendCacheTy &Cache) {
1531   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1532          "This is not an extending conversion!");
1533   assert(isSCEVable(Ty) &&
1534          "This is not a conversion to a SCEVable type!");
1535   Ty = getEffectiveSCEVType(Ty);
1536 
1537   // Fold if the operand is constant.
1538   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1539     return getConstant(
1540         cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
1541 
1542   // zext(zext(x)) --> zext(x)
1543   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1544     return getZeroExtendExprCached(SZ->getOperand(), Ty, Cache);
1545 
1546   // Before doing any expensive analysis, check to see if we've already
1547   // computed a SCEV for this Op and Ty.
1548   FoldingSetNodeID ID;
1549   ID.AddInteger(scZeroExtend);
1550   ID.AddPointer(Op);
1551   ID.AddPointer(Ty);
1552   void *IP = nullptr;
1553   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1554 
1555   // zext(trunc(x)) --> zext(x) or x or trunc(x)
1556   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1557     // It's possible the bits taken off by the truncate were all zero bits. If
1558     // so, we should be able to simplify this further.
1559     const SCEV *X = ST->getOperand();
1560     ConstantRange CR = getUnsignedRange(X);
1561     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1562     unsigned NewBits = getTypeSizeInBits(Ty);
1563     if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1564             CR.zextOrTrunc(NewBits)))
1565       return getTruncateOrZeroExtend(X, Ty);
1566   }
1567 
1568   // If the input value is a chrec scev, and we can prove that the value
1569   // did not overflow the old, smaller, value, we can zero extend all of the
1570   // operands (often constants).  This allows analysis of something like
1571   // this:  for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1572   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1573     if (AR->isAffine()) {
1574       const SCEV *Start = AR->getStart();
1575       const SCEV *Step = AR->getStepRecurrence(*this);
1576       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1577       const Loop *L = AR->getLoop();
1578 
1579       if (!AR->hasNoUnsignedWrap()) {
1580         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1581         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1582       }
1583 
1584       // If we have special knowledge that this addrec won't overflow,
1585       // we don't need to do any further analysis.
1586       if (AR->hasNoUnsignedWrap())
1587         return getAddRecExpr(
1588             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Cache),
1589             getZeroExtendExprCached(Step, Ty, Cache), L, AR->getNoWrapFlags());
1590 
1591       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1592       // Note that this serves two purposes: It filters out loops that are
1593       // simply not analyzable, and it covers the case where this code is
1594       // being called from within backedge-taken count analysis, such that
1595       // attempting to ask for the backedge-taken count would likely result
1596       // in infinite recursion. In the later case, the analysis code will
1597       // cope with a conservative value, and it will take care to purge
1598       // that value once it has finished.
1599       const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1600       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1601         // Manually compute the final value for AR, checking for
1602         // overflow.
1603 
1604         // Check whether the backedge-taken count can be losslessly casted to
1605         // the addrec's type. The count is always unsigned.
1606         const SCEV *CastedMaxBECount =
1607           getTruncateOrZeroExtend(MaxBECount, Start->getType());
1608         const SCEV *RecastedMaxBECount =
1609           getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1610         if (MaxBECount == RecastedMaxBECount) {
1611           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1612           // Check whether Start+Step*MaxBECount has no unsigned overflow.
1613           const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step);
1614           const SCEV *ZAdd =
1615               getZeroExtendExprCached(getAddExpr(Start, ZMul), WideTy, Cache);
1616           const SCEV *WideStart = getZeroExtendExprCached(Start, WideTy, Cache);
1617           const SCEV *WideMaxBECount =
1618               getZeroExtendExprCached(CastedMaxBECount, WideTy, Cache);
1619           const SCEV *OperandExtendedAdd = getAddExpr(
1620               WideStart, getMulExpr(WideMaxBECount, getZeroExtendExprCached(
1621                                                         Step, WideTy, Cache)));
1622           if (ZAdd == OperandExtendedAdd) {
1623             // Cache knowledge of AR NUW, which is propagated to this AddRec.
1624             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1625             // Return the expression with the addrec on the outside.
1626             return getAddRecExpr(
1627                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Cache),
1628                 getZeroExtendExprCached(Step, Ty, Cache), L,
1629                 AR->getNoWrapFlags());
1630           }
1631           // Similar to above, only this time treat the step value as signed.
1632           // This covers loops that count down.
1633           OperandExtendedAdd =
1634             getAddExpr(WideStart,
1635                        getMulExpr(WideMaxBECount,
1636                                   getSignExtendExpr(Step, WideTy)));
1637           if (ZAdd == OperandExtendedAdd) {
1638             // Cache knowledge of AR NW, which is propagated to this AddRec.
1639             // Negative step causes unsigned wrap, but it still can't self-wrap.
1640             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1641             // Return the expression with the addrec on the outside.
1642             return getAddRecExpr(
1643                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Cache),
1644                 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1645           }
1646         }
1647       }
1648 
1649       // Normally, in the cases we can prove no-overflow via a
1650       // backedge guarding condition, we can also compute a backedge
1651       // taken count for the loop.  The exceptions are assumptions and
1652       // guards present in the loop -- SCEV is not great at exploiting
1653       // these to compute max backedge taken counts, but can still use
1654       // these to prove lack of overflow.  Use this fact to avoid
1655       // doing extra work that may not pay off.
1656       if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1657           !AC.assumptions().empty()) {
1658         // If the backedge is guarded by a comparison with the pre-inc
1659         // value the addrec is safe. Also, if the entry is guarded by
1660         // a comparison with the start value and the backedge is
1661         // guarded by a comparison with the post-inc value, the addrec
1662         // is safe.
1663         if (isKnownPositive(Step)) {
1664           const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
1665                                       getUnsignedRange(Step).getUnsignedMax());
1666           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
1667               (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
1668                isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
1669                                            AR->getPostIncExpr(*this), N))) {
1670             // Cache knowledge of AR NUW, which is propagated to this
1671             // AddRec.
1672             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1673             // Return the expression with the addrec on the outside.
1674             return getAddRecExpr(
1675                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Cache),
1676                 getZeroExtendExprCached(Step, Ty, Cache), L,
1677                 AR->getNoWrapFlags());
1678           }
1679         } else if (isKnownNegative(Step)) {
1680           const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1681                                       getSignedRange(Step).getSignedMin());
1682           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1683               (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) &&
1684                isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
1685                                            AR->getPostIncExpr(*this), N))) {
1686             // Cache knowledge of AR NW, which is propagated to this
1687             // AddRec.  Negative step causes unsigned wrap, but it
1688             // still can't self-wrap.
1689             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1690             // Return the expression with the addrec on the outside.
1691             return getAddRecExpr(
1692                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Cache),
1693                 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1694           }
1695         }
1696       }
1697 
1698       if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1699         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1700         return getAddRecExpr(
1701             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Cache),
1702             getZeroExtendExprCached(Step, Ty, Cache), L, AR->getNoWrapFlags());
1703       }
1704     }
1705 
1706   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1707     // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1708     if (SA->hasNoUnsignedWrap()) {
1709       // If the addition does not unsign overflow then we can, by definition,
1710       // commute the zero extension with the addition operation.
1711       SmallVector<const SCEV *, 4> Ops;
1712       for (const auto *Op : SA->operands())
1713         Ops.push_back(getZeroExtendExprCached(Op, Ty, Cache));
1714       return getAddExpr(Ops, SCEV::FlagNUW);
1715     }
1716   }
1717 
1718   // The cast wasn't folded; create an explicit cast node.
1719   // Recompute the insert position, as it may have been invalidated.
1720   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1721   SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1722                                                    Op, Ty);
1723   UniqueSCEVs.InsertNode(S, IP);
1724   return S;
1725 }
1726 
1727 const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty) {
1728   // Use the local cache to prevent exponential behavior of
1729   // getSignExtendExprImpl.
1730   ExtendCacheTy Cache;
1731   return getSignExtendExprCached(Op, Ty, Cache);
1732 }
1733 
1734 /// Query \p Cache before calling getSignExtendExprImpl. If there is no
1735 /// related entry in the \p Cache, call getSignExtendExprImpl and save
1736 /// the result in the \p Cache.
1737 const SCEV *ScalarEvolution::getSignExtendExprCached(const SCEV *Op, Type *Ty,
1738                                                      ExtendCacheTy &Cache) {
1739   auto It = Cache.find({Op, Ty});
1740   if (It != Cache.end())
1741     return It->second;
1742   const SCEV *SExt = getSignExtendExprImpl(Op, Ty, Cache);
1743   auto InsertResult = Cache.insert({{Op, Ty}, SExt});
1744   assert(InsertResult.second && "Expect the key was not in the cache");
1745   (void)InsertResult;
1746   return SExt;
1747 }
1748 
1749 /// The real implementation of getSignExtendExpr.
1750 const SCEV *ScalarEvolution::getSignExtendExprImpl(const SCEV *Op, Type *Ty,
1751                                                    ExtendCacheTy &Cache) {
1752   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1753          "This is not an extending conversion!");
1754   assert(isSCEVable(Ty) &&
1755          "This is not a conversion to a SCEVable type!");
1756   Ty = getEffectiveSCEVType(Ty);
1757 
1758   // Fold if the operand is constant.
1759   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1760     return getConstant(
1761         cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
1762 
1763   // sext(sext(x)) --> sext(x)
1764   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1765     return getSignExtendExprCached(SS->getOperand(), Ty, Cache);
1766 
1767   // sext(zext(x)) --> zext(x)
1768   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1769     return getZeroExtendExpr(SZ->getOperand(), Ty);
1770 
1771   // Before doing any expensive analysis, check to see if we've already
1772   // computed a SCEV for this Op and Ty.
1773   FoldingSetNodeID ID;
1774   ID.AddInteger(scSignExtend);
1775   ID.AddPointer(Op);
1776   ID.AddPointer(Ty);
1777   void *IP = nullptr;
1778   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1779 
1780   // sext(trunc(x)) --> sext(x) or x or trunc(x)
1781   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1782     // It's possible the bits taken off by the truncate were all sign bits. If
1783     // so, we should be able to simplify this further.
1784     const SCEV *X = ST->getOperand();
1785     ConstantRange CR = getSignedRange(X);
1786     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1787     unsigned NewBits = getTypeSizeInBits(Ty);
1788     if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1789             CR.sextOrTrunc(NewBits)))
1790       return getTruncateOrSignExtend(X, Ty);
1791   }
1792 
1793   // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2
1794   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1795     if (SA->getNumOperands() == 2) {
1796       auto *SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0));
1797       auto *SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1));
1798       if (SMul && SC1) {
1799         if (auto *SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) {
1800           const APInt &C1 = SC1->getAPInt();
1801           const APInt &C2 = SC2->getAPInt();
1802           if (C1.isStrictlyPositive() && C2.isStrictlyPositive() &&
1803               C2.ugt(C1) && C2.isPowerOf2())
1804             return getAddExpr(getSignExtendExprCached(SC1, Ty, Cache),
1805                               getSignExtendExprCached(SMul, Ty, Cache));
1806         }
1807       }
1808     }
1809 
1810     // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1811     if (SA->hasNoSignedWrap()) {
1812       // If the addition does not sign overflow then we can, by definition,
1813       // commute the sign extension with the addition operation.
1814       SmallVector<const SCEV *, 4> Ops;
1815       for (const auto *Op : SA->operands())
1816         Ops.push_back(getSignExtendExprCached(Op, Ty, Cache));
1817       return getAddExpr(Ops, SCEV::FlagNSW);
1818     }
1819   }
1820   // If the input value is a chrec scev, and we can prove that the value
1821   // did not overflow the old, smaller, value, we can sign extend all of the
1822   // operands (often constants).  This allows analysis of something like
1823   // this:  for (signed char X = 0; X < 100; ++X) { int Y = X; }
1824   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1825     if (AR->isAffine()) {
1826       const SCEV *Start = AR->getStart();
1827       const SCEV *Step = AR->getStepRecurrence(*this);
1828       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1829       const Loop *L = AR->getLoop();
1830 
1831       if (!AR->hasNoSignedWrap()) {
1832         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1833         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1834       }
1835 
1836       // If we have special knowledge that this addrec won't overflow,
1837       // we don't need to do any further analysis.
1838       if (AR->hasNoSignedWrap())
1839         return getAddRecExpr(
1840             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Cache),
1841             getSignExtendExprCached(Step, Ty, Cache), L, SCEV::FlagNSW);
1842 
1843       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1844       // Note that this serves two purposes: It filters out loops that are
1845       // simply not analyzable, and it covers the case where this code is
1846       // being called from within backedge-taken count analysis, such that
1847       // attempting to ask for the backedge-taken count would likely result
1848       // in infinite recursion. In the later case, the analysis code will
1849       // cope with a conservative value, and it will take care to purge
1850       // that value once it has finished.
1851       const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1852       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1853         // Manually compute the final value for AR, checking for
1854         // overflow.
1855 
1856         // Check whether the backedge-taken count can be losslessly casted to
1857         // the addrec's type. The count is always unsigned.
1858         const SCEV *CastedMaxBECount =
1859           getTruncateOrZeroExtend(MaxBECount, Start->getType());
1860         const SCEV *RecastedMaxBECount =
1861           getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1862         if (MaxBECount == RecastedMaxBECount) {
1863           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1864           // Check whether Start+Step*MaxBECount has no signed overflow.
1865           const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
1866           const SCEV *SAdd =
1867               getSignExtendExprCached(getAddExpr(Start, SMul), WideTy, Cache);
1868           const SCEV *WideStart = getSignExtendExprCached(Start, WideTy, Cache);
1869           const SCEV *WideMaxBECount =
1870               getZeroExtendExpr(CastedMaxBECount, WideTy);
1871           const SCEV *OperandExtendedAdd = getAddExpr(
1872               WideStart, getMulExpr(WideMaxBECount, getSignExtendExprCached(
1873                                                         Step, WideTy, Cache)));
1874           if (SAdd == OperandExtendedAdd) {
1875             // Cache knowledge of AR NSW, which is propagated to this AddRec.
1876             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1877             // Return the expression with the addrec on the outside.
1878             return getAddRecExpr(
1879                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Cache),
1880                 getSignExtendExprCached(Step, Ty, Cache), L,
1881                 AR->getNoWrapFlags());
1882           }
1883           // Similar to above, only this time treat the step value as unsigned.
1884           // This covers loops that count up with an unsigned step.
1885           OperandExtendedAdd =
1886             getAddExpr(WideStart,
1887                        getMulExpr(WideMaxBECount,
1888                                   getZeroExtendExpr(Step, WideTy)));
1889           if (SAdd == OperandExtendedAdd) {
1890             // If AR wraps around then
1891             //
1892             //    abs(Step) * MaxBECount > unsigned-max(AR->getType())
1893             // => SAdd != OperandExtendedAdd
1894             //
1895             // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
1896             // (SAdd == OperandExtendedAdd => AR is NW)
1897 
1898             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1899 
1900             // Return the expression with the addrec on the outside.
1901             return getAddRecExpr(
1902                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Cache),
1903                 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1904           }
1905         }
1906       }
1907 
1908       // Normally, in the cases we can prove no-overflow via a
1909       // backedge guarding condition, we can also compute a backedge
1910       // taken count for the loop.  The exceptions are assumptions and
1911       // guards present in the loop -- SCEV is not great at exploiting
1912       // these to compute max backedge taken counts, but can still use
1913       // these to prove lack of overflow.  Use this fact to avoid
1914       // doing extra work that may not pay off.
1915 
1916       if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1917           !AC.assumptions().empty()) {
1918         // If the backedge is guarded by a comparison with the pre-inc
1919         // value the addrec is safe. Also, if the entry is guarded by
1920         // a comparison with the start value and the backedge is
1921         // guarded by a comparison with the post-inc value, the addrec
1922         // is safe.
1923         ICmpInst::Predicate Pred;
1924         const SCEV *OverflowLimit =
1925             getSignedOverflowLimitForStep(Step, &Pred, this);
1926         if (OverflowLimit &&
1927             (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
1928              (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) &&
1929               isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this),
1930                                           OverflowLimit)))) {
1931           // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec.
1932           const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1933           return getAddRecExpr(
1934               getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Cache),
1935               getSignExtendExprCached(Step, Ty, Cache), L,
1936               AR->getNoWrapFlags());
1937         }
1938       }
1939 
1940       // If Start and Step are constants, check if we can apply this
1941       // transformation:
1942       // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2
1943       auto *SC1 = dyn_cast<SCEVConstant>(Start);
1944       auto *SC2 = dyn_cast<SCEVConstant>(Step);
1945       if (SC1 && SC2) {
1946         const APInt &C1 = SC1->getAPInt();
1947         const APInt &C2 = SC2->getAPInt();
1948         if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) &&
1949             C2.isPowerOf2()) {
1950           Start = getSignExtendExprCached(Start, Ty, Cache);
1951           const SCEV *NewAR = getAddRecExpr(getZero(AR->getType()), Step, L,
1952                                             AR->getNoWrapFlags());
1953           return getAddExpr(Start, getSignExtendExprCached(NewAR, Ty, Cache));
1954         }
1955       }
1956 
1957       if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
1958         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1959         return getAddRecExpr(
1960             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Cache),
1961             getSignExtendExprCached(Step, Ty, Cache), L, AR->getNoWrapFlags());
1962       }
1963     }
1964 
1965   // If the input value is provably positive and we could not simplify
1966   // away the sext build a zext instead.
1967   if (isKnownNonNegative(Op))
1968     return getZeroExtendExpr(Op, Ty);
1969 
1970   // The cast wasn't folded; create an explicit cast node.
1971   // Recompute the insert position, as it may have been invalidated.
1972   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1973   SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1974                                                    Op, Ty);
1975   UniqueSCEVs.InsertNode(S, IP);
1976   return S;
1977 }
1978 
1979 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
1980 /// unspecified bits out to the given type.
1981 ///
1982 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
1983                                               Type *Ty) {
1984   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1985          "This is not an extending conversion!");
1986   assert(isSCEVable(Ty) &&
1987          "This is not a conversion to a SCEVable type!");
1988   Ty = getEffectiveSCEVType(Ty);
1989 
1990   // Sign-extend negative constants.
1991   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1992     if (SC->getAPInt().isNegative())
1993       return getSignExtendExpr(Op, Ty);
1994 
1995   // Peel off a truncate cast.
1996   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
1997     const SCEV *NewOp = T->getOperand();
1998     if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1999       return getAnyExtendExpr(NewOp, Ty);
2000     return getTruncateOrNoop(NewOp, Ty);
2001   }
2002 
2003   // Next try a zext cast. If the cast is folded, use it.
2004   const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2005   if (!isa<SCEVZeroExtendExpr>(ZExt))
2006     return ZExt;
2007 
2008   // Next try a sext cast. If the cast is folded, use it.
2009   const SCEV *SExt = getSignExtendExpr(Op, Ty);
2010   if (!isa<SCEVSignExtendExpr>(SExt))
2011     return SExt;
2012 
2013   // Force the cast to be folded into the operands of an addrec.
2014   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2015     SmallVector<const SCEV *, 4> Ops;
2016     for (const SCEV *Op : AR->operands())
2017       Ops.push_back(getAnyExtendExpr(Op, Ty));
2018     return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2019   }
2020 
2021   // If the expression is obviously signed, use the sext cast value.
2022   if (isa<SCEVSMaxExpr>(Op))
2023     return SExt;
2024 
2025   // Absent any other information, use the zext cast value.
2026   return ZExt;
2027 }
2028 
2029 /// Process the given Ops list, which is a list of operands to be added under
2030 /// the given scale, update the given map. This is a helper function for
2031 /// getAddRecExpr. As an example of what it does, given a sequence of operands
2032 /// that would form an add expression like this:
2033 ///
2034 ///    m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2035 ///
2036 /// where A and B are constants, update the map with these values:
2037 ///
2038 ///    (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2039 ///
2040 /// and add 13 + A*B*29 to AccumulatedConstant.
2041 /// This will allow getAddRecExpr to produce this:
2042 ///
2043 ///    13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2044 ///
2045 /// This form often exposes folding opportunities that are hidden in
2046 /// the original operand list.
2047 ///
2048 /// Return true iff it appears that any interesting folding opportunities
2049 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
2050 /// the common case where no interesting opportunities are present, and
2051 /// is also used as a check to avoid infinite recursion.
2052 ///
2053 static bool
2054 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
2055                              SmallVectorImpl<const SCEV *> &NewOps,
2056                              APInt &AccumulatedConstant,
2057                              const SCEV *const *Ops, size_t NumOperands,
2058                              const APInt &Scale,
2059                              ScalarEvolution &SE) {
2060   bool Interesting = false;
2061 
2062   // Iterate over the add operands. They are sorted, with constants first.
2063   unsigned i = 0;
2064   while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2065     ++i;
2066     // Pull a buried constant out to the outside.
2067     if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2068       Interesting = true;
2069     AccumulatedConstant += Scale * C->getAPInt();
2070   }
2071 
2072   // Next comes everything else. We're especially interested in multiplies
2073   // here, but they're in the middle, so just visit the rest with one loop.
2074   for (; i != NumOperands; ++i) {
2075     const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
2076     if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2077       APInt NewScale =
2078           Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2079       if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2080         // A multiplication of a constant with another add; recurse.
2081         const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2082         Interesting |=
2083           CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2084                                        Add->op_begin(), Add->getNumOperands(),
2085                                        NewScale, SE);
2086       } else {
2087         // A multiplication of a constant with some other value. Update
2088         // the map.
2089         SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
2090         const SCEV *Key = SE.getMulExpr(MulOps);
2091         auto Pair = M.insert({Key, NewScale});
2092         if (Pair.second) {
2093           NewOps.push_back(Pair.first->first);
2094         } else {
2095           Pair.first->second += NewScale;
2096           // The map already had an entry for this value, which may indicate
2097           // a folding opportunity.
2098           Interesting = true;
2099         }
2100       }
2101     } else {
2102       // An ordinary operand. Update the map.
2103       std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
2104           M.insert({Ops[i], Scale});
2105       if (Pair.second) {
2106         NewOps.push_back(Pair.first->first);
2107       } else {
2108         Pair.first->second += Scale;
2109         // The map already had an entry for this value, which may indicate
2110         // a folding opportunity.
2111         Interesting = true;
2112       }
2113     }
2114   }
2115 
2116   return Interesting;
2117 }
2118 
2119 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2120 // `OldFlags' as can't-wrap behavior.  Infer a more aggressive set of
2121 // can't-overflow flags for the operation if possible.
2122 static SCEV::NoWrapFlags
2123 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
2124                       const SmallVectorImpl<const SCEV *> &Ops,
2125                       SCEV::NoWrapFlags Flags) {
2126   using namespace std::placeholders;
2127   typedef OverflowingBinaryOperator OBO;
2128 
2129   bool CanAnalyze =
2130       Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
2131   (void)CanAnalyze;
2132   assert(CanAnalyze && "don't call from other places!");
2133 
2134   int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2135   SCEV::NoWrapFlags SignOrUnsignWrap =
2136       ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2137 
2138   // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2139   auto IsKnownNonNegative = [&](const SCEV *S) {
2140     return SE->isKnownNonNegative(S);
2141   };
2142 
2143   if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2144     Flags =
2145         ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
2146 
2147   SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2148 
2149   if (SignOrUnsignWrap != SignOrUnsignMask && Type == scAddExpr &&
2150       Ops.size() == 2 && isa<SCEVConstant>(Ops[0])) {
2151 
2152     // (A + C) --> (A + C)<nsw> if the addition does not sign overflow
2153     // (A + C) --> (A + C)<nuw> if the addition does not unsign overflow
2154 
2155     const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2156     if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2157       auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2158           Instruction::Add, C, OBO::NoSignedWrap);
2159       if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2160         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2161     }
2162     if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2163       auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2164           Instruction::Add, C, OBO::NoUnsignedWrap);
2165       if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2166         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2167     }
2168   }
2169 
2170   return Flags;
2171 }
2172 
2173 /// Get a canonical add expression, or something simpler if possible.
2174 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2175                                         SCEV::NoWrapFlags Flags,
2176                                         unsigned Depth) {
2177   assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2178          "only nuw or nsw allowed");
2179   assert(!Ops.empty() && "Cannot get empty add!");
2180   if (Ops.size() == 1) return Ops[0];
2181 #ifndef NDEBUG
2182   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2183   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2184     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2185            "SCEVAddExpr operand types don't match!");
2186 #endif
2187 
2188   // Sort by complexity, this groups all similar expression types together.
2189   GroupByComplexity(Ops, &LI);
2190 
2191   Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags);
2192 
2193   // If there are any constants, fold them together.
2194   unsigned Idx = 0;
2195   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2196     ++Idx;
2197     assert(Idx < Ops.size());
2198     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2199       // We found two constants, fold them together!
2200       Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
2201       if (Ops.size() == 2) return Ops[0];
2202       Ops.erase(Ops.begin()+1);  // Erase the folded element
2203       LHSC = cast<SCEVConstant>(Ops[0]);
2204     }
2205 
2206     // If we are left with a constant zero being added, strip it off.
2207     if (LHSC->getValue()->isZero()) {
2208       Ops.erase(Ops.begin());
2209       --Idx;
2210     }
2211 
2212     if (Ops.size() == 1) return Ops[0];
2213   }
2214 
2215   // Limit recursion calls depth
2216   if (Depth > MaxAddExprDepth)
2217     return getOrCreateAddExpr(Ops, Flags);
2218 
2219   // Okay, check to see if the same value occurs in the operand list more than
2220   // once.  If so, merge them together into an multiply expression.  Since we
2221   // sorted the list, these values are required to be adjacent.
2222   Type *Ty = Ops[0]->getType();
2223   bool FoundMatch = false;
2224   for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2225     if (Ops[i] == Ops[i+1]) {      //  X + Y + Y  -->  X + Y*2
2226       // Scan ahead to count how many equal operands there are.
2227       unsigned Count = 2;
2228       while (i+Count != e && Ops[i+Count] == Ops[i])
2229         ++Count;
2230       // Merge the values into a multiply.
2231       const SCEV *Scale = getConstant(Ty, Count);
2232       const SCEV *Mul = getMulExpr(Scale, Ops[i]);
2233       if (Ops.size() == Count)
2234         return Mul;
2235       Ops[i] = Mul;
2236       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2237       --i; e -= Count - 1;
2238       FoundMatch = true;
2239     }
2240   if (FoundMatch)
2241     return getAddExpr(Ops, Flags);
2242 
2243   // Check for truncates. If all the operands are truncated from the same
2244   // type, see if factoring out the truncate would permit the result to be
2245   // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
2246   // if the contents of the resulting outer trunc fold to something simple.
2247   for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
2248     const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
2249     Type *DstType = Trunc->getType();
2250     Type *SrcType = Trunc->getOperand()->getType();
2251     SmallVector<const SCEV *, 8> LargeOps;
2252     bool Ok = true;
2253     // Check all the operands to see if they can be represented in the
2254     // source type of the truncate.
2255     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2256       if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2257         if (T->getOperand()->getType() != SrcType) {
2258           Ok = false;
2259           break;
2260         }
2261         LargeOps.push_back(T->getOperand());
2262       } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2263         LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2264       } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
2265         SmallVector<const SCEV *, 8> LargeMulOps;
2266         for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2267           if (const SCEVTruncateExpr *T =
2268                 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2269             if (T->getOperand()->getType() != SrcType) {
2270               Ok = false;
2271               break;
2272             }
2273             LargeMulOps.push_back(T->getOperand());
2274           } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2275             LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2276           } else {
2277             Ok = false;
2278             break;
2279           }
2280         }
2281         if (Ok)
2282           LargeOps.push_back(getMulExpr(LargeMulOps));
2283       } else {
2284         Ok = false;
2285         break;
2286       }
2287     }
2288     if (Ok) {
2289       // Evaluate the expression in the larger type.
2290       const SCEV *Fold = getAddExpr(LargeOps, Flags, Depth + 1);
2291       // If it folds to something simple, use it. Otherwise, don't.
2292       if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2293         return getTruncateExpr(Fold, DstType);
2294     }
2295   }
2296 
2297   // Skip past any other cast SCEVs.
2298   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2299     ++Idx;
2300 
2301   // If there are add operands they would be next.
2302   if (Idx < Ops.size()) {
2303     bool DeletedAdd = false;
2304     while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2305       if (Ops.size() > AddOpsInlineThreshold ||
2306           Add->getNumOperands() > AddOpsInlineThreshold)
2307         break;
2308       // If we have an add, expand the add operands onto the end of the operands
2309       // list.
2310       Ops.erase(Ops.begin()+Idx);
2311       Ops.append(Add->op_begin(), Add->op_end());
2312       DeletedAdd = true;
2313     }
2314 
2315     // If we deleted at least one add, we added operands to the end of the list,
2316     // and they are not necessarily sorted.  Recurse to resort and resimplify
2317     // any operands we just acquired.
2318     if (DeletedAdd)
2319       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2320   }
2321 
2322   // Skip over the add expression until we get to a multiply.
2323   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2324     ++Idx;
2325 
2326   // Check to see if there are any folding opportunities present with
2327   // operands multiplied by constant values.
2328   if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2329     uint64_t BitWidth = getTypeSizeInBits(Ty);
2330     DenseMap<const SCEV *, APInt> M;
2331     SmallVector<const SCEV *, 8> NewOps;
2332     APInt AccumulatedConstant(BitWidth, 0);
2333     if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2334                                      Ops.data(), Ops.size(),
2335                                      APInt(BitWidth, 1), *this)) {
2336       struct APIntCompare {
2337         bool operator()(const APInt &LHS, const APInt &RHS) const {
2338           return LHS.ult(RHS);
2339         }
2340       };
2341 
2342       // Some interesting folding opportunity is present, so its worthwhile to
2343       // re-generate the operands list. Group the operands by constant scale,
2344       // to avoid multiplying by the same constant scale multiple times.
2345       std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
2346       for (const SCEV *NewOp : NewOps)
2347         MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2348       // Re-generate the operands list.
2349       Ops.clear();
2350       if (AccumulatedConstant != 0)
2351         Ops.push_back(getConstant(AccumulatedConstant));
2352       for (auto &MulOp : MulOpLists)
2353         if (MulOp.first != 0)
2354           Ops.push_back(getMulExpr(
2355               getConstant(MulOp.first),
2356               getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1)));
2357       if (Ops.empty())
2358         return getZero(Ty);
2359       if (Ops.size() == 1)
2360         return Ops[0];
2361       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2362     }
2363   }
2364 
2365   // If we are adding something to a multiply expression, make sure the
2366   // something is not already an operand of the multiply.  If so, merge it into
2367   // the multiply.
2368   for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2369     const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2370     for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2371       const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2372       if (isa<SCEVConstant>(MulOpSCEV))
2373         continue;
2374       for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
2375         if (MulOpSCEV == Ops[AddOp]) {
2376           // Fold W + X + (X * Y * Z)  -->  W + (X * ((Y*Z)+1))
2377           const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
2378           if (Mul->getNumOperands() != 2) {
2379             // If the multiply has more than two operands, we must get the
2380             // Y*Z term.
2381             SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2382                                                 Mul->op_begin()+MulOp);
2383             MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2384             InnerMul = getMulExpr(MulOps);
2385           }
2386           SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul};
2387           const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2388           const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV);
2389           if (Ops.size() == 2) return OuterMul;
2390           if (AddOp < Idx) {
2391             Ops.erase(Ops.begin()+AddOp);
2392             Ops.erase(Ops.begin()+Idx-1);
2393           } else {
2394             Ops.erase(Ops.begin()+Idx);
2395             Ops.erase(Ops.begin()+AddOp-1);
2396           }
2397           Ops.push_back(OuterMul);
2398           return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2399         }
2400 
2401       // Check this multiply against other multiplies being added together.
2402       for (unsigned OtherMulIdx = Idx+1;
2403            OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2404            ++OtherMulIdx) {
2405         const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
2406         // If MulOp occurs in OtherMul, we can fold the two multiplies
2407         // together.
2408         for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2409              OMulOp != e; ++OMulOp)
2410           if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2411             // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
2412             const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
2413             if (Mul->getNumOperands() != 2) {
2414               SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2415                                                   Mul->op_begin()+MulOp);
2416               MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2417               InnerMul1 = getMulExpr(MulOps);
2418             }
2419             const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
2420             if (OtherMul->getNumOperands() != 2) {
2421               SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
2422                                                   OtherMul->op_begin()+OMulOp);
2423               MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
2424               InnerMul2 = getMulExpr(MulOps);
2425             }
2426             SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2};
2427             const SCEV *InnerMulSum =
2428                 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2429             const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
2430             if (Ops.size() == 2) return OuterMul;
2431             Ops.erase(Ops.begin()+Idx);
2432             Ops.erase(Ops.begin()+OtherMulIdx-1);
2433             Ops.push_back(OuterMul);
2434             return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2435           }
2436       }
2437     }
2438   }
2439 
2440   // If there are any add recurrences in the operands list, see if any other
2441   // added values are loop invariant.  If so, we can fold them into the
2442   // recurrence.
2443   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2444     ++Idx;
2445 
2446   // Scan over all recurrences, trying to fold loop invariants into them.
2447   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2448     // Scan all of the other operands to this add and add them to the vector if
2449     // they are loop invariant w.r.t. the recurrence.
2450     SmallVector<const SCEV *, 8> LIOps;
2451     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2452     const Loop *AddRecLoop = AddRec->getLoop();
2453     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2454       if (isLoopInvariant(Ops[i], AddRecLoop)) {
2455         LIOps.push_back(Ops[i]);
2456         Ops.erase(Ops.begin()+i);
2457         --i; --e;
2458       }
2459 
2460     // If we found some loop invariants, fold them into the recurrence.
2461     if (!LIOps.empty()) {
2462       //  NLI + LI + {Start,+,Step}  -->  NLI + {LI+Start,+,Step}
2463       LIOps.push_back(AddRec->getStart());
2464 
2465       SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2466                                              AddRec->op_end());
2467       // This follows from the fact that the no-wrap flags on the outer add
2468       // expression are applicable on the 0th iteration, when the add recurrence
2469       // will be equal to its start value.
2470       AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1);
2471 
2472       // Build the new addrec. Propagate the NUW and NSW flags if both the
2473       // outer add and the inner addrec are guaranteed to have no overflow.
2474       // Always propagate NW.
2475       Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2476       const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2477 
2478       // If all of the other operands were loop invariant, we are done.
2479       if (Ops.size() == 1) return NewRec;
2480 
2481       // Otherwise, add the folded AddRec by the non-invariant parts.
2482       for (unsigned i = 0;; ++i)
2483         if (Ops[i] == AddRec) {
2484           Ops[i] = NewRec;
2485           break;
2486         }
2487       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2488     }
2489 
2490     // Okay, if there weren't any loop invariants to be folded, check to see if
2491     // there are multiple AddRec's with the same loop induction variable being
2492     // added together.  If so, we can fold them.
2493     for (unsigned OtherIdx = Idx+1;
2494          OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2495          ++OtherIdx)
2496       if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2497         // Other + {A,+,B}<L> + {C,+,D}<L>  -->  Other + {A+C,+,B+D}<L>
2498         SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2499                                                AddRec->op_end());
2500         for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2501              ++OtherIdx)
2502           if (const auto *OtherAddRec = dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]))
2503             if (OtherAddRec->getLoop() == AddRecLoop) {
2504               for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2505                    i != e; ++i) {
2506                 if (i >= AddRecOps.size()) {
2507                   AddRecOps.append(OtherAddRec->op_begin()+i,
2508                                    OtherAddRec->op_end());
2509                   break;
2510                 }
2511                 SmallVector<const SCEV *, 2> TwoOps = {
2512                     AddRecOps[i], OtherAddRec->getOperand(i)};
2513                 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2514               }
2515               Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2516             }
2517         // Step size has changed, so we cannot guarantee no self-wraparound.
2518         Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2519         return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2520       }
2521 
2522     // Otherwise couldn't fold anything into this recurrence.  Move onto the
2523     // next one.
2524   }
2525 
2526   // Okay, it looks like we really DO need an add expr.  Check to see if we
2527   // already have one, otherwise create a new one.
2528   return getOrCreateAddExpr(Ops, Flags);
2529 }
2530 
2531 const SCEV *
2532 ScalarEvolution::getOrCreateAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2533                                     SCEV::NoWrapFlags Flags) {
2534   FoldingSetNodeID ID;
2535   ID.AddInteger(scAddExpr);
2536   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2537     ID.AddPointer(Ops[i]);
2538   void *IP = nullptr;
2539   SCEVAddExpr *S =
2540       static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2541   if (!S) {
2542     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2543     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2544     S = new (SCEVAllocator)
2545         SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
2546     UniqueSCEVs.InsertNode(S, IP);
2547   }
2548   S->setNoWrapFlags(Flags);
2549   return S;
2550 }
2551 
2552 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2553   uint64_t k = i*j;
2554   if (j > 1 && k / j != i) Overflow = true;
2555   return k;
2556 }
2557 
2558 /// Compute the result of "n choose k", the binomial coefficient.  If an
2559 /// intermediate computation overflows, Overflow will be set and the return will
2560 /// be garbage. Overflow is not cleared on absence of overflow.
2561 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2562   // We use the multiplicative formula:
2563   //     n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2564   // At each iteration, we take the n-th term of the numeral and divide by the
2565   // (k-n)th term of the denominator.  This division will always produce an
2566   // integral result, and helps reduce the chance of overflow in the
2567   // intermediate computations. However, we can still overflow even when the
2568   // final result would fit.
2569 
2570   if (n == 0 || n == k) return 1;
2571   if (k > n) return 0;
2572 
2573   if (k > n/2)
2574     k = n-k;
2575 
2576   uint64_t r = 1;
2577   for (uint64_t i = 1; i <= k; ++i) {
2578     r = umul_ov(r, n-(i-1), Overflow);
2579     r /= i;
2580   }
2581   return r;
2582 }
2583 
2584 /// Determine if any of the operands in this SCEV are a constant or if
2585 /// any of the add or multiply expressions in this SCEV contain a constant.
2586 static bool containsConstantSomewhere(const SCEV *StartExpr) {
2587   SmallVector<const SCEV *, 4> Ops;
2588   Ops.push_back(StartExpr);
2589   while (!Ops.empty()) {
2590     const SCEV *CurrentExpr = Ops.pop_back_val();
2591     if (isa<SCEVConstant>(*CurrentExpr))
2592       return true;
2593 
2594     if (isa<SCEVAddExpr>(*CurrentExpr) || isa<SCEVMulExpr>(*CurrentExpr)) {
2595       const auto *CurrentNAry = cast<SCEVNAryExpr>(CurrentExpr);
2596       Ops.append(CurrentNAry->op_begin(), CurrentNAry->op_end());
2597     }
2598   }
2599   return false;
2600 }
2601 
2602 /// Get a canonical multiply expression, or something simpler if possible.
2603 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
2604                                         SCEV::NoWrapFlags Flags) {
2605   assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&
2606          "only nuw or nsw allowed");
2607   assert(!Ops.empty() && "Cannot get empty mul!");
2608   if (Ops.size() == 1) return Ops[0];
2609 #ifndef NDEBUG
2610   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2611   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2612     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2613            "SCEVMulExpr operand types don't match!");
2614 #endif
2615 
2616   // Sort by complexity, this groups all similar expression types together.
2617   GroupByComplexity(Ops, &LI);
2618 
2619   Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags);
2620 
2621   // If there are any constants, fold them together.
2622   unsigned Idx = 0;
2623   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2624 
2625     // C1*(C2+V) -> C1*C2 + C1*V
2626     if (Ops.size() == 2)
2627         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
2628           // If any of Add's ops are Adds or Muls with a constant,
2629           // apply this transformation as well.
2630           if (Add->getNumOperands() == 2)
2631             if (containsConstantSomewhere(Add))
2632               return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
2633                                 getMulExpr(LHSC, Add->getOperand(1)));
2634 
2635     ++Idx;
2636     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2637       // We found two constants, fold them together!
2638       ConstantInt *Fold =
2639           ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt());
2640       Ops[0] = getConstant(Fold);
2641       Ops.erase(Ops.begin()+1);  // Erase the folded element
2642       if (Ops.size() == 1) return Ops[0];
2643       LHSC = cast<SCEVConstant>(Ops[0]);
2644     }
2645 
2646     // If we are left with a constant one being multiplied, strip it off.
2647     if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
2648       Ops.erase(Ops.begin());
2649       --Idx;
2650     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
2651       // If we have a multiply of zero, it will always be zero.
2652       return Ops[0];
2653     } else if (Ops[0]->isAllOnesValue()) {
2654       // If we have a mul by -1 of an add, try distributing the -1 among the
2655       // add operands.
2656       if (Ops.size() == 2) {
2657         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
2658           SmallVector<const SCEV *, 4> NewOps;
2659           bool AnyFolded = false;
2660           for (const SCEV *AddOp : Add->operands()) {
2661             const SCEV *Mul = getMulExpr(Ops[0], AddOp);
2662             if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
2663             NewOps.push_back(Mul);
2664           }
2665           if (AnyFolded)
2666             return getAddExpr(NewOps);
2667         } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
2668           // Negation preserves a recurrence's no self-wrap property.
2669           SmallVector<const SCEV *, 4> Operands;
2670           for (const SCEV *AddRecOp : AddRec->operands())
2671             Operands.push_back(getMulExpr(Ops[0], AddRecOp));
2672 
2673           return getAddRecExpr(Operands, AddRec->getLoop(),
2674                                AddRec->getNoWrapFlags(SCEV::FlagNW));
2675         }
2676       }
2677     }
2678 
2679     if (Ops.size() == 1)
2680       return Ops[0];
2681   }
2682 
2683   // Skip over the add expression until we get to a multiply.
2684   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2685     ++Idx;
2686 
2687   // If there are mul operands inline them all into this expression.
2688   if (Idx < Ops.size()) {
2689     bool DeletedMul = false;
2690     while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2691       if (Ops.size() > MulOpsInlineThreshold)
2692         break;
2693       // If we have an mul, expand the mul operands onto the end of the operands
2694       // list.
2695       Ops.erase(Ops.begin()+Idx);
2696       Ops.append(Mul->op_begin(), Mul->op_end());
2697       DeletedMul = true;
2698     }
2699 
2700     // If we deleted at least one mul, we added operands to the end of the list,
2701     // and they are not necessarily sorted.  Recurse to resort and resimplify
2702     // any operands we just acquired.
2703     if (DeletedMul)
2704       return getMulExpr(Ops);
2705   }
2706 
2707   // If there are any add recurrences in the operands list, see if any other
2708   // added values are loop invariant.  If so, we can fold them into the
2709   // recurrence.
2710   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2711     ++Idx;
2712 
2713   // Scan over all recurrences, trying to fold loop invariants into them.
2714   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2715     // Scan all of the other operands to this mul and add them to the vector if
2716     // they are loop invariant w.r.t. the recurrence.
2717     SmallVector<const SCEV *, 8> LIOps;
2718     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2719     const Loop *AddRecLoop = AddRec->getLoop();
2720     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2721       if (isLoopInvariant(Ops[i], AddRecLoop)) {
2722         LIOps.push_back(Ops[i]);
2723         Ops.erase(Ops.begin()+i);
2724         --i; --e;
2725       }
2726 
2727     // If we found some loop invariants, fold them into the recurrence.
2728     if (!LIOps.empty()) {
2729       //  NLI * LI * {Start,+,Step}  -->  NLI * {LI*Start,+,LI*Step}
2730       SmallVector<const SCEV *, 4> NewOps;
2731       NewOps.reserve(AddRec->getNumOperands());
2732       const SCEV *Scale = getMulExpr(LIOps);
2733       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
2734         NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
2735 
2736       // Build the new addrec. Propagate the NUW and NSW flags if both the
2737       // outer mul and the inner addrec are guaranteed to have no overflow.
2738       //
2739       // No self-wrap cannot be guaranteed after changing the step size, but
2740       // will be inferred if either NUW or NSW is true.
2741       Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW));
2742       const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
2743 
2744       // If all of the other operands were loop invariant, we are done.
2745       if (Ops.size() == 1) return NewRec;
2746 
2747       // Otherwise, multiply the folded AddRec by the non-invariant parts.
2748       for (unsigned i = 0;; ++i)
2749         if (Ops[i] == AddRec) {
2750           Ops[i] = NewRec;
2751           break;
2752         }
2753       return getMulExpr(Ops);
2754     }
2755 
2756     // Okay, if there weren't any loop invariants to be folded, check to see if
2757     // there are multiple AddRec's with the same loop induction variable being
2758     // multiplied together.  If so, we can fold them.
2759 
2760     // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
2761     // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
2762     //       choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
2763     //   ]]],+,...up to x=2n}.
2764     // Note that the arguments to choose() are always integers with values
2765     // known at compile time, never SCEV objects.
2766     //
2767     // The implementation avoids pointless extra computations when the two
2768     // addrec's are of different length (mathematically, it's equivalent to
2769     // an infinite stream of zeros on the right).
2770     bool OpsModified = false;
2771     for (unsigned OtherIdx = Idx+1;
2772          OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2773          ++OtherIdx) {
2774       const SCEVAddRecExpr *OtherAddRec =
2775         dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2776       if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
2777         continue;
2778 
2779       bool Overflow = false;
2780       Type *Ty = AddRec->getType();
2781       bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
2782       SmallVector<const SCEV*, 7> AddRecOps;
2783       for (int x = 0, xe = AddRec->getNumOperands() +
2784              OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
2785         const SCEV *Term = getZero(Ty);
2786         for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
2787           uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
2788           for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
2789                  ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
2790                z < ze && !Overflow; ++z) {
2791             uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
2792             uint64_t Coeff;
2793             if (LargerThan64Bits)
2794               Coeff = umul_ov(Coeff1, Coeff2, Overflow);
2795             else
2796               Coeff = Coeff1*Coeff2;
2797             const SCEV *CoeffTerm = getConstant(Ty, Coeff);
2798             const SCEV *Term1 = AddRec->getOperand(y-z);
2799             const SCEV *Term2 = OtherAddRec->getOperand(z);
2800             Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1,Term2));
2801           }
2802         }
2803         AddRecOps.push_back(Term);
2804       }
2805       if (!Overflow) {
2806         const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
2807                                               SCEV::FlagAnyWrap);
2808         if (Ops.size() == 2) return NewAddRec;
2809         Ops[Idx] = NewAddRec;
2810         Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2811         OpsModified = true;
2812         AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
2813         if (!AddRec)
2814           break;
2815       }
2816     }
2817     if (OpsModified)
2818       return getMulExpr(Ops);
2819 
2820     // Otherwise couldn't fold anything into this recurrence.  Move onto the
2821     // next one.
2822   }
2823 
2824   // Okay, it looks like we really DO need an mul expr.  Check to see if we
2825   // already have one, otherwise create a new one.
2826   FoldingSetNodeID ID;
2827   ID.AddInteger(scMulExpr);
2828   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2829     ID.AddPointer(Ops[i]);
2830   void *IP = nullptr;
2831   SCEVMulExpr *S =
2832     static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2833   if (!S) {
2834     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2835     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2836     S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2837                                         O, Ops.size());
2838     UniqueSCEVs.InsertNode(S, IP);
2839   }
2840   S->setNoWrapFlags(Flags);
2841   return S;
2842 }
2843 
2844 /// Get a canonical unsigned division expression, or something simpler if
2845 /// possible.
2846 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
2847                                          const SCEV *RHS) {
2848   assert(getEffectiveSCEVType(LHS->getType()) ==
2849          getEffectiveSCEVType(RHS->getType()) &&
2850          "SCEVUDivExpr operand types don't match!");
2851 
2852   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
2853     if (RHSC->getValue()->equalsInt(1))
2854       return LHS;                               // X udiv 1 --> x
2855     // If the denominator is zero, the result of the udiv is undefined. Don't
2856     // try to analyze it, because the resolution chosen here may differ from
2857     // the resolution chosen in other parts of the compiler.
2858     if (!RHSC->getValue()->isZero()) {
2859       // Determine if the division can be folded into the operands of
2860       // its operands.
2861       // TODO: Generalize this to non-constants by using known-bits information.
2862       Type *Ty = LHS->getType();
2863       unsigned LZ = RHSC->getAPInt().countLeadingZeros();
2864       unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
2865       // For non-power-of-two values, effectively round the value up to the
2866       // nearest power of two.
2867       if (!RHSC->getAPInt().isPowerOf2())
2868         ++MaxShiftAmt;
2869       IntegerType *ExtTy =
2870         IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
2871       if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
2872         if (const SCEVConstant *Step =
2873             dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
2874           // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
2875           const APInt &StepInt = Step->getAPInt();
2876           const APInt &DivInt = RHSC->getAPInt();
2877           if (!StepInt.urem(DivInt) &&
2878               getZeroExtendExpr(AR, ExtTy) ==
2879               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2880                             getZeroExtendExpr(Step, ExtTy),
2881                             AR->getLoop(), SCEV::FlagAnyWrap)) {
2882             SmallVector<const SCEV *, 4> Operands;
2883             for (const SCEV *Op : AR->operands())
2884               Operands.push_back(getUDivExpr(Op, RHS));
2885             return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
2886           }
2887           /// Get a canonical UDivExpr for a recurrence.
2888           /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
2889           // We can currently only fold X%N if X is constant.
2890           const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
2891           if (StartC && !DivInt.urem(StepInt) &&
2892               getZeroExtendExpr(AR, ExtTy) ==
2893               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2894                             getZeroExtendExpr(Step, ExtTy),
2895                             AR->getLoop(), SCEV::FlagAnyWrap)) {
2896             const APInt &StartInt = StartC->getAPInt();
2897             const APInt &StartRem = StartInt.urem(StepInt);
2898             if (StartRem != 0)
2899               LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step,
2900                                   AR->getLoop(), SCEV::FlagNW);
2901           }
2902         }
2903       // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
2904       if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
2905         SmallVector<const SCEV *, 4> Operands;
2906         for (const SCEV *Op : M->operands())
2907           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
2908         if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
2909           // Find an operand that's safely divisible.
2910           for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
2911             const SCEV *Op = M->getOperand(i);
2912             const SCEV *Div = getUDivExpr(Op, RHSC);
2913             if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
2914               Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
2915                                                       M->op_end());
2916               Operands[i] = Div;
2917               return getMulExpr(Operands);
2918             }
2919           }
2920       }
2921       // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
2922       if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
2923         SmallVector<const SCEV *, 4> Operands;
2924         for (const SCEV *Op : A->operands())
2925           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
2926         if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
2927           Operands.clear();
2928           for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
2929             const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
2930             if (isa<SCEVUDivExpr>(Op) ||
2931                 getMulExpr(Op, RHS) != A->getOperand(i))
2932               break;
2933             Operands.push_back(Op);
2934           }
2935           if (Operands.size() == A->getNumOperands())
2936             return getAddExpr(Operands);
2937         }
2938       }
2939 
2940       // Fold if both operands are constant.
2941       if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
2942         Constant *LHSCV = LHSC->getValue();
2943         Constant *RHSCV = RHSC->getValue();
2944         return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
2945                                                                    RHSCV)));
2946       }
2947     }
2948   }
2949 
2950   FoldingSetNodeID ID;
2951   ID.AddInteger(scUDivExpr);
2952   ID.AddPointer(LHS);
2953   ID.AddPointer(RHS);
2954   void *IP = nullptr;
2955   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2956   SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
2957                                              LHS, RHS);
2958   UniqueSCEVs.InsertNode(S, IP);
2959   return S;
2960 }
2961 
2962 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
2963   APInt A = C1->getAPInt().abs();
2964   APInt B = C2->getAPInt().abs();
2965   uint32_t ABW = A.getBitWidth();
2966   uint32_t BBW = B.getBitWidth();
2967 
2968   if (ABW > BBW)
2969     B = B.zext(ABW);
2970   else if (ABW < BBW)
2971     A = A.zext(BBW);
2972 
2973   return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B));
2974 }
2975 
2976 /// Get a canonical unsigned division expression, or something simpler if
2977 /// possible. There is no representation for an exact udiv in SCEV IR, but we
2978 /// can attempt to remove factors from the LHS and RHS.  We can't do this when
2979 /// it's not exact because the udiv may be clearing bits.
2980 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
2981                                               const SCEV *RHS) {
2982   // TODO: we could try to find factors in all sorts of things, but for now we
2983   // just deal with u/exact (multiply, constant). See SCEVDivision towards the
2984   // end of this file for inspiration.
2985 
2986   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
2987   if (!Mul || !Mul->hasNoUnsignedWrap())
2988     return getUDivExpr(LHS, RHS);
2989 
2990   if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
2991     // If the mulexpr multiplies by a constant, then that constant must be the
2992     // first element of the mulexpr.
2993     if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
2994       if (LHSCst == RHSCst) {
2995         SmallVector<const SCEV *, 2> Operands;
2996         Operands.append(Mul->op_begin() + 1, Mul->op_end());
2997         return getMulExpr(Operands);
2998       }
2999 
3000       // We can't just assume that LHSCst divides RHSCst cleanly, it could be
3001       // that there's a factor provided by one of the other terms. We need to
3002       // check.
3003       APInt Factor = gcd(LHSCst, RHSCst);
3004       if (!Factor.isIntN(1)) {
3005         LHSCst =
3006             cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
3007         RHSCst =
3008             cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
3009         SmallVector<const SCEV *, 2> Operands;
3010         Operands.push_back(LHSCst);
3011         Operands.append(Mul->op_begin() + 1, Mul->op_end());
3012         LHS = getMulExpr(Operands);
3013         RHS = RHSCst;
3014         Mul = dyn_cast<SCEVMulExpr>(LHS);
3015         if (!Mul)
3016           return getUDivExactExpr(LHS, RHS);
3017       }
3018     }
3019   }
3020 
3021   for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3022     if (Mul->getOperand(i) == RHS) {
3023       SmallVector<const SCEV *, 2> Operands;
3024       Operands.append(Mul->op_begin(), Mul->op_begin() + i);
3025       Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
3026       return getMulExpr(Operands);
3027     }
3028   }
3029 
3030   return getUDivExpr(LHS, RHS);
3031 }
3032 
3033 /// Get an add recurrence expression for the specified loop.  Simplify the
3034 /// expression as much as possible.
3035 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
3036                                            const Loop *L,
3037                                            SCEV::NoWrapFlags Flags) {
3038   SmallVector<const SCEV *, 4> Operands;
3039   Operands.push_back(Start);
3040   if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3041     if (StepChrec->getLoop() == L) {
3042       Operands.append(StepChrec->op_begin(), StepChrec->op_end());
3043       return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
3044     }
3045 
3046   Operands.push_back(Step);
3047   return getAddRecExpr(Operands, L, Flags);
3048 }
3049 
3050 /// Get an add recurrence expression for the specified loop.  Simplify the
3051 /// expression as much as possible.
3052 const SCEV *
3053 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
3054                                const Loop *L, SCEV::NoWrapFlags Flags) {
3055   if (Operands.size() == 1) return Operands[0];
3056 #ifndef NDEBUG
3057   Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
3058   for (unsigned i = 1, e = Operands.size(); i != e; ++i)
3059     assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
3060            "SCEVAddRecExpr operand types don't match!");
3061   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3062     assert(isLoopInvariant(Operands[i], L) &&
3063            "SCEVAddRecExpr operand is not loop-invariant!");
3064 #endif
3065 
3066   if (Operands.back()->isZero()) {
3067     Operands.pop_back();
3068     return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0}  -->  X
3069   }
3070 
3071   // It's tempting to want to call getMaxBackedgeTakenCount count here and
3072   // use that information to infer NUW and NSW flags. However, computing a
3073   // BE count requires calling getAddRecExpr, so we may not yet have a
3074   // meaningful BE count at this point (and if we don't, we'd be stuck
3075   // with a SCEVCouldNotCompute as the cached BE count).
3076 
3077   Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
3078 
3079   // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3080   if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3081     const Loop *NestedLoop = NestedAR->getLoop();
3082     if (L->contains(NestedLoop)
3083             ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3084             : (!NestedLoop->contains(L) &&
3085                DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3086       SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
3087                                                   NestedAR->op_end());
3088       Operands[0] = NestedAR->getStart();
3089       // AddRecs require their operands be loop-invariant with respect to their
3090       // loops. Don't perform this transformation if it would break this
3091       // requirement.
3092       bool AllInvariant = all_of(
3093           Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3094 
3095       if (AllInvariant) {
3096         // Create a recurrence for the outer loop with the same step size.
3097         //
3098         // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3099         // inner recurrence has the same property.
3100         SCEV::NoWrapFlags OuterFlags =
3101           maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3102 
3103         NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3104         AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3105           return isLoopInvariant(Op, NestedLoop);
3106         });
3107 
3108         if (AllInvariant) {
3109           // Ok, both add recurrences are valid after the transformation.
3110           //
3111           // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3112           // the outer recurrence has the same property.
3113           SCEV::NoWrapFlags InnerFlags =
3114             maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
3115           return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3116         }
3117       }
3118       // Reset Operands to its original state.
3119       Operands[0] = NestedAR;
3120     }
3121   }
3122 
3123   // Okay, it looks like we really DO need an addrec expr.  Check to see if we
3124   // already have one, otherwise create a new one.
3125   FoldingSetNodeID ID;
3126   ID.AddInteger(scAddRecExpr);
3127   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3128     ID.AddPointer(Operands[i]);
3129   ID.AddPointer(L);
3130   void *IP = nullptr;
3131   SCEVAddRecExpr *S =
3132     static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3133   if (!S) {
3134     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
3135     std::uninitialized_copy(Operands.begin(), Operands.end(), O);
3136     S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
3137                                            O, Operands.size(), L);
3138     UniqueSCEVs.InsertNode(S, IP);
3139   }
3140   S->setNoWrapFlags(Flags);
3141   return S;
3142 }
3143 
3144 const SCEV *
3145 ScalarEvolution::getGEPExpr(GEPOperator *GEP,
3146                             const SmallVectorImpl<const SCEV *> &IndexExprs) {
3147   const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3148   // getSCEV(Base)->getType() has the same address space as Base->getType()
3149   // because SCEV::getType() preserves the address space.
3150   Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType());
3151   // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP
3152   // instruction to its SCEV, because the Instruction may be guarded by control
3153   // flow and the no-overflow bits may not be valid for the expression in any
3154   // context. This can be fixed similarly to how these flags are handled for
3155   // adds.
3156   SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW
3157                                              : SCEV::FlagAnyWrap;
3158 
3159   const SCEV *TotalOffset = getZero(IntPtrTy);
3160   // The array size is unimportant. The first thing we do on CurTy is getting
3161   // its element type.
3162   Type *CurTy = ArrayType::get(GEP->getSourceElementType(), 0);
3163   for (const SCEV *IndexExpr : IndexExprs) {
3164     // Compute the (potentially symbolic) offset in bytes for this index.
3165     if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3166       // For a struct, add the member offset.
3167       ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3168       unsigned FieldNo = Index->getZExtValue();
3169       const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo);
3170 
3171       // Add the field offset to the running total offset.
3172       TotalOffset = getAddExpr(TotalOffset, FieldOffset);
3173 
3174       // Update CurTy to the type of the field at Index.
3175       CurTy = STy->getTypeAtIndex(Index);
3176     } else {
3177       // Update CurTy to its element type.
3178       CurTy = cast<SequentialType>(CurTy)->getElementType();
3179       // For an array, add the element offset, explicitly scaled.
3180       const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy);
3181       // Getelementptr indices are signed.
3182       IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy);
3183 
3184       // Multiply the index by the element size to compute the element offset.
3185       const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap);
3186 
3187       // Add the element offset to the running total offset.
3188       TotalOffset = getAddExpr(TotalOffset, LocalOffset);
3189     }
3190   }
3191 
3192   // Add the total offset from all the GEP indices to the base.
3193   return getAddExpr(BaseExpr, TotalOffset, Wrap);
3194 }
3195 
3196 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
3197                                          const SCEV *RHS) {
3198   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3199   return getSMaxExpr(Ops);
3200 }
3201 
3202 const SCEV *
3203 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3204   assert(!Ops.empty() && "Cannot get empty smax!");
3205   if (Ops.size() == 1) return Ops[0];
3206 #ifndef NDEBUG
3207   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3208   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3209     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3210            "SCEVSMaxExpr operand types don't match!");
3211 #endif
3212 
3213   // Sort by complexity, this groups all similar expression types together.
3214   GroupByComplexity(Ops, &LI);
3215 
3216   // If there are any constants, fold them together.
3217   unsigned Idx = 0;
3218   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3219     ++Idx;
3220     assert(Idx < Ops.size());
3221     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3222       // We found two constants, fold them together!
3223       ConstantInt *Fold = ConstantInt::get(
3224           getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt()));
3225       Ops[0] = getConstant(Fold);
3226       Ops.erase(Ops.begin()+1);  // Erase the folded element
3227       if (Ops.size() == 1) return Ops[0];
3228       LHSC = cast<SCEVConstant>(Ops[0]);
3229     }
3230 
3231     // If we are left with a constant minimum-int, strip it off.
3232     if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
3233       Ops.erase(Ops.begin());
3234       --Idx;
3235     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
3236       // If we have an smax with a constant maximum-int, it will always be
3237       // maximum-int.
3238       return Ops[0];
3239     }
3240 
3241     if (Ops.size() == 1) return Ops[0];
3242   }
3243 
3244   // Find the first SMax
3245   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
3246     ++Idx;
3247 
3248   // Check to see if one of the operands is an SMax. If so, expand its operands
3249   // onto our operand list, and recurse to simplify.
3250   if (Idx < Ops.size()) {
3251     bool DeletedSMax = false;
3252     while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
3253       Ops.erase(Ops.begin()+Idx);
3254       Ops.append(SMax->op_begin(), SMax->op_end());
3255       DeletedSMax = true;
3256     }
3257 
3258     if (DeletedSMax)
3259       return getSMaxExpr(Ops);
3260   }
3261 
3262   // Okay, check to see if the same value occurs in the operand list twice.  If
3263   // so, delete one.  Since we sorted the list, these values are required to
3264   // be adjacent.
3265   for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
3266     //  X smax Y smax Y  -->  X smax Y
3267     //  X smax Y         -->  X, if X is always greater than Y
3268     if (Ops[i] == Ops[i+1] ||
3269         isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
3270       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3271       --i; --e;
3272     } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
3273       Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3274       --i; --e;
3275     }
3276 
3277   if (Ops.size() == 1) return Ops[0];
3278 
3279   assert(!Ops.empty() && "Reduced smax down to nothing!");
3280 
3281   // Okay, it looks like we really DO need an smax expr.  Check to see if we
3282   // already have one, otherwise create a new one.
3283   FoldingSetNodeID ID;
3284   ID.AddInteger(scSMaxExpr);
3285   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3286     ID.AddPointer(Ops[i]);
3287   void *IP = nullptr;
3288   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3289   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3290   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3291   SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
3292                                              O, Ops.size());
3293   UniqueSCEVs.InsertNode(S, IP);
3294   return S;
3295 }
3296 
3297 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
3298                                          const SCEV *RHS) {
3299   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3300   return getUMaxExpr(Ops);
3301 }
3302 
3303 const SCEV *
3304 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3305   assert(!Ops.empty() && "Cannot get empty umax!");
3306   if (Ops.size() == 1) return Ops[0];
3307 #ifndef NDEBUG
3308   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3309   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3310     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3311            "SCEVUMaxExpr operand types don't match!");
3312 #endif
3313 
3314   // Sort by complexity, this groups all similar expression types together.
3315   GroupByComplexity(Ops, &LI);
3316 
3317   // If there are any constants, fold them together.
3318   unsigned Idx = 0;
3319   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3320     ++Idx;
3321     assert(Idx < Ops.size());
3322     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3323       // We found two constants, fold them together!
3324       ConstantInt *Fold = ConstantInt::get(
3325           getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt()));
3326       Ops[0] = getConstant(Fold);
3327       Ops.erase(Ops.begin()+1);  // Erase the folded element
3328       if (Ops.size() == 1) return Ops[0];
3329       LHSC = cast<SCEVConstant>(Ops[0]);
3330     }
3331 
3332     // If we are left with a constant minimum-int, strip it off.
3333     if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
3334       Ops.erase(Ops.begin());
3335       --Idx;
3336     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
3337       // If we have an umax with a constant maximum-int, it will always be
3338       // maximum-int.
3339       return Ops[0];
3340     }
3341 
3342     if (Ops.size() == 1) return Ops[0];
3343   }
3344 
3345   // Find the first UMax
3346   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
3347     ++Idx;
3348 
3349   // Check to see if one of the operands is a UMax. If so, expand its operands
3350   // onto our operand list, and recurse to simplify.
3351   if (Idx < Ops.size()) {
3352     bool DeletedUMax = false;
3353     while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
3354       Ops.erase(Ops.begin()+Idx);
3355       Ops.append(UMax->op_begin(), UMax->op_end());
3356       DeletedUMax = true;
3357     }
3358 
3359     if (DeletedUMax)
3360       return getUMaxExpr(Ops);
3361   }
3362 
3363   // Okay, check to see if the same value occurs in the operand list twice.  If
3364   // so, delete one.  Since we sorted the list, these values are required to
3365   // be adjacent.
3366   for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
3367     //  X umax Y umax Y  -->  X umax Y
3368     //  X umax Y         -->  X, if X is always greater than Y
3369     if (Ops[i] == Ops[i+1] ||
3370         isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
3371       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3372       --i; --e;
3373     } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
3374       Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3375       --i; --e;
3376     }
3377 
3378   if (Ops.size() == 1) return Ops[0];
3379 
3380   assert(!Ops.empty() && "Reduced umax down to nothing!");
3381 
3382   // Okay, it looks like we really DO need a umax expr.  Check to see if we
3383   // already have one, otherwise create a new one.
3384   FoldingSetNodeID ID;
3385   ID.AddInteger(scUMaxExpr);
3386   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3387     ID.AddPointer(Ops[i]);
3388   void *IP = nullptr;
3389   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3390   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3391   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3392   SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
3393                                              O, Ops.size());
3394   UniqueSCEVs.InsertNode(S, IP);
3395   return S;
3396 }
3397 
3398 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
3399                                          const SCEV *RHS) {
3400   // ~smax(~x, ~y) == smin(x, y).
3401   return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3402 }
3403 
3404 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
3405                                          const SCEV *RHS) {
3406   // ~umax(~x, ~y) == umin(x, y)
3407   return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3408 }
3409 
3410 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
3411   // We can bypass creating a target-independent
3412   // constant expression and then folding it back into a ConstantInt.
3413   // This is just a compile-time optimization.
3414   return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
3415 }
3416 
3417 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
3418                                              StructType *STy,
3419                                              unsigned FieldNo) {
3420   // We can bypass creating a target-independent
3421   // constant expression and then folding it back into a ConstantInt.
3422   // This is just a compile-time optimization.
3423   return getConstant(
3424       IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
3425 }
3426 
3427 const SCEV *ScalarEvolution::getUnknown(Value *V) {
3428   // Don't attempt to do anything other than create a SCEVUnknown object
3429   // here.  createSCEV only calls getUnknown after checking for all other
3430   // interesting possibilities, and any other code that calls getUnknown
3431   // is doing so in order to hide a value from SCEV canonicalization.
3432 
3433   FoldingSetNodeID ID;
3434   ID.AddInteger(scUnknown);
3435   ID.AddPointer(V);
3436   void *IP = nullptr;
3437   if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3438     assert(cast<SCEVUnknown>(S)->getValue() == V &&
3439            "Stale SCEVUnknown in uniquing map!");
3440     return S;
3441   }
3442   SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3443                                             FirstUnknown);
3444   FirstUnknown = cast<SCEVUnknown>(S);
3445   UniqueSCEVs.InsertNode(S, IP);
3446   return S;
3447 }
3448 
3449 //===----------------------------------------------------------------------===//
3450 //            Basic SCEV Analysis and PHI Idiom Recognition Code
3451 //
3452 
3453 /// Test if values of the given type are analyzable within the SCEV
3454 /// framework. This primarily includes integer types, and it can optionally
3455 /// include pointer types if the ScalarEvolution class has access to
3456 /// target-specific information.
3457 bool ScalarEvolution::isSCEVable(Type *Ty) const {
3458   // Integers and pointers are always SCEVable.
3459   return Ty->isIntegerTy() || Ty->isPointerTy();
3460 }
3461 
3462 /// Return the size in bits of the specified type, for which isSCEVable must
3463 /// return true.
3464 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
3465   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3466   return getDataLayout().getTypeSizeInBits(Ty);
3467 }
3468 
3469 /// Return a type with the same bitwidth as the given type and which represents
3470 /// how SCEV will treat the given type, for which isSCEVable must return
3471 /// true. For pointer types, this is the pointer-sized integer type.
3472 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
3473   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3474 
3475   if (Ty->isIntegerTy())
3476     return Ty;
3477 
3478   // The only other support type is pointer.
3479   assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
3480   return getDataLayout().getIntPtrType(Ty);
3481 }
3482 
3483 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const {
3484   return  getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
3485 }
3486 
3487 const SCEV *ScalarEvolution::getCouldNotCompute() {
3488   return CouldNotCompute.get();
3489 }
3490 
3491 bool ScalarEvolution::checkValidity(const SCEV *S) const {
3492   bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
3493     auto *SU = dyn_cast<SCEVUnknown>(S);
3494     return SU && SU->getValue() == nullptr;
3495   });
3496 
3497   return !ContainsNulls;
3498 }
3499 
3500 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
3501   HasRecMapType::iterator I = HasRecMap.find(S);
3502   if (I != HasRecMap.end())
3503     return I->second;
3504 
3505   bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>);
3506   HasRecMap.insert({S, FoundAddRec});
3507   return FoundAddRec;
3508 }
3509 
3510 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}.
3511 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an
3512 /// offset I, then return {S', I}, else return {\p S, nullptr}.
3513 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) {
3514   const auto *Add = dyn_cast<SCEVAddExpr>(S);
3515   if (!Add)
3516     return {S, nullptr};
3517 
3518   if (Add->getNumOperands() != 2)
3519     return {S, nullptr};
3520 
3521   auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0));
3522   if (!ConstOp)
3523     return {S, nullptr};
3524 
3525   return {Add->getOperand(1), ConstOp->getValue()};
3526 }
3527 
3528 /// Return the ValueOffsetPair set for \p S. \p S can be represented
3529 /// by the value and offset from any ValueOffsetPair in the set.
3530 SetVector<ScalarEvolution::ValueOffsetPair> *
3531 ScalarEvolution::getSCEVValues(const SCEV *S) {
3532   ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
3533   if (SI == ExprValueMap.end())
3534     return nullptr;
3535 #ifndef NDEBUG
3536   if (VerifySCEVMap) {
3537     // Check there is no dangling Value in the set returned.
3538     for (const auto &VE : SI->second)
3539       assert(ValueExprMap.count(VE.first));
3540   }
3541 #endif
3542   return &SI->second;
3543 }
3544 
3545 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
3546 /// cannot be used separately. eraseValueFromMap should be used to remove
3547 /// V from ValueExprMap and ExprValueMap at the same time.
3548 void ScalarEvolution::eraseValueFromMap(Value *V) {
3549   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3550   if (I != ValueExprMap.end()) {
3551     const SCEV *S = I->second;
3552     // Remove {V, 0} from the set of ExprValueMap[S]
3553     if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S))
3554       SV->remove({V, nullptr});
3555 
3556     // Remove {V, Offset} from the set of ExprValueMap[Stripped]
3557     const SCEV *Stripped;
3558     ConstantInt *Offset;
3559     std::tie(Stripped, Offset) = splitAddExpr(S);
3560     if (Offset != nullptr) {
3561       if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped))
3562         SV->remove({V, Offset});
3563     }
3564     ValueExprMap.erase(V);
3565   }
3566 }
3567 
3568 /// Return an existing SCEV if it exists, otherwise analyze the expression and
3569 /// create a new one.
3570 const SCEV *ScalarEvolution::getSCEV(Value *V) {
3571   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3572 
3573   const SCEV *S = getExistingSCEV(V);
3574   if (S == nullptr) {
3575     S = createSCEV(V);
3576     // During PHI resolution, it is possible to create two SCEVs for the same
3577     // V, so it is needed to double check whether V->S is inserted into
3578     // ValueExprMap before insert S->{V, 0} into ExprValueMap.
3579     std::pair<ValueExprMapType::iterator, bool> Pair =
3580         ValueExprMap.insert({SCEVCallbackVH(V, this), S});
3581     if (Pair.second) {
3582       ExprValueMap[S].insert({V, nullptr});
3583 
3584       // If S == Stripped + Offset, add Stripped -> {V, Offset} into
3585       // ExprValueMap.
3586       const SCEV *Stripped = S;
3587       ConstantInt *Offset = nullptr;
3588       std::tie(Stripped, Offset) = splitAddExpr(S);
3589       // If stripped is SCEVUnknown, don't bother to save
3590       // Stripped -> {V, offset}. It doesn't simplify and sometimes even
3591       // increase the complexity of the expansion code.
3592       // If V is GetElementPtrInst, don't save Stripped -> {V, offset}
3593       // because it may generate add/sub instead of GEP in SCEV expansion.
3594       if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) &&
3595           !isa<GetElementPtrInst>(V))
3596         ExprValueMap[Stripped].insert({V, Offset});
3597     }
3598   }
3599   return S;
3600 }
3601 
3602 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
3603   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3604 
3605   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3606   if (I != ValueExprMap.end()) {
3607     const SCEV *S = I->second;
3608     if (checkValidity(S))
3609       return S;
3610     eraseValueFromMap(V);
3611     forgetMemoizedResults(S);
3612   }
3613   return nullptr;
3614 }
3615 
3616 /// Return a SCEV corresponding to -V = -1*V
3617 ///
3618 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
3619                                              SCEV::NoWrapFlags Flags) {
3620   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3621     return getConstant(
3622                cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
3623 
3624   Type *Ty = V->getType();
3625   Ty = getEffectiveSCEVType(Ty);
3626   return getMulExpr(
3627       V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags);
3628 }
3629 
3630 /// Return a SCEV corresponding to ~V = -1-V
3631 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
3632   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3633     return getConstant(
3634                 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
3635 
3636   Type *Ty = V->getType();
3637   Ty = getEffectiveSCEVType(Ty);
3638   const SCEV *AllOnes =
3639                    getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
3640   return getMinusSCEV(AllOnes, V);
3641 }
3642 
3643 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
3644                                           SCEV::NoWrapFlags Flags) {
3645   // Fast path: X - X --> 0.
3646   if (LHS == RHS)
3647     return getZero(LHS->getType());
3648 
3649   // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
3650   // makes it so that we cannot make much use of NUW.
3651   auto AddFlags = SCEV::FlagAnyWrap;
3652   const bool RHSIsNotMinSigned =
3653       !getSignedRange(RHS).getSignedMin().isMinSignedValue();
3654   if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) {
3655     // Let M be the minimum representable signed value. Then (-1)*RHS
3656     // signed-wraps if and only if RHS is M. That can happen even for
3657     // a NSW subtraction because e.g. (-1)*M signed-wraps even though
3658     // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
3659     // (-1)*RHS, we need to prove that RHS != M.
3660     //
3661     // If LHS is non-negative and we know that LHS - RHS does not
3662     // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
3663     // either by proving that RHS > M or that LHS >= 0.
3664     if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
3665       AddFlags = SCEV::FlagNSW;
3666     }
3667   }
3668 
3669   // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
3670   // RHS is NSW and LHS >= 0.
3671   //
3672   // The difficulty here is that the NSW flag may have been proven
3673   // relative to a loop that is to be found in a recurrence in LHS and
3674   // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
3675   // larger scope than intended.
3676   auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3677 
3678   return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags);
3679 }
3680 
3681 const SCEV *
3682 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) {
3683   Type *SrcTy = V->getType();
3684   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3685          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3686          "Cannot truncate or zero extend with non-integer arguments!");
3687   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3688     return V;  // No conversion
3689   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
3690     return getTruncateExpr(V, Ty);
3691   return getZeroExtendExpr(V, Ty);
3692 }
3693 
3694 const SCEV *
3695 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
3696                                          Type *Ty) {
3697   Type *SrcTy = V->getType();
3698   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3699          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3700          "Cannot truncate or zero extend with non-integer arguments!");
3701   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3702     return V;  // No conversion
3703   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
3704     return getTruncateExpr(V, Ty);
3705   return getSignExtendExpr(V, Ty);
3706 }
3707 
3708 const SCEV *
3709 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
3710   Type *SrcTy = V->getType();
3711   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3712          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3713          "Cannot noop or zero extend with non-integer arguments!");
3714   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3715          "getNoopOrZeroExtend cannot truncate!");
3716   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3717     return V;  // No conversion
3718   return getZeroExtendExpr(V, Ty);
3719 }
3720 
3721 const SCEV *
3722 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
3723   Type *SrcTy = V->getType();
3724   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3725          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3726          "Cannot noop or sign extend with non-integer arguments!");
3727   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3728          "getNoopOrSignExtend cannot truncate!");
3729   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3730     return V;  // No conversion
3731   return getSignExtendExpr(V, Ty);
3732 }
3733 
3734 const SCEV *
3735 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
3736   Type *SrcTy = V->getType();
3737   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3738          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3739          "Cannot noop or any extend with non-integer arguments!");
3740   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3741          "getNoopOrAnyExtend cannot truncate!");
3742   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3743     return V;  // No conversion
3744   return getAnyExtendExpr(V, Ty);
3745 }
3746 
3747 const SCEV *
3748 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
3749   Type *SrcTy = V->getType();
3750   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3751          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3752          "Cannot truncate or noop with non-integer arguments!");
3753   assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
3754          "getTruncateOrNoop cannot extend!");
3755   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3756     return V;  // No conversion
3757   return getTruncateExpr(V, Ty);
3758 }
3759 
3760 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
3761                                                         const SCEV *RHS) {
3762   const SCEV *PromotedLHS = LHS;
3763   const SCEV *PromotedRHS = RHS;
3764 
3765   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3766     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3767   else
3768     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3769 
3770   return getUMaxExpr(PromotedLHS, PromotedRHS);
3771 }
3772 
3773 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
3774                                                         const SCEV *RHS) {
3775   const SCEV *PromotedLHS = LHS;
3776   const SCEV *PromotedRHS = RHS;
3777 
3778   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3779     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3780   else
3781     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3782 
3783   return getUMinExpr(PromotedLHS, PromotedRHS);
3784 }
3785 
3786 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
3787   // A pointer operand may evaluate to a nonpointer expression, such as null.
3788   if (!V->getType()->isPointerTy())
3789     return V;
3790 
3791   if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
3792     return getPointerBase(Cast->getOperand());
3793   } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
3794     const SCEV *PtrOp = nullptr;
3795     for (const SCEV *NAryOp : NAry->operands()) {
3796       if (NAryOp->getType()->isPointerTy()) {
3797         // Cannot find the base of an expression with multiple pointer operands.
3798         if (PtrOp)
3799           return V;
3800         PtrOp = NAryOp;
3801       }
3802     }
3803     if (!PtrOp)
3804       return V;
3805     return getPointerBase(PtrOp);
3806   }
3807   return V;
3808 }
3809 
3810 /// Push users of the given Instruction onto the given Worklist.
3811 static void
3812 PushDefUseChildren(Instruction *I,
3813                    SmallVectorImpl<Instruction *> &Worklist) {
3814   // Push the def-use children onto the Worklist stack.
3815   for (User *U : I->users())
3816     Worklist.push_back(cast<Instruction>(U));
3817 }
3818 
3819 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) {
3820   SmallVector<Instruction *, 16> Worklist;
3821   PushDefUseChildren(PN, Worklist);
3822 
3823   SmallPtrSet<Instruction *, 8> Visited;
3824   Visited.insert(PN);
3825   while (!Worklist.empty()) {
3826     Instruction *I = Worklist.pop_back_val();
3827     if (!Visited.insert(I).second)
3828       continue;
3829 
3830     auto It = ValueExprMap.find_as(static_cast<Value *>(I));
3831     if (It != ValueExprMap.end()) {
3832       const SCEV *Old = It->second;
3833 
3834       // Short-circuit the def-use traversal if the symbolic name
3835       // ceases to appear in expressions.
3836       if (Old != SymName && !hasOperand(Old, SymName))
3837         continue;
3838 
3839       // SCEVUnknown for a PHI either means that it has an unrecognized
3840       // structure, it's a PHI that's in the progress of being computed
3841       // by createNodeForPHI, or it's a single-value PHI. In the first case,
3842       // additional loop trip count information isn't going to change anything.
3843       // In the second case, createNodeForPHI will perform the necessary
3844       // updates on its own when it gets to that point. In the third, we do
3845       // want to forget the SCEVUnknown.
3846       if (!isa<PHINode>(I) ||
3847           !isa<SCEVUnknown>(Old) ||
3848           (I != PN && Old == SymName)) {
3849         eraseValueFromMap(It->first);
3850         forgetMemoizedResults(Old);
3851       }
3852     }
3853 
3854     PushDefUseChildren(I, Worklist);
3855   }
3856 }
3857 
3858 namespace {
3859 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
3860 public:
3861   static const SCEV *rewrite(const SCEV *S, const Loop *L,
3862                              ScalarEvolution &SE) {
3863     SCEVInitRewriter Rewriter(L, SE);
3864     const SCEV *Result = Rewriter.visit(S);
3865     return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
3866   }
3867 
3868   SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
3869       : SCEVRewriteVisitor(SE), L(L), Valid(true) {}
3870 
3871   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
3872     if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant))
3873       Valid = false;
3874     return Expr;
3875   }
3876 
3877   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
3878     // Only allow AddRecExprs for this loop.
3879     if (Expr->getLoop() == L)
3880       return Expr->getStart();
3881     Valid = false;
3882     return Expr;
3883   }
3884 
3885   bool isValid() { return Valid; }
3886 
3887 private:
3888   const Loop *L;
3889   bool Valid;
3890 };
3891 
3892 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
3893 public:
3894   static const SCEV *rewrite(const SCEV *S, const Loop *L,
3895                              ScalarEvolution &SE) {
3896     SCEVShiftRewriter Rewriter(L, SE);
3897     const SCEV *Result = Rewriter.visit(S);
3898     return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
3899   }
3900 
3901   SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
3902       : SCEVRewriteVisitor(SE), L(L), Valid(true) {}
3903 
3904   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
3905     // Only allow AddRecExprs for this loop.
3906     if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant))
3907       Valid = false;
3908     return Expr;
3909   }
3910 
3911   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
3912     if (Expr->getLoop() == L && Expr->isAffine())
3913       return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
3914     Valid = false;
3915     return Expr;
3916   }
3917   bool isValid() { return Valid; }
3918 
3919 private:
3920   const Loop *L;
3921   bool Valid;
3922 };
3923 } // end anonymous namespace
3924 
3925 SCEV::NoWrapFlags
3926 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
3927   if (!AR->isAffine())
3928     return SCEV::FlagAnyWrap;
3929 
3930   typedef OverflowingBinaryOperator OBO;
3931   SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
3932 
3933   if (!AR->hasNoSignedWrap()) {
3934     ConstantRange AddRecRange = getSignedRange(AR);
3935     ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
3936 
3937     auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
3938         Instruction::Add, IncRange, OBO::NoSignedWrap);
3939     if (NSWRegion.contains(AddRecRange))
3940       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
3941   }
3942 
3943   if (!AR->hasNoUnsignedWrap()) {
3944     ConstantRange AddRecRange = getUnsignedRange(AR);
3945     ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
3946 
3947     auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
3948         Instruction::Add, IncRange, OBO::NoUnsignedWrap);
3949     if (NUWRegion.contains(AddRecRange))
3950       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
3951   }
3952 
3953   return Result;
3954 }
3955 
3956 namespace {
3957 /// Represents an abstract binary operation.  This may exist as a
3958 /// normal instruction or constant expression, or may have been
3959 /// derived from an expression tree.
3960 struct BinaryOp {
3961   unsigned Opcode;
3962   Value *LHS;
3963   Value *RHS;
3964   bool IsNSW;
3965   bool IsNUW;
3966 
3967   /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
3968   /// constant expression.
3969   Operator *Op;
3970 
3971   explicit BinaryOp(Operator *Op)
3972       : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
3973         IsNSW(false), IsNUW(false), Op(Op) {
3974     if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
3975       IsNSW = OBO->hasNoSignedWrap();
3976       IsNUW = OBO->hasNoUnsignedWrap();
3977     }
3978   }
3979 
3980   explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
3981                     bool IsNUW = false)
3982       : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW),
3983         Op(nullptr) {}
3984 };
3985 }
3986 
3987 
3988 /// Try to map \p V into a BinaryOp, and return \c None on failure.
3989 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) {
3990   auto *Op = dyn_cast<Operator>(V);
3991   if (!Op)
3992     return None;
3993 
3994   // Implementation detail: all the cleverness here should happen without
3995   // creating new SCEV expressions -- our caller knowns tricks to avoid creating
3996   // SCEV expressions when possible, and we should not break that.
3997 
3998   switch (Op->getOpcode()) {
3999   case Instruction::Add:
4000   case Instruction::Sub:
4001   case Instruction::Mul:
4002   case Instruction::UDiv:
4003   case Instruction::And:
4004   case Instruction::Or:
4005   case Instruction::AShr:
4006   case Instruction::Shl:
4007     return BinaryOp(Op);
4008 
4009   case Instruction::Xor:
4010     if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
4011       // If the RHS of the xor is a signmask, then this is just an add.
4012       // Instcombine turns add of signmask into xor as a strength reduction step.
4013       if (RHSC->getValue().isSignMask())
4014         return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
4015     return BinaryOp(Op);
4016 
4017   case Instruction::LShr:
4018     // Turn logical shift right of a constant into a unsigned divide.
4019     if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
4020       uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
4021 
4022       // If the shift count is not less than the bitwidth, the result of
4023       // the shift is undefined. Don't try to analyze it, because the
4024       // resolution chosen here may differ from the resolution chosen in
4025       // other parts of the compiler.
4026       if (SA->getValue().ult(BitWidth)) {
4027         Constant *X =
4028             ConstantInt::get(SA->getContext(),
4029                              APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
4030         return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
4031       }
4032     }
4033     return BinaryOp(Op);
4034 
4035   case Instruction::ExtractValue: {
4036     auto *EVI = cast<ExtractValueInst>(Op);
4037     if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
4038       break;
4039 
4040     auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand());
4041     if (!CI)
4042       break;
4043 
4044     if (auto *F = CI->getCalledFunction())
4045       switch (F->getIntrinsicID()) {
4046       case Intrinsic::sadd_with_overflow:
4047       case Intrinsic::uadd_with_overflow: {
4048         if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT))
4049           return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4050                           CI->getArgOperand(1));
4051 
4052         // Now that we know that all uses of the arithmetic-result component of
4053         // CI are guarded by the overflow check, we can go ahead and pretend
4054         // that the arithmetic is non-overflowing.
4055         if (F->getIntrinsicID() == Intrinsic::sadd_with_overflow)
4056           return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4057                           CI->getArgOperand(1), /* IsNSW = */ true,
4058                           /* IsNUW = */ false);
4059         else
4060           return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4061                           CI->getArgOperand(1), /* IsNSW = */ false,
4062                           /* IsNUW*/ true);
4063       }
4064 
4065       case Intrinsic::ssub_with_overflow:
4066       case Intrinsic::usub_with_overflow:
4067         return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
4068                         CI->getArgOperand(1));
4069 
4070       case Intrinsic::smul_with_overflow:
4071       case Intrinsic::umul_with_overflow:
4072         return BinaryOp(Instruction::Mul, CI->getArgOperand(0),
4073                         CI->getArgOperand(1));
4074       default:
4075         break;
4076       }
4077   }
4078 
4079   default:
4080     break;
4081   }
4082 
4083   return None;
4084 }
4085 
4086 /// A helper function for createAddRecFromPHI to handle simple cases.
4087 ///
4088 /// This function tries to find an AddRec expression for the simplest (yet most
4089 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
4090 /// If it fails, createAddRecFromPHI will use a more general, but slow,
4091 /// technique for finding the AddRec expression.
4092 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
4093                                                       Value *BEValueV,
4094                                                       Value *StartValueV) {
4095   const Loop *L = LI.getLoopFor(PN->getParent());
4096   assert(L && L->getHeader() == PN->getParent());
4097   assert(BEValueV && StartValueV);
4098 
4099   auto BO = MatchBinaryOp(BEValueV, DT);
4100   if (!BO)
4101     return nullptr;
4102 
4103   if (BO->Opcode != Instruction::Add)
4104     return nullptr;
4105 
4106   const SCEV *Accum = nullptr;
4107   if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
4108     Accum = getSCEV(BO->RHS);
4109   else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
4110     Accum = getSCEV(BO->LHS);
4111 
4112   if (!Accum)
4113     return nullptr;
4114 
4115   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4116   if (BO->IsNUW)
4117     Flags = setFlags(Flags, SCEV::FlagNUW);
4118   if (BO->IsNSW)
4119     Flags = setFlags(Flags, SCEV::FlagNSW);
4120 
4121   const SCEV *StartVal = getSCEV(StartValueV);
4122   const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
4123 
4124   ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
4125 
4126   // We can add Flags to the post-inc expression only if we
4127   // know that it is *undefined behavior* for BEValueV to
4128   // overflow.
4129   if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
4130     if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
4131       (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
4132 
4133   return PHISCEV;
4134 }
4135 
4136 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
4137   const Loop *L = LI.getLoopFor(PN->getParent());
4138   if (!L || L->getHeader() != PN->getParent())
4139     return nullptr;
4140 
4141   // The loop may have multiple entrances or multiple exits; we can analyze
4142   // this phi as an addrec if it has a unique entry value and a unique
4143   // backedge value.
4144   Value *BEValueV = nullptr, *StartValueV = nullptr;
4145   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4146     Value *V = PN->getIncomingValue(i);
4147     if (L->contains(PN->getIncomingBlock(i))) {
4148       if (!BEValueV) {
4149         BEValueV = V;
4150       } else if (BEValueV != V) {
4151         BEValueV = nullptr;
4152         break;
4153       }
4154     } else if (!StartValueV) {
4155       StartValueV = V;
4156     } else if (StartValueV != V) {
4157       StartValueV = nullptr;
4158       break;
4159     }
4160   }
4161   if (!BEValueV || !StartValueV)
4162     return nullptr;
4163 
4164   assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
4165          "PHI node already processed?");
4166 
4167   // First, try to find AddRec expression without creating a fictituos symbolic
4168   // value for PN.
4169   if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
4170     return S;
4171 
4172   // Handle PHI node value symbolically.
4173   const SCEV *SymbolicName = getUnknown(PN);
4174   ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName});
4175 
4176   // Using this symbolic name for the PHI, analyze the value coming around
4177   // the back-edge.
4178   const SCEV *BEValue = getSCEV(BEValueV);
4179 
4180   // NOTE: If BEValue is loop invariant, we know that the PHI node just
4181   // has a special value for the first iteration of the loop.
4182 
4183   // If the value coming around the backedge is an add with the symbolic
4184   // value we just inserted, then we found a simple induction variable!
4185   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
4186     // If there is a single occurrence of the symbolic value, replace it
4187     // with a recurrence.
4188     unsigned FoundIndex = Add->getNumOperands();
4189     for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4190       if (Add->getOperand(i) == SymbolicName)
4191         if (FoundIndex == e) {
4192           FoundIndex = i;
4193           break;
4194         }
4195 
4196     if (FoundIndex != Add->getNumOperands()) {
4197       // Create an add with everything but the specified operand.
4198       SmallVector<const SCEV *, 8> Ops;
4199       for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4200         if (i != FoundIndex)
4201           Ops.push_back(Add->getOperand(i));
4202       const SCEV *Accum = getAddExpr(Ops);
4203 
4204       // This is not a valid addrec if the step amount is varying each
4205       // loop iteration, but is not itself an addrec in this loop.
4206       if (isLoopInvariant(Accum, L) ||
4207           (isa<SCEVAddRecExpr>(Accum) &&
4208            cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
4209         SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4210 
4211         if (auto BO = MatchBinaryOp(BEValueV, DT)) {
4212           if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
4213             if (BO->IsNUW)
4214               Flags = setFlags(Flags, SCEV::FlagNUW);
4215             if (BO->IsNSW)
4216               Flags = setFlags(Flags, SCEV::FlagNSW);
4217           }
4218         } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
4219           // If the increment is an inbounds GEP, then we know the address
4220           // space cannot be wrapped around. We cannot make any guarantee
4221           // about signed or unsigned overflow because pointers are
4222           // unsigned but we may have a negative index from the base
4223           // pointer. We can guarantee that no unsigned wrap occurs if the
4224           // indices form a positive value.
4225           if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
4226             Flags = setFlags(Flags, SCEV::FlagNW);
4227 
4228             const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
4229             if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
4230               Flags = setFlags(Flags, SCEV::FlagNUW);
4231           }
4232 
4233           // We cannot transfer nuw and nsw flags from subtraction
4234           // operations -- sub nuw X, Y is not the same as add nuw X, -Y
4235           // for instance.
4236         }
4237 
4238         const SCEV *StartVal = getSCEV(StartValueV);
4239         const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
4240 
4241         // Okay, for the entire analysis of this edge we assumed the PHI
4242         // to be symbolic.  We now need to go back and purge all of the
4243         // entries for the scalars that use the symbolic expression.
4244         forgetSymbolicName(PN, SymbolicName);
4245         ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
4246 
4247         // We can add Flags to the post-inc expression only if we
4248         // know that it is *undefined behavior* for BEValueV to
4249         // overflow.
4250         if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
4251           if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
4252             (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
4253 
4254         return PHISCEV;
4255       }
4256     }
4257   } else {
4258     // Otherwise, this could be a loop like this:
4259     //     i = 0;  for (j = 1; ..; ++j) { ....  i = j; }
4260     // In this case, j = {1,+,1}  and BEValue is j.
4261     // Because the other in-value of i (0) fits the evolution of BEValue
4262     // i really is an addrec evolution.
4263     //
4264     // We can generalize this saying that i is the shifted value of BEValue
4265     // by one iteration:
4266     //   PHI(f(0), f({1,+,1})) --> f({0,+,1})
4267     const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
4268     const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this);
4269     if (Shifted != getCouldNotCompute() &&
4270         Start != getCouldNotCompute()) {
4271       const SCEV *StartVal = getSCEV(StartValueV);
4272       if (Start == StartVal) {
4273         // Okay, for the entire analysis of this edge we assumed the PHI
4274         // to be symbolic.  We now need to go back and purge all of the
4275         // entries for the scalars that use the symbolic expression.
4276         forgetSymbolicName(PN, SymbolicName);
4277         ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted;
4278         return Shifted;
4279       }
4280     }
4281   }
4282 
4283   // Remove the temporary PHI node SCEV that has been inserted while intending
4284   // to create an AddRecExpr for this PHI node. We can not keep this temporary
4285   // as it will prevent later (possibly simpler) SCEV expressions to be added
4286   // to the ValueExprMap.
4287   eraseValueFromMap(PN);
4288 
4289   return nullptr;
4290 }
4291 
4292 // Checks if the SCEV S is available at BB.  S is considered available at BB
4293 // if S can be materialized at BB without introducing a fault.
4294 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
4295                                BasicBlock *BB) {
4296   struct CheckAvailable {
4297     bool TraversalDone = false;
4298     bool Available = true;
4299 
4300     const Loop *L = nullptr;  // The loop BB is in (can be nullptr)
4301     BasicBlock *BB = nullptr;
4302     DominatorTree &DT;
4303 
4304     CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
4305       : L(L), BB(BB), DT(DT) {}
4306 
4307     bool setUnavailable() {
4308       TraversalDone = true;
4309       Available = false;
4310       return false;
4311     }
4312 
4313     bool follow(const SCEV *S) {
4314       switch (S->getSCEVType()) {
4315       case scConstant: case scTruncate: case scZeroExtend: case scSignExtend:
4316       case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr:
4317         // These expressions are available if their operand(s) is/are.
4318         return true;
4319 
4320       case scAddRecExpr: {
4321         // We allow add recurrences that are on the loop BB is in, or some
4322         // outer loop.  This guarantees availability because the value of the
4323         // add recurrence at BB is simply the "current" value of the induction
4324         // variable.  We can relax this in the future; for instance an add
4325         // recurrence on a sibling dominating loop is also available at BB.
4326         const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
4327         if (L && (ARLoop == L || ARLoop->contains(L)))
4328           return true;
4329 
4330         return setUnavailable();
4331       }
4332 
4333       case scUnknown: {
4334         // For SCEVUnknown, we check for simple dominance.
4335         const auto *SU = cast<SCEVUnknown>(S);
4336         Value *V = SU->getValue();
4337 
4338         if (isa<Argument>(V))
4339           return false;
4340 
4341         if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
4342           return false;
4343 
4344         return setUnavailable();
4345       }
4346 
4347       case scUDivExpr:
4348       case scCouldNotCompute:
4349         // We do not try to smart about these at all.
4350         return setUnavailable();
4351       }
4352       llvm_unreachable("switch should be fully covered!");
4353     }
4354 
4355     bool isDone() { return TraversalDone; }
4356   };
4357 
4358   CheckAvailable CA(L, BB, DT);
4359   SCEVTraversal<CheckAvailable> ST(CA);
4360 
4361   ST.visitAll(S);
4362   return CA.Available;
4363 }
4364 
4365 // Try to match a control flow sequence that branches out at BI and merges back
4366 // at Merge into a "C ? LHS : RHS" select pattern.  Return true on a successful
4367 // match.
4368 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
4369                           Value *&C, Value *&LHS, Value *&RHS) {
4370   C = BI->getCondition();
4371 
4372   BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
4373   BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
4374 
4375   if (!LeftEdge.isSingleEdge())
4376     return false;
4377 
4378   assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
4379 
4380   Use &LeftUse = Merge->getOperandUse(0);
4381   Use &RightUse = Merge->getOperandUse(1);
4382 
4383   if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
4384     LHS = LeftUse;
4385     RHS = RightUse;
4386     return true;
4387   }
4388 
4389   if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
4390     LHS = RightUse;
4391     RHS = LeftUse;
4392     return true;
4393   }
4394 
4395   return false;
4396 }
4397 
4398 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
4399   auto IsReachable =
4400       [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
4401   if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
4402     const Loop *L = LI.getLoopFor(PN->getParent());
4403 
4404     // We don't want to break LCSSA, even in a SCEV expression tree.
4405     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
4406       if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
4407         return nullptr;
4408 
4409     // Try to match
4410     //
4411     //  br %cond, label %left, label %right
4412     // left:
4413     //  br label %merge
4414     // right:
4415     //  br label %merge
4416     // merge:
4417     //  V = phi [ %x, %left ], [ %y, %right ]
4418     //
4419     // as "select %cond, %x, %y"
4420 
4421     BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
4422     assert(IDom && "At least the entry block should dominate PN");
4423 
4424     auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
4425     Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
4426 
4427     if (BI && BI->isConditional() &&
4428         BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
4429         IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
4430         IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
4431       return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
4432   }
4433 
4434   return nullptr;
4435 }
4436 
4437 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
4438   if (const SCEV *S = createAddRecFromPHI(PN))
4439     return S;
4440 
4441   if (const SCEV *S = createNodeFromSelectLikePHI(PN))
4442     return S;
4443 
4444   // If the PHI has a single incoming value, follow that value, unless the
4445   // PHI's incoming blocks are in a different loop, in which case doing so
4446   // risks breaking LCSSA form. Instcombine would normally zap these, but
4447   // it doesn't have DominatorTree information, so it may miss cases.
4448   if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC}))
4449     if (LI.replacementPreservesLCSSAForm(PN, V))
4450       return getSCEV(V);
4451 
4452   // If it's not a loop phi, we can't handle it yet.
4453   return getUnknown(PN);
4454 }
4455 
4456 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I,
4457                                                       Value *Cond,
4458                                                       Value *TrueVal,
4459                                                       Value *FalseVal) {
4460   // Handle "constant" branch or select. This can occur for instance when a
4461   // loop pass transforms an inner loop and moves on to process the outer loop.
4462   if (auto *CI = dyn_cast<ConstantInt>(Cond))
4463     return getSCEV(CI->isOne() ? TrueVal : FalseVal);
4464 
4465   // Try to match some simple smax or umax patterns.
4466   auto *ICI = dyn_cast<ICmpInst>(Cond);
4467   if (!ICI)
4468     return getUnknown(I);
4469 
4470   Value *LHS = ICI->getOperand(0);
4471   Value *RHS = ICI->getOperand(1);
4472 
4473   switch (ICI->getPredicate()) {
4474   case ICmpInst::ICMP_SLT:
4475   case ICmpInst::ICMP_SLE:
4476     std::swap(LHS, RHS);
4477     LLVM_FALLTHROUGH;
4478   case ICmpInst::ICMP_SGT:
4479   case ICmpInst::ICMP_SGE:
4480     // a >s b ? a+x : b+x  ->  smax(a, b)+x
4481     // a >s b ? b+x : a+x  ->  smin(a, b)+x
4482     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
4483       const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType());
4484       const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType());
4485       const SCEV *LA = getSCEV(TrueVal);
4486       const SCEV *RA = getSCEV(FalseVal);
4487       const SCEV *LDiff = getMinusSCEV(LA, LS);
4488       const SCEV *RDiff = getMinusSCEV(RA, RS);
4489       if (LDiff == RDiff)
4490         return getAddExpr(getSMaxExpr(LS, RS), LDiff);
4491       LDiff = getMinusSCEV(LA, RS);
4492       RDiff = getMinusSCEV(RA, LS);
4493       if (LDiff == RDiff)
4494         return getAddExpr(getSMinExpr(LS, RS), LDiff);
4495     }
4496     break;
4497   case ICmpInst::ICMP_ULT:
4498   case ICmpInst::ICMP_ULE:
4499     std::swap(LHS, RHS);
4500     LLVM_FALLTHROUGH;
4501   case ICmpInst::ICMP_UGT:
4502   case ICmpInst::ICMP_UGE:
4503     // a >u b ? a+x : b+x  ->  umax(a, b)+x
4504     // a >u b ? b+x : a+x  ->  umin(a, b)+x
4505     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
4506       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4507       const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType());
4508       const SCEV *LA = getSCEV(TrueVal);
4509       const SCEV *RA = getSCEV(FalseVal);
4510       const SCEV *LDiff = getMinusSCEV(LA, LS);
4511       const SCEV *RDiff = getMinusSCEV(RA, RS);
4512       if (LDiff == RDiff)
4513         return getAddExpr(getUMaxExpr(LS, RS), LDiff);
4514       LDiff = getMinusSCEV(LA, RS);
4515       RDiff = getMinusSCEV(RA, LS);
4516       if (LDiff == RDiff)
4517         return getAddExpr(getUMinExpr(LS, RS), LDiff);
4518     }
4519     break;
4520   case ICmpInst::ICMP_NE:
4521     // n != 0 ? n+x : 1+x  ->  umax(n, 1)+x
4522     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
4523         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
4524       const SCEV *One = getOne(I->getType());
4525       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4526       const SCEV *LA = getSCEV(TrueVal);
4527       const SCEV *RA = getSCEV(FalseVal);
4528       const SCEV *LDiff = getMinusSCEV(LA, LS);
4529       const SCEV *RDiff = getMinusSCEV(RA, One);
4530       if (LDiff == RDiff)
4531         return getAddExpr(getUMaxExpr(One, LS), LDiff);
4532     }
4533     break;
4534   case ICmpInst::ICMP_EQ:
4535     // n == 0 ? 1+x : n+x  ->  umax(n, 1)+x
4536     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
4537         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
4538       const SCEV *One = getOne(I->getType());
4539       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4540       const SCEV *LA = getSCEV(TrueVal);
4541       const SCEV *RA = getSCEV(FalseVal);
4542       const SCEV *LDiff = getMinusSCEV(LA, One);
4543       const SCEV *RDiff = getMinusSCEV(RA, LS);
4544       if (LDiff == RDiff)
4545         return getAddExpr(getUMaxExpr(One, LS), LDiff);
4546     }
4547     break;
4548   default:
4549     break;
4550   }
4551 
4552   return getUnknown(I);
4553 }
4554 
4555 /// Expand GEP instructions into add and multiply operations. This allows them
4556 /// to be analyzed by regular SCEV code.
4557 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
4558   // Don't attempt to analyze GEPs over unsized objects.
4559   if (!GEP->getSourceElementType()->isSized())
4560     return getUnknown(GEP);
4561 
4562   SmallVector<const SCEV *, 4> IndexExprs;
4563   for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
4564     IndexExprs.push_back(getSCEV(*Index));
4565   return getGEPExpr(GEP, IndexExprs);
4566 }
4567 
4568 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) {
4569   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
4570     return C->getAPInt().countTrailingZeros();
4571 
4572   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
4573     return std::min(GetMinTrailingZeros(T->getOperand()),
4574                     (uint32_t)getTypeSizeInBits(T->getType()));
4575 
4576   if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
4577     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
4578     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
4579                ? getTypeSizeInBits(E->getType())
4580                : OpRes;
4581   }
4582 
4583   if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
4584     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
4585     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
4586                ? getTypeSizeInBits(E->getType())
4587                : OpRes;
4588   }
4589 
4590   if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
4591     // The result is the min of all operands results.
4592     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
4593     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
4594       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
4595     return MinOpRes;
4596   }
4597 
4598   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
4599     // The result is the sum of all operands results.
4600     uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
4601     uint32_t BitWidth = getTypeSizeInBits(M->getType());
4602     for (unsigned i = 1, e = M->getNumOperands();
4603          SumOpRes != BitWidth && i != e; ++i)
4604       SumOpRes =
4605           std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth);
4606     return SumOpRes;
4607   }
4608 
4609   if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
4610     // The result is the min of all operands results.
4611     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
4612     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
4613       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
4614     return MinOpRes;
4615   }
4616 
4617   if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
4618     // The result is the min of all operands results.
4619     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
4620     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
4621       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
4622     return MinOpRes;
4623   }
4624 
4625   if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
4626     // The result is the min of all operands results.
4627     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
4628     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
4629       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
4630     return MinOpRes;
4631   }
4632 
4633   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
4634     // For a SCEVUnknown, ask ValueTracking.
4635     unsigned BitWidth = getTypeSizeInBits(U->getType());
4636     KnownBits Known(BitWidth);
4637     computeKnownBits(U->getValue(), Known, getDataLayout(), 0, &AC,
4638                      nullptr, &DT);
4639     return Known.Zero.countTrailingOnes();
4640   }
4641 
4642   // SCEVUDivExpr
4643   return 0;
4644 }
4645 
4646 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
4647   auto I = MinTrailingZerosCache.find(S);
4648   if (I != MinTrailingZerosCache.end())
4649     return I->second;
4650 
4651   uint32_t Result = GetMinTrailingZerosImpl(S);
4652   auto InsertPair = MinTrailingZerosCache.insert({S, Result});
4653   assert(InsertPair.second && "Should insert a new key");
4654   return InsertPair.first->second;
4655 }
4656 
4657 /// Helper method to assign a range to V from metadata present in the IR.
4658 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
4659   if (Instruction *I = dyn_cast<Instruction>(V))
4660     if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
4661       return getConstantRangeFromMetadata(*MD);
4662 
4663   return None;
4664 }
4665 
4666 /// Determine the range for a particular SCEV.  If SignHint is
4667 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
4668 /// with a "cleaner" unsigned (resp. signed) representation.
4669 ConstantRange
4670 ScalarEvolution::getRange(const SCEV *S,
4671                           ScalarEvolution::RangeSignHint SignHint) {
4672   DenseMap<const SCEV *, ConstantRange> &Cache =
4673       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
4674                                                        : SignedRanges;
4675 
4676   // See if we've computed this range already.
4677   DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
4678   if (I != Cache.end())
4679     return I->second;
4680 
4681   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
4682     return setRange(C, SignHint, ConstantRange(C->getAPInt()));
4683 
4684   unsigned BitWidth = getTypeSizeInBits(S->getType());
4685   ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
4686 
4687   // If the value has known zeros, the maximum value will have those known zeros
4688   // as well.
4689   uint32_t TZ = GetMinTrailingZeros(S);
4690   if (TZ != 0) {
4691     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
4692       ConservativeResult =
4693           ConstantRange(APInt::getMinValue(BitWidth),
4694                         APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
4695     else
4696       ConservativeResult = ConstantRange(
4697           APInt::getSignedMinValue(BitWidth),
4698           APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
4699   }
4700 
4701   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
4702     ConstantRange X = getRange(Add->getOperand(0), SignHint);
4703     for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
4704       X = X.add(getRange(Add->getOperand(i), SignHint));
4705     return setRange(Add, SignHint, ConservativeResult.intersectWith(X));
4706   }
4707 
4708   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
4709     ConstantRange X = getRange(Mul->getOperand(0), SignHint);
4710     for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
4711       X = X.multiply(getRange(Mul->getOperand(i), SignHint));
4712     return setRange(Mul, SignHint, ConservativeResult.intersectWith(X));
4713   }
4714 
4715   if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
4716     ConstantRange X = getRange(SMax->getOperand(0), SignHint);
4717     for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
4718       X = X.smax(getRange(SMax->getOperand(i), SignHint));
4719     return setRange(SMax, SignHint, ConservativeResult.intersectWith(X));
4720   }
4721 
4722   if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
4723     ConstantRange X = getRange(UMax->getOperand(0), SignHint);
4724     for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
4725       X = X.umax(getRange(UMax->getOperand(i), SignHint));
4726     return setRange(UMax, SignHint, ConservativeResult.intersectWith(X));
4727   }
4728 
4729   if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
4730     ConstantRange X = getRange(UDiv->getLHS(), SignHint);
4731     ConstantRange Y = getRange(UDiv->getRHS(), SignHint);
4732     return setRange(UDiv, SignHint,
4733                     ConservativeResult.intersectWith(X.udiv(Y)));
4734   }
4735 
4736   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
4737     ConstantRange X = getRange(ZExt->getOperand(), SignHint);
4738     return setRange(ZExt, SignHint,
4739                     ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
4740   }
4741 
4742   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
4743     ConstantRange X = getRange(SExt->getOperand(), SignHint);
4744     return setRange(SExt, SignHint,
4745                     ConservativeResult.intersectWith(X.signExtend(BitWidth)));
4746   }
4747 
4748   if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
4749     ConstantRange X = getRange(Trunc->getOperand(), SignHint);
4750     return setRange(Trunc, SignHint,
4751                     ConservativeResult.intersectWith(X.truncate(BitWidth)));
4752   }
4753 
4754   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
4755     // If there's no unsigned wrap, the value will never be less than its
4756     // initial value.
4757     if (AddRec->hasNoUnsignedWrap())
4758       if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
4759         if (!C->getValue()->isZero())
4760           ConservativeResult = ConservativeResult.intersectWith(
4761               ConstantRange(C->getAPInt(), APInt(BitWidth, 0)));
4762 
4763     // If there's no signed wrap, and all the operands have the same sign or
4764     // zero, the value won't ever change sign.
4765     if (AddRec->hasNoSignedWrap()) {
4766       bool AllNonNeg = true;
4767       bool AllNonPos = true;
4768       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
4769         if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
4770         if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
4771       }
4772       if (AllNonNeg)
4773         ConservativeResult = ConservativeResult.intersectWith(
4774           ConstantRange(APInt(BitWidth, 0),
4775                         APInt::getSignedMinValue(BitWidth)));
4776       else if (AllNonPos)
4777         ConservativeResult = ConservativeResult.intersectWith(
4778           ConstantRange(APInt::getSignedMinValue(BitWidth),
4779                         APInt(BitWidth, 1)));
4780     }
4781 
4782     // TODO: non-affine addrec
4783     if (AddRec->isAffine()) {
4784       const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
4785       if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
4786           getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
4787         auto RangeFromAffine = getRangeForAffineAR(
4788             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
4789             BitWidth);
4790         if (!RangeFromAffine.isFullSet())
4791           ConservativeResult =
4792               ConservativeResult.intersectWith(RangeFromAffine);
4793 
4794         auto RangeFromFactoring = getRangeViaFactoring(
4795             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
4796             BitWidth);
4797         if (!RangeFromFactoring.isFullSet())
4798           ConservativeResult =
4799               ConservativeResult.intersectWith(RangeFromFactoring);
4800       }
4801     }
4802 
4803     return setRange(AddRec, SignHint, std::move(ConservativeResult));
4804   }
4805 
4806   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
4807     // Check if the IR explicitly contains !range metadata.
4808     Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
4809     if (MDRange.hasValue())
4810       ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue());
4811 
4812     // Split here to avoid paying the compile-time cost of calling both
4813     // computeKnownBits and ComputeNumSignBits.  This restriction can be lifted
4814     // if needed.
4815     const DataLayout &DL = getDataLayout();
4816     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
4817       // For a SCEVUnknown, ask ValueTracking.
4818       KnownBits Known(BitWidth);
4819       computeKnownBits(U->getValue(), Known, DL, 0, &AC, nullptr, &DT);
4820       if (Known.One != ~Known.Zero + 1)
4821         ConservativeResult =
4822             ConservativeResult.intersectWith(ConstantRange(Known.One,
4823                                                            ~Known.Zero + 1));
4824     } else {
4825       assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED &&
4826              "generalize as needed!");
4827       unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
4828       if (NS > 1)
4829         ConservativeResult = ConservativeResult.intersectWith(
4830             ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
4831                           APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1));
4832     }
4833 
4834     return setRange(U, SignHint, std::move(ConservativeResult));
4835   }
4836 
4837   return setRange(S, SignHint, std::move(ConservativeResult));
4838 }
4839 
4840 // Given a StartRange, Step and MaxBECount for an expression compute a range of
4841 // values that the expression can take. Initially, the expression has a value
4842 // from StartRange and then is changed by Step up to MaxBECount times. Signed
4843 // argument defines if we treat Step as signed or unsigned.
4844 static ConstantRange getRangeForAffineARHelper(APInt Step,
4845                                                const ConstantRange &StartRange,
4846                                                const APInt &MaxBECount,
4847                                                unsigned BitWidth, bool Signed) {
4848   // If either Step or MaxBECount is 0, then the expression won't change, and we
4849   // just need to return the initial range.
4850   if (Step == 0 || MaxBECount == 0)
4851     return StartRange;
4852 
4853   // If we don't know anything about the initial value (i.e. StartRange is
4854   // FullRange), then we don't know anything about the final range either.
4855   // Return FullRange.
4856   if (StartRange.isFullSet())
4857     return ConstantRange(BitWidth, /* isFullSet = */ true);
4858 
4859   // If Step is signed and negative, then we use its absolute value, but we also
4860   // note that we're moving in the opposite direction.
4861   bool Descending = Signed && Step.isNegative();
4862 
4863   if (Signed)
4864     // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
4865     // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
4866     // This equations hold true due to the well-defined wrap-around behavior of
4867     // APInt.
4868     Step = Step.abs();
4869 
4870   // Check if Offset is more than full span of BitWidth. If it is, the
4871   // expression is guaranteed to overflow.
4872   if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
4873     return ConstantRange(BitWidth, /* isFullSet = */ true);
4874 
4875   // Offset is by how much the expression can change. Checks above guarantee no
4876   // overflow here.
4877   APInt Offset = Step * MaxBECount;
4878 
4879   // Minimum value of the final range will match the minimal value of StartRange
4880   // if the expression is increasing and will be decreased by Offset otherwise.
4881   // Maximum value of the final range will match the maximal value of StartRange
4882   // if the expression is decreasing and will be increased by Offset otherwise.
4883   APInt StartLower = StartRange.getLower();
4884   APInt StartUpper = StartRange.getUpper() - 1;
4885   APInt MovedBoundary = Descending ? (StartLower - std::move(Offset))
4886                                    : (StartUpper + std::move(Offset));
4887 
4888   // It's possible that the new minimum/maximum value will fall into the initial
4889   // range (due to wrap around). This means that the expression can take any
4890   // value in this bitwidth, and we have to return full range.
4891   if (StartRange.contains(MovedBoundary))
4892     return ConstantRange(BitWidth, /* isFullSet = */ true);
4893 
4894   APInt NewLower =
4895       Descending ? std::move(MovedBoundary) : std::move(StartLower);
4896   APInt NewUpper =
4897       Descending ? std::move(StartUpper) : std::move(MovedBoundary);
4898   NewUpper += 1;
4899 
4900   // If we end up with full range, return a proper full range.
4901   if (NewLower == NewUpper)
4902     return ConstantRange(BitWidth, /* isFullSet = */ true);
4903 
4904   // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
4905   return ConstantRange(std::move(NewLower), std::move(NewUpper));
4906 }
4907 
4908 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
4909                                                    const SCEV *Step,
4910                                                    const SCEV *MaxBECount,
4911                                                    unsigned BitWidth) {
4912   assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&
4913          getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
4914          "Precondition!");
4915 
4916   MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType());
4917   ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
4918   APInt MaxBECountValue = MaxBECountRange.getUnsignedMax();
4919 
4920   // First, consider step signed.
4921   ConstantRange StartSRange = getSignedRange(Start);
4922   ConstantRange StepSRange = getSignedRange(Step);
4923 
4924   // If Step can be both positive and negative, we need to find ranges for the
4925   // maximum absolute step values in both directions and union them.
4926   ConstantRange SR =
4927       getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange,
4928                                 MaxBECountValue, BitWidth, /* Signed = */ true);
4929   SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(),
4930                                               StartSRange, MaxBECountValue,
4931                                               BitWidth, /* Signed = */ true));
4932 
4933   // Next, consider step unsigned.
4934   ConstantRange UR = getRangeForAffineARHelper(
4935       getUnsignedRange(Step).getUnsignedMax(), getUnsignedRange(Start),
4936       MaxBECountValue, BitWidth, /* Signed = */ false);
4937 
4938   // Finally, intersect signed and unsigned ranges.
4939   return SR.intersectWith(UR);
4940 }
4941 
4942 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
4943                                                     const SCEV *Step,
4944                                                     const SCEV *MaxBECount,
4945                                                     unsigned BitWidth) {
4946   //    RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
4947   // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
4948 
4949   struct SelectPattern {
4950     Value *Condition = nullptr;
4951     APInt TrueValue;
4952     APInt FalseValue;
4953 
4954     explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
4955                            const SCEV *S) {
4956       Optional<unsigned> CastOp;
4957       APInt Offset(BitWidth, 0);
4958 
4959       assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&
4960              "Should be!");
4961 
4962       // Peel off a constant offset:
4963       if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
4964         // In the future we could consider being smarter here and handle
4965         // {Start+Step,+,Step} too.
4966         if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
4967           return;
4968 
4969         Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
4970         S = SA->getOperand(1);
4971       }
4972 
4973       // Peel off a cast operation
4974       if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) {
4975         CastOp = SCast->getSCEVType();
4976         S = SCast->getOperand();
4977       }
4978 
4979       using namespace llvm::PatternMatch;
4980 
4981       auto *SU = dyn_cast<SCEVUnknown>(S);
4982       const APInt *TrueVal, *FalseVal;
4983       if (!SU ||
4984           !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
4985                                           m_APInt(FalseVal)))) {
4986         Condition = nullptr;
4987         return;
4988       }
4989 
4990       TrueValue = *TrueVal;
4991       FalseValue = *FalseVal;
4992 
4993       // Re-apply the cast we peeled off earlier
4994       if (CastOp.hasValue())
4995         switch (*CastOp) {
4996         default:
4997           llvm_unreachable("Unknown SCEV cast type!");
4998 
4999         case scTruncate:
5000           TrueValue = TrueValue.trunc(BitWidth);
5001           FalseValue = FalseValue.trunc(BitWidth);
5002           break;
5003         case scZeroExtend:
5004           TrueValue = TrueValue.zext(BitWidth);
5005           FalseValue = FalseValue.zext(BitWidth);
5006           break;
5007         case scSignExtend:
5008           TrueValue = TrueValue.sext(BitWidth);
5009           FalseValue = FalseValue.sext(BitWidth);
5010           break;
5011         }
5012 
5013       // Re-apply the constant offset we peeled off earlier
5014       TrueValue += Offset;
5015       FalseValue += Offset;
5016     }
5017 
5018     bool isRecognized() { return Condition != nullptr; }
5019   };
5020 
5021   SelectPattern StartPattern(*this, BitWidth, Start);
5022   if (!StartPattern.isRecognized())
5023     return ConstantRange(BitWidth, /* isFullSet = */ true);
5024 
5025   SelectPattern StepPattern(*this, BitWidth, Step);
5026   if (!StepPattern.isRecognized())
5027     return ConstantRange(BitWidth, /* isFullSet = */ true);
5028 
5029   if (StartPattern.Condition != StepPattern.Condition) {
5030     // We don't handle this case today; but we could, by considering four
5031     // possibilities below instead of two. I'm not sure if there are cases where
5032     // that will help over what getRange already does, though.
5033     return ConstantRange(BitWidth, /* isFullSet = */ true);
5034   }
5035 
5036   // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
5037   // construct arbitrary general SCEV expressions here.  This function is called
5038   // from deep in the call stack, and calling getSCEV (on a sext instruction,
5039   // say) can end up caching a suboptimal value.
5040 
5041   // FIXME: without the explicit `this` receiver below, MSVC errors out with
5042   // C2352 and C2512 (otherwise it isn't needed).
5043 
5044   const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
5045   const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
5046   const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
5047   const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
5048 
5049   ConstantRange TrueRange =
5050       this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
5051   ConstantRange FalseRange =
5052       this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
5053 
5054   return TrueRange.unionWith(FalseRange);
5055 }
5056 
5057 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
5058   if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
5059   const BinaryOperator *BinOp = cast<BinaryOperator>(V);
5060 
5061   // Return early if there are no flags to propagate to the SCEV.
5062   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5063   if (BinOp->hasNoUnsignedWrap())
5064     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
5065   if (BinOp->hasNoSignedWrap())
5066     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
5067   if (Flags == SCEV::FlagAnyWrap)
5068     return SCEV::FlagAnyWrap;
5069 
5070   return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
5071 }
5072 
5073 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
5074   // Here we check that I is in the header of the innermost loop containing I,
5075   // since we only deal with instructions in the loop header. The actual loop we
5076   // need to check later will come from an add recurrence, but getting that
5077   // requires computing the SCEV of the operands, which can be expensive. This
5078   // check we can do cheaply to rule out some cases early.
5079   Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent());
5080   if (InnermostContainingLoop == nullptr ||
5081       InnermostContainingLoop->getHeader() != I->getParent())
5082     return false;
5083 
5084   // Only proceed if we can prove that I does not yield poison.
5085   if (!programUndefinedIfFullPoison(I))
5086     return false;
5087 
5088   // At this point we know that if I is executed, then it does not wrap
5089   // according to at least one of NSW or NUW. If I is not executed, then we do
5090   // not know if the calculation that I represents would wrap. Multiple
5091   // instructions can map to the same SCEV. If we apply NSW or NUW from I to
5092   // the SCEV, we must guarantee no wrapping for that SCEV also when it is
5093   // derived from other instructions that map to the same SCEV. We cannot make
5094   // that guarantee for cases where I is not executed. So we need to find the
5095   // loop that I is considered in relation to and prove that I is executed for
5096   // every iteration of that loop. That implies that the value that I
5097   // calculates does not wrap anywhere in the loop, so then we can apply the
5098   // flags to the SCEV.
5099   //
5100   // We check isLoopInvariant to disambiguate in case we are adding recurrences
5101   // from different loops, so that we know which loop to prove that I is
5102   // executed in.
5103   for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) {
5104     // I could be an extractvalue from a call to an overflow intrinsic.
5105     // TODO: We can do better here in some cases.
5106     if (!isSCEVable(I->getOperand(OpIndex)->getType()))
5107       return false;
5108     const SCEV *Op = getSCEV(I->getOperand(OpIndex));
5109     if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
5110       bool AllOtherOpsLoopInvariant = true;
5111       for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands();
5112            ++OtherOpIndex) {
5113         if (OtherOpIndex != OpIndex) {
5114           const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex));
5115           if (!isLoopInvariant(OtherOp, AddRec->getLoop())) {
5116             AllOtherOpsLoopInvariant = false;
5117             break;
5118           }
5119         }
5120       }
5121       if (AllOtherOpsLoopInvariant &&
5122           isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop()))
5123         return true;
5124     }
5125   }
5126   return false;
5127 }
5128 
5129 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
5130   // If we know that \c I can never be poison period, then that's enough.
5131   if (isSCEVExprNeverPoison(I))
5132     return true;
5133 
5134   // For an add recurrence specifically, we assume that infinite loops without
5135   // side effects are undefined behavior, and then reason as follows:
5136   //
5137   // If the add recurrence is poison in any iteration, it is poison on all
5138   // future iterations (since incrementing poison yields poison). If the result
5139   // of the add recurrence is fed into the loop latch condition and the loop
5140   // does not contain any throws or exiting blocks other than the latch, we now
5141   // have the ability to "choose" whether the backedge is taken or not (by
5142   // choosing a sufficiently evil value for the poison feeding into the branch)
5143   // for every iteration including and after the one in which \p I first became
5144   // poison.  There are two possibilities (let's call the iteration in which \p
5145   // I first became poison as K):
5146   //
5147   //  1. In the set of iterations including and after K, the loop body executes
5148   //     no side effects.  In this case executing the backege an infinte number
5149   //     of times will yield undefined behavior.
5150   //
5151   //  2. In the set of iterations including and after K, the loop body executes
5152   //     at least one side effect.  In this case, that specific instance of side
5153   //     effect is control dependent on poison, which also yields undefined
5154   //     behavior.
5155 
5156   auto *ExitingBB = L->getExitingBlock();
5157   auto *LatchBB = L->getLoopLatch();
5158   if (!ExitingBB || !LatchBB || ExitingBB != LatchBB)
5159     return false;
5160 
5161   SmallPtrSet<const Instruction *, 16> Pushed;
5162   SmallVector<const Instruction *, 8> PoisonStack;
5163 
5164   // We start by assuming \c I, the post-inc add recurrence, is poison.  Only
5165   // things that are known to be fully poison under that assumption go on the
5166   // PoisonStack.
5167   Pushed.insert(I);
5168   PoisonStack.push_back(I);
5169 
5170   bool LatchControlDependentOnPoison = false;
5171   while (!PoisonStack.empty() && !LatchControlDependentOnPoison) {
5172     const Instruction *Poison = PoisonStack.pop_back_val();
5173 
5174     for (auto *PoisonUser : Poison->users()) {
5175       if (propagatesFullPoison(cast<Instruction>(PoisonUser))) {
5176         if (Pushed.insert(cast<Instruction>(PoisonUser)).second)
5177           PoisonStack.push_back(cast<Instruction>(PoisonUser));
5178       } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) {
5179         assert(BI->isConditional() && "Only possibility!");
5180         if (BI->getParent() == LatchBB) {
5181           LatchControlDependentOnPoison = true;
5182           break;
5183         }
5184       }
5185     }
5186   }
5187 
5188   return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L);
5189 }
5190 
5191 ScalarEvolution::LoopProperties
5192 ScalarEvolution::getLoopProperties(const Loop *L) {
5193   typedef ScalarEvolution::LoopProperties LoopProperties;
5194 
5195   auto Itr = LoopPropertiesCache.find(L);
5196   if (Itr == LoopPropertiesCache.end()) {
5197     auto HasSideEffects = [](Instruction *I) {
5198       if (auto *SI = dyn_cast<StoreInst>(I))
5199         return !SI->isSimple();
5200 
5201       return I->mayHaveSideEffects();
5202     };
5203 
5204     LoopProperties LP = {/* HasNoAbnormalExits */ true,
5205                          /*HasNoSideEffects*/ true};
5206 
5207     for (auto *BB : L->getBlocks())
5208       for (auto &I : *BB) {
5209         if (!isGuaranteedToTransferExecutionToSuccessor(&I))
5210           LP.HasNoAbnormalExits = false;
5211         if (HasSideEffects(&I))
5212           LP.HasNoSideEffects = false;
5213         if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
5214           break; // We're already as pessimistic as we can get.
5215       }
5216 
5217     auto InsertPair = LoopPropertiesCache.insert({L, LP});
5218     assert(InsertPair.second && "We just checked!");
5219     Itr = InsertPair.first;
5220   }
5221 
5222   return Itr->second;
5223 }
5224 
5225 const SCEV *ScalarEvolution::createSCEV(Value *V) {
5226   if (!isSCEVable(V->getType()))
5227     return getUnknown(V);
5228 
5229   if (Instruction *I = dyn_cast<Instruction>(V)) {
5230     // Don't attempt to analyze instructions in blocks that aren't
5231     // reachable. Such instructions don't matter, and they aren't required
5232     // to obey basic rules for definitions dominating uses which this
5233     // analysis depends on.
5234     if (!DT.isReachableFromEntry(I->getParent()))
5235       return getUnknown(V);
5236   } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
5237     return getConstant(CI);
5238   else if (isa<ConstantPointerNull>(V))
5239     return getZero(V->getType());
5240   else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
5241     return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee());
5242   else if (!isa<ConstantExpr>(V))
5243     return getUnknown(V);
5244 
5245   Operator *U = cast<Operator>(V);
5246   if (auto BO = MatchBinaryOp(U, DT)) {
5247     switch (BO->Opcode) {
5248     case Instruction::Add: {
5249       // The simple thing to do would be to just call getSCEV on both operands
5250       // and call getAddExpr with the result. However if we're looking at a
5251       // bunch of things all added together, this can be quite inefficient,
5252       // because it leads to N-1 getAddExpr calls for N ultimate operands.
5253       // Instead, gather up all the operands and make a single getAddExpr call.
5254       // LLVM IR canonical form means we need only traverse the left operands.
5255       SmallVector<const SCEV *, 4> AddOps;
5256       do {
5257         if (BO->Op) {
5258           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
5259             AddOps.push_back(OpSCEV);
5260             break;
5261           }
5262 
5263           // If a NUW or NSW flag can be applied to the SCEV for this
5264           // addition, then compute the SCEV for this addition by itself
5265           // with a separate call to getAddExpr. We need to do that
5266           // instead of pushing the operands of the addition onto AddOps,
5267           // since the flags are only known to apply to this particular
5268           // addition - they may not apply to other additions that can be
5269           // formed with operands from AddOps.
5270           const SCEV *RHS = getSCEV(BO->RHS);
5271           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
5272           if (Flags != SCEV::FlagAnyWrap) {
5273             const SCEV *LHS = getSCEV(BO->LHS);
5274             if (BO->Opcode == Instruction::Sub)
5275               AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
5276             else
5277               AddOps.push_back(getAddExpr(LHS, RHS, Flags));
5278             break;
5279           }
5280         }
5281 
5282         if (BO->Opcode == Instruction::Sub)
5283           AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
5284         else
5285           AddOps.push_back(getSCEV(BO->RHS));
5286 
5287         auto NewBO = MatchBinaryOp(BO->LHS, DT);
5288         if (!NewBO || (NewBO->Opcode != Instruction::Add &&
5289                        NewBO->Opcode != Instruction::Sub)) {
5290           AddOps.push_back(getSCEV(BO->LHS));
5291           break;
5292         }
5293         BO = NewBO;
5294       } while (true);
5295 
5296       return getAddExpr(AddOps);
5297     }
5298 
5299     case Instruction::Mul: {
5300       SmallVector<const SCEV *, 4> MulOps;
5301       do {
5302         if (BO->Op) {
5303           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
5304             MulOps.push_back(OpSCEV);
5305             break;
5306           }
5307 
5308           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
5309           if (Flags != SCEV::FlagAnyWrap) {
5310             MulOps.push_back(
5311                 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags));
5312             break;
5313           }
5314         }
5315 
5316         MulOps.push_back(getSCEV(BO->RHS));
5317         auto NewBO = MatchBinaryOp(BO->LHS, DT);
5318         if (!NewBO || NewBO->Opcode != Instruction::Mul) {
5319           MulOps.push_back(getSCEV(BO->LHS));
5320           break;
5321         }
5322         BO = NewBO;
5323       } while (true);
5324 
5325       return getMulExpr(MulOps);
5326     }
5327     case Instruction::UDiv:
5328       return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
5329     case Instruction::Sub: {
5330       SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5331       if (BO->Op)
5332         Flags = getNoWrapFlagsFromUB(BO->Op);
5333       return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags);
5334     }
5335     case Instruction::And:
5336       // For an expression like x&255 that merely masks off the high bits,
5337       // use zext(trunc(x)) as the SCEV expression.
5338       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5339         if (CI->isNullValue())
5340           return getSCEV(BO->RHS);
5341         if (CI->isAllOnesValue())
5342           return getSCEV(BO->LHS);
5343         const APInt &A = CI->getValue();
5344 
5345         // Instcombine's ShrinkDemandedConstant may strip bits out of
5346         // constants, obscuring what would otherwise be a low-bits mask.
5347         // Use computeKnownBits to compute what ShrinkDemandedConstant
5348         // knew about to reconstruct a low-bits mask value.
5349         unsigned LZ = A.countLeadingZeros();
5350         unsigned TZ = A.countTrailingZeros();
5351         unsigned BitWidth = A.getBitWidth();
5352         KnownBits Known(BitWidth);
5353         computeKnownBits(BO->LHS, Known, getDataLayout(),
5354                          0, &AC, nullptr, &DT);
5355 
5356         APInt EffectiveMask =
5357             APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
5358         if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
5359           const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
5360           const SCEV *LHS = getSCEV(BO->LHS);
5361           const SCEV *ShiftedLHS = nullptr;
5362           if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
5363             if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
5364               // For an expression like (x * 8) & 8, simplify the multiply.
5365               unsigned MulZeros = OpC->getAPInt().countTrailingZeros();
5366               unsigned GCD = std::min(MulZeros, TZ);
5367               APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
5368               SmallVector<const SCEV*, 4> MulOps;
5369               MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD)));
5370               MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end());
5371               auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
5372               ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
5373             }
5374           }
5375           if (!ShiftedLHS)
5376             ShiftedLHS = getUDivExpr(LHS, MulCount);
5377           return getMulExpr(
5378               getZeroExtendExpr(
5379                   getTruncateExpr(ShiftedLHS,
5380                       IntegerType::get(getContext(), BitWidth - LZ - TZ)),
5381                   BO->LHS->getType()),
5382               MulCount);
5383         }
5384       }
5385       break;
5386 
5387     case Instruction::Or:
5388       // If the RHS of the Or is a constant, we may have something like:
5389       // X*4+1 which got turned into X*4|1.  Handle this as an Add so loop
5390       // optimizations will transparently handle this case.
5391       //
5392       // In order for this transformation to be safe, the LHS must be of the
5393       // form X*(2^n) and the Or constant must be less than 2^n.
5394       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5395         const SCEV *LHS = getSCEV(BO->LHS);
5396         const APInt &CIVal = CI->getValue();
5397         if (GetMinTrailingZeros(LHS) >=
5398             (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
5399           // Build a plain add SCEV.
5400           const SCEV *S = getAddExpr(LHS, getSCEV(CI));
5401           // If the LHS of the add was an addrec and it has no-wrap flags,
5402           // transfer the no-wrap flags, since an or won't introduce a wrap.
5403           if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
5404             const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
5405             const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags(
5406                 OldAR->getNoWrapFlags());
5407           }
5408           return S;
5409         }
5410       }
5411       break;
5412 
5413     case Instruction::Xor:
5414       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5415         // If the RHS of xor is -1, then this is a not operation.
5416         if (CI->isAllOnesValue())
5417           return getNotSCEV(getSCEV(BO->LHS));
5418 
5419         // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
5420         // This is a variant of the check for xor with -1, and it handles
5421         // the case where instcombine has trimmed non-demanded bits out
5422         // of an xor with -1.
5423         if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
5424           if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
5425             if (LBO->getOpcode() == Instruction::And &&
5426                 LCI->getValue() == CI->getValue())
5427               if (const SCEVZeroExtendExpr *Z =
5428                       dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
5429                 Type *UTy = BO->LHS->getType();
5430                 const SCEV *Z0 = Z->getOperand();
5431                 Type *Z0Ty = Z0->getType();
5432                 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
5433 
5434                 // If C is a low-bits mask, the zero extend is serving to
5435                 // mask off the high bits. Complement the operand and
5436                 // re-apply the zext.
5437                 if (CI->getValue().isMask(Z0TySize))
5438                   return getZeroExtendExpr(getNotSCEV(Z0), UTy);
5439 
5440                 // If C is a single bit, it may be in the sign-bit position
5441                 // before the zero-extend. In this case, represent the xor
5442                 // using an add, which is equivalent, and re-apply the zext.
5443                 APInt Trunc = CI->getValue().trunc(Z0TySize);
5444                 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
5445                     Trunc.isSignMask())
5446                   return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
5447                                            UTy);
5448               }
5449       }
5450       break;
5451 
5452   case Instruction::Shl:
5453     // Turn shift left of a constant amount into a multiply.
5454     if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
5455       uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
5456 
5457       // If the shift count is not less than the bitwidth, the result of
5458       // the shift is undefined. Don't try to analyze it, because the
5459       // resolution chosen here may differ from the resolution chosen in
5460       // other parts of the compiler.
5461       if (SA->getValue().uge(BitWidth))
5462         break;
5463 
5464       // It is currently not resolved how to interpret NSW for left
5465       // shift by BitWidth - 1, so we avoid applying flags in that
5466       // case. Remove this check (or this comment) once the situation
5467       // is resolved. See
5468       // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html
5469       // and http://reviews.llvm.org/D8890 .
5470       auto Flags = SCEV::FlagAnyWrap;
5471       if (BO->Op && SA->getValue().ult(BitWidth - 1))
5472         Flags = getNoWrapFlagsFromUB(BO->Op);
5473 
5474       Constant *X = ConstantInt::get(getContext(),
5475         APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
5476       return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags);
5477     }
5478     break;
5479 
5480     case Instruction::AShr:
5481       // AShr X, C, where C is a constant.
5482       ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
5483       if (!CI)
5484         break;
5485 
5486       Type *OuterTy = BO->LHS->getType();
5487       uint64_t BitWidth = getTypeSizeInBits(OuterTy);
5488       // If the shift count is not less than the bitwidth, the result of
5489       // the shift is undefined. Don't try to analyze it, because the
5490       // resolution chosen here may differ from the resolution chosen in
5491       // other parts of the compiler.
5492       if (CI->getValue().uge(BitWidth))
5493         break;
5494 
5495       if (CI->isNullValue())
5496         return getSCEV(BO->LHS); // shift by zero --> noop
5497 
5498       uint64_t AShrAmt = CI->getZExtValue();
5499       Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
5500 
5501       Operator *L = dyn_cast<Operator>(BO->LHS);
5502       if (L && L->getOpcode() == Instruction::Shl) {
5503         // X = Shl A, n
5504         // Y = AShr X, m
5505         // Both n and m are constant.
5506 
5507         const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
5508         if (L->getOperand(1) == BO->RHS)
5509           // For a two-shift sext-inreg, i.e. n = m,
5510           // use sext(trunc(x)) as the SCEV expression.
5511           return getSignExtendExpr(
5512               getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy);
5513 
5514         ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
5515         if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) {
5516           uint64_t ShlAmt = ShlAmtCI->getZExtValue();
5517           if (ShlAmt > AShrAmt) {
5518             // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
5519             // expression. We already checked that ShlAmt < BitWidth, so
5520             // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
5521             // ShlAmt - AShrAmt < Amt.
5522             APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
5523                                             ShlAmt - AShrAmt);
5524             return getSignExtendExpr(
5525                 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy),
5526                 getConstant(Mul)), OuterTy);
5527           }
5528         }
5529       }
5530       break;
5531     }
5532   }
5533 
5534   switch (U->getOpcode()) {
5535   case Instruction::Trunc:
5536     return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
5537 
5538   case Instruction::ZExt:
5539     return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
5540 
5541   case Instruction::SExt:
5542     return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
5543 
5544   case Instruction::BitCast:
5545     // BitCasts are no-op casts so we just eliminate the cast.
5546     if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
5547       return getSCEV(U->getOperand(0));
5548     break;
5549 
5550   // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
5551   // lead to pointer expressions which cannot safely be expanded to GEPs,
5552   // because ScalarEvolution doesn't respect the GEP aliasing rules when
5553   // simplifying integer expressions.
5554 
5555   case Instruction::GetElementPtr:
5556     return createNodeForGEP(cast<GEPOperator>(U));
5557 
5558   case Instruction::PHI:
5559     return createNodeForPHI(cast<PHINode>(U));
5560 
5561   case Instruction::Select:
5562     // U can also be a select constant expr, which let fall through.  Since
5563     // createNodeForSelect only works for a condition that is an `ICmpInst`, and
5564     // constant expressions cannot have instructions as operands, we'd have
5565     // returned getUnknown for a select constant expressions anyway.
5566     if (isa<Instruction>(U))
5567       return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0),
5568                                       U->getOperand(1), U->getOperand(2));
5569     break;
5570 
5571   case Instruction::Call:
5572   case Instruction::Invoke:
5573     if (Value *RV = CallSite(U).getReturnedArgOperand())
5574       return getSCEV(RV);
5575     break;
5576   }
5577 
5578   return getUnknown(V);
5579 }
5580 
5581 
5582 
5583 //===----------------------------------------------------------------------===//
5584 //                   Iteration Count Computation Code
5585 //
5586 
5587 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
5588   if (!ExitCount)
5589     return 0;
5590 
5591   ConstantInt *ExitConst = ExitCount->getValue();
5592 
5593   // Guard against huge trip counts.
5594   if (ExitConst->getValue().getActiveBits() > 32)
5595     return 0;
5596 
5597   // In case of integer overflow, this returns 0, which is correct.
5598   return ((unsigned)ExitConst->getZExtValue()) + 1;
5599 }
5600 
5601 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) {
5602   if (BasicBlock *ExitingBB = L->getExitingBlock())
5603     return getSmallConstantTripCount(L, ExitingBB);
5604 
5605   // No trip count information for multiple exits.
5606   return 0;
5607 }
5608 
5609 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L,
5610                                                     BasicBlock *ExitingBlock) {
5611   assert(ExitingBlock && "Must pass a non-null exiting block!");
5612   assert(L->isLoopExiting(ExitingBlock) &&
5613          "Exiting block must actually branch out of the loop!");
5614   const SCEVConstant *ExitCount =
5615       dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
5616   return getConstantTripCount(ExitCount);
5617 }
5618 
5619 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) {
5620   const auto *MaxExitCount =
5621       dyn_cast<SCEVConstant>(getMaxBackedgeTakenCount(L));
5622   return getConstantTripCount(MaxExitCount);
5623 }
5624 
5625 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) {
5626   if (BasicBlock *ExitingBB = L->getExitingBlock())
5627     return getSmallConstantTripMultiple(L, ExitingBB);
5628 
5629   // No trip multiple information for multiple exits.
5630   return 0;
5631 }
5632 
5633 /// Returns the largest constant divisor of the trip count of this loop as a
5634 /// normal unsigned value, if possible. This means that the actual trip count is
5635 /// always a multiple of the returned value (don't forget the trip count could
5636 /// very well be zero as well!).
5637 ///
5638 /// Returns 1 if the trip count is unknown or not guaranteed to be the
5639 /// multiple of a constant (which is also the case if the trip count is simply
5640 /// constant, use getSmallConstantTripCount for that case), Will also return 1
5641 /// if the trip count is very large (>= 2^32).
5642 ///
5643 /// As explained in the comments for getSmallConstantTripCount, this assumes
5644 /// that control exits the loop via ExitingBlock.
5645 unsigned
5646 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
5647                                               BasicBlock *ExitingBlock) {
5648   assert(ExitingBlock && "Must pass a non-null exiting block!");
5649   assert(L->isLoopExiting(ExitingBlock) &&
5650          "Exiting block must actually branch out of the loop!");
5651   const SCEV *ExitCount = getExitCount(L, ExitingBlock);
5652   if (ExitCount == getCouldNotCompute())
5653     return 1;
5654 
5655   // Get the trip count from the BE count by adding 1.
5656   const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType()));
5657 
5658   const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr);
5659   if (!TC)
5660     // Attempt to factor more general cases. Returns the greatest power of
5661     // two divisor. If overflow happens, the trip count expression is still
5662     // divisible by the greatest power of 2 divisor returned.
5663     return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr));
5664 
5665   ConstantInt *Result = TC->getValue();
5666 
5667   // Guard against huge trip counts (this requires checking
5668   // for zero to handle the case where the trip count == -1 and the
5669   // addition wraps).
5670   if (!Result || Result->getValue().getActiveBits() > 32 ||
5671       Result->getValue().getActiveBits() == 0)
5672     return 1;
5673 
5674   return (unsigned)Result->getZExtValue();
5675 }
5676 
5677 /// Get the expression for the number of loop iterations for which this loop is
5678 /// guaranteed not to exit via ExitingBlock. Otherwise return
5679 /// SCEVCouldNotCompute.
5680 const SCEV *ScalarEvolution::getExitCount(const Loop *L,
5681                                           BasicBlock *ExitingBlock) {
5682   return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
5683 }
5684 
5685 const SCEV *
5686 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
5687                                                  SCEVUnionPredicate &Preds) {
5688   return getPredicatedBackedgeTakenInfo(L).getExact(this, &Preds);
5689 }
5690 
5691 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
5692   return getBackedgeTakenInfo(L).getExact(this);
5693 }
5694 
5695 /// Similar to getBackedgeTakenCount, except return the least SCEV value that is
5696 /// known never to be less than the actual backedge taken count.
5697 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
5698   return getBackedgeTakenInfo(L).getMax(this);
5699 }
5700 
5701 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) {
5702   return getBackedgeTakenInfo(L).isMaxOrZero(this);
5703 }
5704 
5705 /// Push PHI nodes in the header of the given loop onto the given Worklist.
5706 static void
5707 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
5708   BasicBlock *Header = L->getHeader();
5709 
5710   // Push all Loop-header PHIs onto the Worklist stack.
5711   for (BasicBlock::iterator I = Header->begin();
5712        PHINode *PN = dyn_cast<PHINode>(I); ++I)
5713     Worklist.push_back(PN);
5714 }
5715 
5716 const ScalarEvolution::BackedgeTakenInfo &
5717 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
5718   auto &BTI = getBackedgeTakenInfo(L);
5719   if (BTI.hasFullInfo())
5720     return BTI;
5721 
5722   auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
5723 
5724   if (!Pair.second)
5725     return Pair.first->second;
5726 
5727   BackedgeTakenInfo Result =
5728       computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
5729 
5730   return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
5731 }
5732 
5733 const ScalarEvolution::BackedgeTakenInfo &
5734 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
5735   // Initially insert an invalid entry for this loop. If the insertion
5736   // succeeds, proceed to actually compute a backedge-taken count and
5737   // update the value. The temporary CouldNotCompute value tells SCEV
5738   // code elsewhere that it shouldn't attempt to request a new
5739   // backedge-taken count, which could result in infinite recursion.
5740   std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
5741       BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
5742   if (!Pair.second)
5743     return Pair.first->second;
5744 
5745   // computeBackedgeTakenCount may allocate memory for its result. Inserting it
5746   // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
5747   // must be cleared in this scope.
5748   BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
5749 
5750   if (Result.getExact(this) != getCouldNotCompute()) {
5751     assert(isLoopInvariant(Result.getExact(this), L) &&
5752            isLoopInvariant(Result.getMax(this), L) &&
5753            "Computed backedge-taken count isn't loop invariant for loop!");
5754     ++NumTripCountsComputed;
5755   }
5756   else if (Result.getMax(this) == getCouldNotCompute() &&
5757            isa<PHINode>(L->getHeader()->begin())) {
5758     // Only count loops that have phi nodes as not being computable.
5759     ++NumTripCountsNotComputed;
5760   }
5761 
5762   // Now that we know more about the trip count for this loop, forget any
5763   // existing SCEV values for PHI nodes in this loop since they are only
5764   // conservative estimates made without the benefit of trip count
5765   // information. This is similar to the code in forgetLoop, except that
5766   // it handles SCEVUnknown PHI nodes specially.
5767   if (Result.hasAnyInfo()) {
5768     SmallVector<Instruction *, 16> Worklist;
5769     PushLoopPHIs(L, Worklist);
5770 
5771     SmallPtrSet<Instruction *, 8> Visited;
5772     while (!Worklist.empty()) {
5773       Instruction *I = Worklist.pop_back_val();
5774       if (!Visited.insert(I).second)
5775         continue;
5776 
5777       ValueExprMapType::iterator It =
5778         ValueExprMap.find_as(static_cast<Value *>(I));
5779       if (It != ValueExprMap.end()) {
5780         const SCEV *Old = It->second;
5781 
5782         // SCEVUnknown for a PHI either means that it has an unrecognized
5783         // structure, or it's a PHI that's in the progress of being computed
5784         // by createNodeForPHI.  In the former case, additional loop trip
5785         // count information isn't going to change anything. In the later
5786         // case, createNodeForPHI will perform the necessary updates on its
5787         // own when it gets to that point.
5788         if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
5789           eraseValueFromMap(It->first);
5790           forgetMemoizedResults(Old);
5791         }
5792         if (PHINode *PN = dyn_cast<PHINode>(I))
5793           ConstantEvolutionLoopExitValue.erase(PN);
5794       }
5795 
5796       PushDefUseChildren(I, Worklist);
5797     }
5798   }
5799 
5800   // Re-lookup the insert position, since the call to
5801   // computeBackedgeTakenCount above could result in a
5802   // recusive call to getBackedgeTakenInfo (on a different
5803   // loop), which would invalidate the iterator computed
5804   // earlier.
5805   return BackedgeTakenCounts.find(L)->second = std::move(Result);
5806 }
5807 
5808 void ScalarEvolution::forgetLoop(const Loop *L) {
5809   // Drop any stored trip count value.
5810   auto RemoveLoopFromBackedgeMap =
5811       [L](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
5812         auto BTCPos = Map.find(L);
5813         if (BTCPos != Map.end()) {
5814           BTCPos->second.clear();
5815           Map.erase(BTCPos);
5816         }
5817       };
5818 
5819   RemoveLoopFromBackedgeMap(BackedgeTakenCounts);
5820   RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts);
5821 
5822   // Drop information about expressions based on loop-header PHIs.
5823   SmallVector<Instruction *, 16> Worklist;
5824   PushLoopPHIs(L, Worklist);
5825 
5826   SmallPtrSet<Instruction *, 8> Visited;
5827   while (!Worklist.empty()) {
5828     Instruction *I = Worklist.pop_back_val();
5829     if (!Visited.insert(I).second)
5830       continue;
5831 
5832     ValueExprMapType::iterator It =
5833       ValueExprMap.find_as(static_cast<Value *>(I));
5834     if (It != ValueExprMap.end()) {
5835       eraseValueFromMap(It->first);
5836       forgetMemoizedResults(It->second);
5837       if (PHINode *PN = dyn_cast<PHINode>(I))
5838         ConstantEvolutionLoopExitValue.erase(PN);
5839     }
5840 
5841     PushDefUseChildren(I, Worklist);
5842   }
5843 
5844   // Forget all contained loops too, to avoid dangling entries in the
5845   // ValuesAtScopes map.
5846   for (Loop *I : *L)
5847     forgetLoop(I);
5848 
5849   LoopPropertiesCache.erase(L);
5850 }
5851 
5852 void ScalarEvolution::forgetValue(Value *V) {
5853   Instruction *I = dyn_cast<Instruction>(V);
5854   if (!I) return;
5855 
5856   // Drop information about expressions based on loop-header PHIs.
5857   SmallVector<Instruction *, 16> Worklist;
5858   Worklist.push_back(I);
5859 
5860   SmallPtrSet<Instruction *, 8> Visited;
5861   while (!Worklist.empty()) {
5862     I = Worklist.pop_back_val();
5863     if (!Visited.insert(I).second)
5864       continue;
5865 
5866     ValueExprMapType::iterator It =
5867       ValueExprMap.find_as(static_cast<Value *>(I));
5868     if (It != ValueExprMap.end()) {
5869       eraseValueFromMap(It->first);
5870       forgetMemoizedResults(It->second);
5871       if (PHINode *PN = dyn_cast<PHINode>(I))
5872         ConstantEvolutionLoopExitValue.erase(PN);
5873     }
5874 
5875     PushDefUseChildren(I, Worklist);
5876   }
5877 }
5878 
5879 /// Get the exact loop backedge taken count considering all loop exits. A
5880 /// computable result can only be returned for loops with a single exit.
5881 /// Returning the minimum taken count among all exits is incorrect because one
5882 /// of the loop's exit limit's may have been skipped. howFarToZero assumes that
5883 /// the limit of each loop test is never skipped. This is a valid assumption as
5884 /// long as the loop exits via that test. For precise results, it is the
5885 /// caller's responsibility to specify the relevant loop exit using
5886 /// getExact(ExitingBlock, SE).
5887 const SCEV *
5888 ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE,
5889                                              SCEVUnionPredicate *Preds) const {
5890   // If any exits were not computable, the loop is not computable.
5891   if (!isComplete() || ExitNotTaken.empty())
5892     return SE->getCouldNotCompute();
5893 
5894   const SCEV *BECount = nullptr;
5895   for (auto &ENT : ExitNotTaken) {
5896     assert(ENT.ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV");
5897 
5898     if (!BECount)
5899       BECount = ENT.ExactNotTaken;
5900     else if (BECount != ENT.ExactNotTaken)
5901       return SE->getCouldNotCompute();
5902     if (Preds && !ENT.hasAlwaysTruePredicate())
5903       Preds->add(ENT.Predicate.get());
5904 
5905     assert((Preds || ENT.hasAlwaysTruePredicate()) &&
5906            "Predicate should be always true!");
5907   }
5908 
5909   assert(BECount && "Invalid not taken count for loop exit");
5910   return BECount;
5911 }
5912 
5913 /// Get the exact not taken count for this loop exit.
5914 const SCEV *
5915 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock,
5916                                              ScalarEvolution *SE) const {
5917   for (auto &ENT : ExitNotTaken)
5918     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
5919       return ENT.ExactNotTaken;
5920 
5921   return SE->getCouldNotCompute();
5922 }
5923 
5924 /// getMax - Get the max backedge taken count for the loop.
5925 const SCEV *
5926 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const {
5927   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
5928     return !ENT.hasAlwaysTruePredicate();
5929   };
5930 
5931   if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax())
5932     return SE->getCouldNotCompute();
5933 
5934   return getMax();
5935 }
5936 
5937 bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const {
5938   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
5939     return !ENT.hasAlwaysTruePredicate();
5940   };
5941   return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
5942 }
5943 
5944 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S,
5945                                                     ScalarEvolution *SE) const {
5946   if (getMax() && getMax() != SE->getCouldNotCompute() &&
5947       SE->hasOperand(getMax(), S))
5948     return true;
5949 
5950   for (auto &ENT : ExitNotTaken)
5951     if (ENT.ExactNotTaken != SE->getCouldNotCompute() &&
5952         SE->hasOperand(ENT.ExactNotTaken, S))
5953       return true;
5954 
5955   return false;
5956 }
5957 
5958 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
5959 /// computable exit into a persistent ExitNotTakenInfo array.
5960 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
5961     SmallVectorImpl<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo>
5962         &&ExitCounts,
5963     bool Complete, const SCEV *MaxCount, bool MaxOrZero)
5964     : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) {
5965   typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo;
5966   ExitNotTaken.reserve(ExitCounts.size());
5967   std::transform(
5968       ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken),
5969       [&](const EdgeExitInfo &EEI) {
5970         BasicBlock *ExitBB = EEI.first;
5971         const ExitLimit &EL = EEI.second;
5972         if (EL.Predicates.empty())
5973           return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr);
5974 
5975         std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate);
5976         for (auto *Pred : EL.Predicates)
5977           Predicate->add(Pred);
5978 
5979         return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, std::move(Predicate));
5980       });
5981 }
5982 
5983 /// Invalidate this result and free the ExitNotTakenInfo array.
5984 void ScalarEvolution::BackedgeTakenInfo::clear() {
5985   ExitNotTaken.clear();
5986 }
5987 
5988 /// Compute the number of times the backedge of the specified loop will execute.
5989 ScalarEvolution::BackedgeTakenInfo
5990 ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
5991                                            bool AllowPredicates) {
5992   SmallVector<BasicBlock *, 8> ExitingBlocks;
5993   L->getExitingBlocks(ExitingBlocks);
5994 
5995   typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo;
5996 
5997   SmallVector<EdgeExitInfo, 4> ExitCounts;
5998   bool CouldComputeBECount = true;
5999   BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
6000   const SCEV *MustExitMaxBECount = nullptr;
6001   const SCEV *MayExitMaxBECount = nullptr;
6002   bool MustExitMaxOrZero = false;
6003 
6004   // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
6005   // and compute maxBECount.
6006   // Do a union of all the predicates here.
6007   for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
6008     BasicBlock *ExitBB = ExitingBlocks[i];
6009     ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
6010 
6011     assert((AllowPredicates || EL.Predicates.empty()) &&
6012            "Predicated exit limit when predicates are not allowed!");
6013 
6014     // 1. For each exit that can be computed, add an entry to ExitCounts.
6015     // CouldComputeBECount is true only if all exits can be computed.
6016     if (EL.ExactNotTaken == getCouldNotCompute())
6017       // We couldn't compute an exact value for this exit, so
6018       // we won't be able to compute an exact value for the loop.
6019       CouldComputeBECount = false;
6020     else
6021       ExitCounts.emplace_back(ExitBB, EL);
6022 
6023     // 2. Derive the loop's MaxBECount from each exit's max number of
6024     // non-exiting iterations. Partition the loop exits into two kinds:
6025     // LoopMustExits and LoopMayExits.
6026     //
6027     // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
6028     // is a LoopMayExit.  If any computable LoopMustExit is found, then
6029     // MaxBECount is the minimum EL.MaxNotTaken of computable
6030     // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
6031     // EL.MaxNotTaken, where CouldNotCompute is considered greater than any
6032     // computable EL.MaxNotTaken.
6033     if (EL.MaxNotTaken != getCouldNotCompute() && Latch &&
6034         DT.dominates(ExitBB, Latch)) {
6035       if (!MustExitMaxBECount) {
6036         MustExitMaxBECount = EL.MaxNotTaken;
6037         MustExitMaxOrZero = EL.MaxOrZero;
6038       } else {
6039         MustExitMaxBECount =
6040             getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken);
6041       }
6042     } else if (MayExitMaxBECount != getCouldNotCompute()) {
6043       if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute())
6044         MayExitMaxBECount = EL.MaxNotTaken;
6045       else {
6046         MayExitMaxBECount =
6047             getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken);
6048       }
6049     }
6050   }
6051   const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
6052     (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
6053   // The loop backedge will be taken the maximum or zero times if there's
6054   // a single exit that must be taken the maximum or zero times.
6055   bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
6056   return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
6057                            MaxBECount, MaxOrZero);
6058 }
6059 
6060 ScalarEvolution::ExitLimit
6061 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
6062                                   bool AllowPredicates) {
6063 
6064   // Okay, we've chosen an exiting block.  See what condition causes us to exit
6065   // at this block and remember the exit block and whether all other targets
6066   // lead to the loop header.
6067   bool MustExecuteLoopHeader = true;
6068   BasicBlock *Exit = nullptr;
6069   for (auto *SBB : successors(ExitingBlock))
6070     if (!L->contains(SBB)) {
6071       if (Exit) // Multiple exit successors.
6072         return getCouldNotCompute();
6073       Exit = SBB;
6074     } else if (SBB != L->getHeader()) {
6075       MustExecuteLoopHeader = false;
6076     }
6077 
6078   // At this point, we know we have a conditional branch that determines whether
6079   // the loop is exited.  However, we don't know if the branch is executed each
6080   // time through the loop.  If not, then the execution count of the branch will
6081   // not be equal to the trip count of the loop.
6082   //
6083   // Currently we check for this by checking to see if the Exit branch goes to
6084   // the loop header.  If so, we know it will always execute the same number of
6085   // times as the loop.  We also handle the case where the exit block *is* the
6086   // loop header.  This is common for un-rotated loops.
6087   //
6088   // If both of those tests fail, walk up the unique predecessor chain to the
6089   // header, stopping if there is an edge that doesn't exit the loop. If the
6090   // header is reached, the execution count of the branch will be equal to the
6091   // trip count of the loop.
6092   //
6093   //  More extensive analysis could be done to handle more cases here.
6094   //
6095   if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) {
6096     // The simple checks failed, try climbing the unique predecessor chain
6097     // up to the header.
6098     bool Ok = false;
6099     for (BasicBlock *BB = ExitingBlock; BB; ) {
6100       BasicBlock *Pred = BB->getUniquePredecessor();
6101       if (!Pred)
6102         return getCouldNotCompute();
6103       TerminatorInst *PredTerm = Pred->getTerminator();
6104       for (const BasicBlock *PredSucc : PredTerm->successors()) {
6105         if (PredSucc == BB)
6106           continue;
6107         // If the predecessor has a successor that isn't BB and isn't
6108         // outside the loop, assume the worst.
6109         if (L->contains(PredSucc))
6110           return getCouldNotCompute();
6111       }
6112       if (Pred == L->getHeader()) {
6113         Ok = true;
6114         break;
6115       }
6116       BB = Pred;
6117     }
6118     if (!Ok)
6119       return getCouldNotCompute();
6120   }
6121 
6122   bool IsOnlyExit = (L->getExitingBlock() != nullptr);
6123   TerminatorInst *Term = ExitingBlock->getTerminator();
6124   if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
6125     assert(BI->isConditional() && "If unconditional, it can't be in loop!");
6126     // Proceed to the next level to examine the exit condition expression.
6127     return computeExitLimitFromCond(
6128         L, BI->getCondition(), BI->getSuccessor(0), BI->getSuccessor(1),
6129         /*ControlsExit=*/IsOnlyExit, AllowPredicates);
6130   }
6131 
6132   if (SwitchInst *SI = dyn_cast<SwitchInst>(Term))
6133     return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
6134                                                 /*ControlsExit=*/IsOnlyExit);
6135 
6136   return getCouldNotCompute();
6137 }
6138 
6139 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond(
6140     const Loop *L, Value *ExitCond, BasicBlock *TBB, BasicBlock *FBB,
6141     bool ControlsExit, bool AllowPredicates) {
6142   ScalarEvolution::ExitLimitCacheTy Cache(L, TBB, FBB, AllowPredicates);
6143   return computeExitLimitFromCondCached(Cache, L, ExitCond, TBB, FBB,
6144                                         ControlsExit, AllowPredicates);
6145 }
6146 
6147 Optional<ScalarEvolution::ExitLimit>
6148 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
6149                                       BasicBlock *TBB, BasicBlock *FBB,
6150                                       bool ControlsExit, bool AllowPredicates) {
6151   (void)this->L;
6152   (void)this->TBB;
6153   (void)this->FBB;
6154   (void)this->AllowPredicates;
6155 
6156   assert(this->L == L && this->TBB == TBB && this->FBB == FBB &&
6157          this->AllowPredicates == AllowPredicates &&
6158          "Variance in assumed invariant key components!");
6159   auto Itr = TripCountMap.find({ExitCond, ControlsExit});
6160   if (Itr == TripCountMap.end())
6161     return None;
6162   return Itr->second;
6163 }
6164 
6165 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
6166                                              BasicBlock *TBB, BasicBlock *FBB,
6167                                              bool ControlsExit,
6168                                              bool AllowPredicates,
6169                                              const ExitLimit &EL) {
6170   assert(this->L == L && this->TBB == TBB && this->FBB == FBB &&
6171          this->AllowPredicates == AllowPredicates &&
6172          "Variance in assumed invariant key components!");
6173 
6174   auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL});
6175   assert(InsertResult.second && "Expected successful insertion!");
6176   (void)InsertResult;
6177 }
6178 
6179 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
6180     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, BasicBlock *TBB,
6181     BasicBlock *FBB, bool ControlsExit, bool AllowPredicates) {
6182 
6183   if (auto MaybeEL =
6184           Cache.find(L, ExitCond, TBB, FBB, ControlsExit, AllowPredicates))
6185     return *MaybeEL;
6186 
6187   ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, TBB, FBB,
6188                                               ControlsExit, AllowPredicates);
6189   Cache.insert(L, ExitCond, TBB, FBB, ControlsExit, AllowPredicates, EL);
6190   return EL;
6191 }
6192 
6193 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
6194     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, BasicBlock *TBB,
6195     BasicBlock *FBB, bool ControlsExit, bool AllowPredicates) {
6196   // Check if the controlling expression for this loop is an And or Or.
6197   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
6198     if (BO->getOpcode() == Instruction::And) {
6199       // Recurse on the operands of the and.
6200       bool EitherMayExit = L->contains(TBB);
6201       ExitLimit EL0 = computeExitLimitFromCondCached(
6202           Cache, L, BO->getOperand(0), TBB, FBB, ControlsExit && !EitherMayExit,
6203           AllowPredicates);
6204       ExitLimit EL1 = computeExitLimitFromCondCached(
6205           Cache, L, BO->getOperand(1), TBB, FBB, ControlsExit && !EitherMayExit,
6206           AllowPredicates);
6207       const SCEV *BECount = getCouldNotCompute();
6208       const SCEV *MaxBECount = getCouldNotCompute();
6209       if (EitherMayExit) {
6210         // Both conditions must be true for the loop to continue executing.
6211         // Choose the less conservative count.
6212         if (EL0.ExactNotTaken == getCouldNotCompute() ||
6213             EL1.ExactNotTaken == getCouldNotCompute())
6214           BECount = getCouldNotCompute();
6215         else
6216           BECount =
6217               getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
6218         if (EL0.MaxNotTaken == getCouldNotCompute())
6219           MaxBECount = EL1.MaxNotTaken;
6220         else if (EL1.MaxNotTaken == getCouldNotCompute())
6221           MaxBECount = EL0.MaxNotTaken;
6222         else
6223           MaxBECount =
6224               getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
6225       } else {
6226         // Both conditions must be true at the same time for the loop to exit.
6227         // For now, be conservative.
6228         assert(L->contains(FBB) && "Loop block has no successor in loop!");
6229         if (EL0.MaxNotTaken == EL1.MaxNotTaken)
6230           MaxBECount = EL0.MaxNotTaken;
6231         if (EL0.ExactNotTaken == EL1.ExactNotTaken)
6232           BECount = EL0.ExactNotTaken;
6233       }
6234 
6235       // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
6236       // to be more aggressive when computing BECount than when computing
6237       // MaxBECount.  In these cases it is possible for EL0.ExactNotTaken and
6238       // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
6239       // to not.
6240       if (isa<SCEVCouldNotCompute>(MaxBECount) &&
6241           !isa<SCEVCouldNotCompute>(BECount))
6242         MaxBECount = BECount;
6243 
6244       return ExitLimit(BECount, MaxBECount, false,
6245                        {&EL0.Predicates, &EL1.Predicates});
6246     }
6247     if (BO->getOpcode() == Instruction::Or) {
6248       // Recurse on the operands of the or.
6249       bool EitherMayExit = L->contains(FBB);
6250       ExitLimit EL0 = computeExitLimitFromCondCached(
6251           Cache, L, BO->getOperand(0), TBB, FBB, ControlsExit && !EitherMayExit,
6252           AllowPredicates);
6253       ExitLimit EL1 = computeExitLimitFromCondCached(
6254           Cache, L, BO->getOperand(1), TBB, FBB, ControlsExit && !EitherMayExit,
6255           AllowPredicates);
6256       const SCEV *BECount = getCouldNotCompute();
6257       const SCEV *MaxBECount = getCouldNotCompute();
6258       if (EitherMayExit) {
6259         // Both conditions must be false for the loop to continue executing.
6260         // Choose the less conservative count.
6261         if (EL0.ExactNotTaken == getCouldNotCompute() ||
6262             EL1.ExactNotTaken == getCouldNotCompute())
6263           BECount = getCouldNotCompute();
6264         else
6265           BECount =
6266               getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
6267         if (EL0.MaxNotTaken == getCouldNotCompute())
6268           MaxBECount = EL1.MaxNotTaken;
6269         else if (EL1.MaxNotTaken == getCouldNotCompute())
6270           MaxBECount = EL0.MaxNotTaken;
6271         else
6272           MaxBECount =
6273               getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
6274       } else {
6275         // Both conditions must be false at the same time for the loop to exit.
6276         // For now, be conservative.
6277         assert(L->contains(TBB) && "Loop block has no successor in loop!");
6278         if (EL0.MaxNotTaken == EL1.MaxNotTaken)
6279           MaxBECount = EL0.MaxNotTaken;
6280         if (EL0.ExactNotTaken == EL1.ExactNotTaken)
6281           BECount = EL0.ExactNotTaken;
6282       }
6283 
6284       return ExitLimit(BECount, MaxBECount, false,
6285                        {&EL0.Predicates, &EL1.Predicates});
6286     }
6287   }
6288 
6289   // With an icmp, it may be feasible to compute an exact backedge-taken count.
6290   // Proceed to the next level to examine the icmp.
6291   if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
6292     ExitLimit EL =
6293         computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit);
6294     if (EL.hasFullInfo() || !AllowPredicates)
6295       return EL;
6296 
6297     // Try again, but use SCEV predicates this time.
6298     return computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit,
6299                                     /*AllowPredicates=*/true);
6300   }
6301 
6302   // Check for a constant condition. These are normally stripped out by
6303   // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
6304   // preserve the CFG and is temporarily leaving constant conditions
6305   // in place.
6306   if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
6307     if (L->contains(FBB) == !CI->getZExtValue())
6308       // The backedge is always taken.
6309       return getCouldNotCompute();
6310     else
6311       // The backedge is never taken.
6312       return getZero(CI->getType());
6313   }
6314 
6315   // If it's not an integer or pointer comparison then compute it the hard way.
6316   return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
6317 }
6318 
6319 ScalarEvolution::ExitLimit
6320 ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
6321                                           ICmpInst *ExitCond,
6322                                           BasicBlock *TBB,
6323                                           BasicBlock *FBB,
6324                                           bool ControlsExit,
6325                                           bool AllowPredicates) {
6326 
6327   // If the condition was exit on true, convert the condition to exit on false
6328   ICmpInst::Predicate Cond;
6329   if (!L->contains(FBB))
6330     Cond = ExitCond->getPredicate();
6331   else
6332     Cond = ExitCond->getInversePredicate();
6333 
6334   // Handle common loops like: for (X = "string"; *X; ++X)
6335   if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
6336     if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
6337       ExitLimit ItCnt =
6338         computeLoadConstantCompareExitLimit(LI, RHS, L, Cond);
6339       if (ItCnt.hasAnyInfo())
6340         return ItCnt;
6341     }
6342 
6343   const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
6344   const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
6345 
6346   // Try to evaluate any dependencies out of the loop.
6347   LHS = getSCEVAtScope(LHS, L);
6348   RHS = getSCEVAtScope(RHS, L);
6349 
6350   // At this point, we would like to compute how many iterations of the
6351   // loop the predicate will return true for these inputs.
6352   if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
6353     // If there is a loop-invariant, force it into the RHS.
6354     std::swap(LHS, RHS);
6355     Cond = ICmpInst::getSwappedPredicate(Cond);
6356   }
6357 
6358   // Simplify the operands before analyzing them.
6359   (void)SimplifyICmpOperands(Cond, LHS, RHS);
6360 
6361   // If we have a comparison of a chrec against a constant, try to use value
6362   // ranges to answer this query.
6363   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
6364     if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
6365       if (AddRec->getLoop() == L) {
6366         // Form the constant range.
6367         ConstantRange CompRange =
6368             ConstantRange::makeExactICmpRegion(Cond, RHSC->getAPInt());
6369 
6370         const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
6371         if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
6372       }
6373 
6374   switch (Cond) {
6375   case ICmpInst::ICMP_NE: {                     // while (X != Y)
6376     // Convert to: while (X-Y != 0)
6377     ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit,
6378                                 AllowPredicates);
6379     if (EL.hasAnyInfo()) return EL;
6380     break;
6381   }
6382   case ICmpInst::ICMP_EQ: {                     // while (X == Y)
6383     // Convert to: while (X-Y == 0)
6384     ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
6385     if (EL.hasAnyInfo()) return EL;
6386     break;
6387   }
6388   case ICmpInst::ICMP_SLT:
6389   case ICmpInst::ICMP_ULT: {                    // while (X < Y)
6390     bool IsSigned = Cond == ICmpInst::ICMP_SLT;
6391     ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit,
6392                                     AllowPredicates);
6393     if (EL.hasAnyInfo()) return EL;
6394     break;
6395   }
6396   case ICmpInst::ICMP_SGT:
6397   case ICmpInst::ICMP_UGT: {                    // while (X > Y)
6398     bool IsSigned = Cond == ICmpInst::ICMP_SGT;
6399     ExitLimit EL =
6400         howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
6401                             AllowPredicates);
6402     if (EL.hasAnyInfo()) return EL;
6403     break;
6404   }
6405   default:
6406     break;
6407   }
6408 
6409   auto *ExhaustiveCount =
6410       computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
6411 
6412   if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
6413     return ExhaustiveCount;
6414 
6415   return computeShiftCompareExitLimit(ExitCond->getOperand(0),
6416                                       ExitCond->getOperand(1), L, Cond);
6417 }
6418 
6419 ScalarEvolution::ExitLimit
6420 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
6421                                                       SwitchInst *Switch,
6422                                                       BasicBlock *ExitingBlock,
6423                                                       bool ControlsExit) {
6424   assert(!L->contains(ExitingBlock) && "Not an exiting block!");
6425 
6426   // Give up if the exit is the default dest of a switch.
6427   if (Switch->getDefaultDest() == ExitingBlock)
6428     return getCouldNotCompute();
6429 
6430   assert(L->contains(Switch->getDefaultDest()) &&
6431          "Default case must not exit the loop!");
6432   const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
6433   const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
6434 
6435   // while (X != Y) --> while (X-Y != 0)
6436   ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
6437   if (EL.hasAnyInfo())
6438     return EL;
6439 
6440   return getCouldNotCompute();
6441 }
6442 
6443 static ConstantInt *
6444 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
6445                                 ScalarEvolution &SE) {
6446   const SCEV *InVal = SE.getConstant(C);
6447   const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
6448   assert(isa<SCEVConstant>(Val) &&
6449          "Evaluation of SCEV at constant didn't fold correctly?");
6450   return cast<SCEVConstant>(Val)->getValue();
6451 }
6452 
6453 /// Given an exit condition of 'icmp op load X, cst', try to see if we can
6454 /// compute the backedge execution count.
6455 ScalarEvolution::ExitLimit
6456 ScalarEvolution::computeLoadConstantCompareExitLimit(
6457   LoadInst *LI,
6458   Constant *RHS,
6459   const Loop *L,
6460   ICmpInst::Predicate predicate) {
6461 
6462   if (LI->isVolatile()) return getCouldNotCompute();
6463 
6464   // Check to see if the loaded pointer is a getelementptr of a global.
6465   // TODO: Use SCEV instead of manually grubbing with GEPs.
6466   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
6467   if (!GEP) return getCouldNotCompute();
6468 
6469   // Make sure that it is really a constant global we are gepping, with an
6470   // initializer, and make sure the first IDX is really 0.
6471   GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
6472   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
6473       GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
6474       !cast<Constant>(GEP->getOperand(1))->isNullValue())
6475     return getCouldNotCompute();
6476 
6477   // Okay, we allow one non-constant index into the GEP instruction.
6478   Value *VarIdx = nullptr;
6479   std::vector<Constant*> Indexes;
6480   unsigned VarIdxNum = 0;
6481   for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
6482     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
6483       Indexes.push_back(CI);
6484     } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
6485       if (VarIdx) return getCouldNotCompute();  // Multiple non-constant idx's.
6486       VarIdx = GEP->getOperand(i);
6487       VarIdxNum = i-2;
6488       Indexes.push_back(nullptr);
6489     }
6490 
6491   // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
6492   if (!VarIdx)
6493     return getCouldNotCompute();
6494 
6495   // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
6496   // Check to see if X is a loop variant variable value now.
6497   const SCEV *Idx = getSCEV(VarIdx);
6498   Idx = getSCEVAtScope(Idx, L);
6499 
6500   // We can only recognize very limited forms of loop index expressions, in
6501   // particular, only affine AddRec's like {C1,+,C2}.
6502   const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
6503   if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
6504       !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
6505       !isa<SCEVConstant>(IdxExpr->getOperand(1)))
6506     return getCouldNotCompute();
6507 
6508   unsigned MaxSteps = MaxBruteForceIterations;
6509   for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
6510     ConstantInt *ItCst = ConstantInt::get(
6511                            cast<IntegerType>(IdxExpr->getType()), IterationNum);
6512     ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
6513 
6514     // Form the GEP offset.
6515     Indexes[VarIdxNum] = Val;
6516 
6517     Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
6518                                                          Indexes);
6519     if (!Result) break;  // Cannot compute!
6520 
6521     // Evaluate the condition for this iteration.
6522     Result = ConstantExpr::getICmp(predicate, Result, RHS);
6523     if (!isa<ConstantInt>(Result)) break;  // Couldn't decide for sure
6524     if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
6525       ++NumArrayLenItCounts;
6526       return getConstant(ItCst);   // Found terminating iteration!
6527     }
6528   }
6529   return getCouldNotCompute();
6530 }
6531 
6532 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
6533     Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
6534   ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
6535   if (!RHS)
6536     return getCouldNotCompute();
6537 
6538   const BasicBlock *Latch = L->getLoopLatch();
6539   if (!Latch)
6540     return getCouldNotCompute();
6541 
6542   const BasicBlock *Predecessor = L->getLoopPredecessor();
6543   if (!Predecessor)
6544     return getCouldNotCompute();
6545 
6546   // Return true if V is of the form "LHS `shift_op` <positive constant>".
6547   // Return LHS in OutLHS and shift_opt in OutOpCode.
6548   auto MatchPositiveShift =
6549       [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
6550 
6551     using namespace PatternMatch;
6552 
6553     ConstantInt *ShiftAmt;
6554     if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6555       OutOpCode = Instruction::LShr;
6556     else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6557       OutOpCode = Instruction::AShr;
6558     else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6559       OutOpCode = Instruction::Shl;
6560     else
6561       return false;
6562 
6563     return ShiftAmt->getValue().isStrictlyPositive();
6564   };
6565 
6566   // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
6567   //
6568   // loop:
6569   //   %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
6570   //   %iv.shifted = lshr i32 %iv, <positive constant>
6571   //
6572   // Return true on a successful match.  Return the corresponding PHI node (%iv
6573   // above) in PNOut and the opcode of the shift operation in OpCodeOut.
6574   auto MatchShiftRecurrence =
6575       [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
6576     Optional<Instruction::BinaryOps> PostShiftOpCode;
6577 
6578     {
6579       Instruction::BinaryOps OpC;
6580       Value *V;
6581 
6582       // If we encounter a shift instruction, "peel off" the shift operation,
6583       // and remember that we did so.  Later when we inspect %iv's backedge
6584       // value, we will make sure that the backedge value uses the same
6585       // operation.
6586       //
6587       // Note: the peeled shift operation does not have to be the same
6588       // instruction as the one feeding into the PHI's backedge value.  We only
6589       // really care about it being the same *kind* of shift instruction --
6590       // that's all that is required for our later inferences to hold.
6591       if (MatchPositiveShift(LHS, V, OpC)) {
6592         PostShiftOpCode = OpC;
6593         LHS = V;
6594       }
6595     }
6596 
6597     PNOut = dyn_cast<PHINode>(LHS);
6598     if (!PNOut || PNOut->getParent() != L->getHeader())
6599       return false;
6600 
6601     Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
6602     Value *OpLHS;
6603 
6604     return
6605         // The backedge value for the PHI node must be a shift by a positive
6606         // amount
6607         MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
6608 
6609         // of the PHI node itself
6610         OpLHS == PNOut &&
6611 
6612         // and the kind of shift should be match the kind of shift we peeled
6613         // off, if any.
6614         (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut);
6615   };
6616 
6617   PHINode *PN;
6618   Instruction::BinaryOps OpCode;
6619   if (!MatchShiftRecurrence(LHS, PN, OpCode))
6620     return getCouldNotCompute();
6621 
6622   const DataLayout &DL = getDataLayout();
6623 
6624   // The key rationale for this optimization is that for some kinds of shift
6625   // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
6626   // within a finite number of iterations.  If the condition guarding the
6627   // backedge (in the sense that the backedge is taken if the condition is true)
6628   // is false for the value the shift recurrence stabilizes to, then we know
6629   // that the backedge is taken only a finite number of times.
6630 
6631   ConstantInt *StableValue = nullptr;
6632   switch (OpCode) {
6633   default:
6634     llvm_unreachable("Impossible case!");
6635 
6636   case Instruction::AShr: {
6637     // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
6638     // bitwidth(K) iterations.
6639     Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
6640     bool KnownZero, KnownOne;
6641     ComputeSignBit(FirstValue, KnownZero, KnownOne, DL, 0, nullptr,
6642                    Predecessor->getTerminator(), &DT);
6643     auto *Ty = cast<IntegerType>(RHS->getType());
6644     if (KnownZero)
6645       StableValue = ConstantInt::get(Ty, 0);
6646     else if (KnownOne)
6647       StableValue = ConstantInt::get(Ty, -1, true);
6648     else
6649       return getCouldNotCompute();
6650 
6651     break;
6652   }
6653   case Instruction::LShr:
6654   case Instruction::Shl:
6655     // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
6656     // stabilize to 0 in at most bitwidth(K) iterations.
6657     StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
6658     break;
6659   }
6660 
6661   auto *Result =
6662       ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
6663   assert(Result->getType()->isIntegerTy(1) &&
6664          "Otherwise cannot be an operand to a branch instruction");
6665 
6666   if (Result->isZeroValue()) {
6667     unsigned BitWidth = getTypeSizeInBits(RHS->getType());
6668     const SCEV *UpperBound =
6669         getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
6670     return ExitLimit(getCouldNotCompute(), UpperBound, false);
6671   }
6672 
6673   return getCouldNotCompute();
6674 }
6675 
6676 /// Return true if we can constant fold an instruction of the specified type,
6677 /// assuming that all operands were constants.
6678 static bool CanConstantFold(const Instruction *I) {
6679   if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
6680       isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
6681       isa<LoadInst>(I))
6682     return true;
6683 
6684   if (const CallInst *CI = dyn_cast<CallInst>(I))
6685     if (const Function *F = CI->getCalledFunction())
6686       return canConstantFoldCallTo(F);
6687   return false;
6688 }
6689 
6690 /// Determine whether this instruction can constant evolve within this loop
6691 /// assuming its operands can all constant evolve.
6692 static bool canConstantEvolve(Instruction *I, const Loop *L) {
6693   // An instruction outside of the loop can't be derived from a loop PHI.
6694   if (!L->contains(I)) return false;
6695 
6696   if (isa<PHINode>(I)) {
6697     // We don't currently keep track of the control flow needed to evaluate
6698     // PHIs, so we cannot handle PHIs inside of loops.
6699     return L->getHeader() == I->getParent();
6700   }
6701 
6702   // If we won't be able to constant fold this expression even if the operands
6703   // are constants, bail early.
6704   return CanConstantFold(I);
6705 }
6706 
6707 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
6708 /// recursing through each instruction operand until reaching a loop header phi.
6709 static PHINode *
6710 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
6711                                DenseMap<Instruction *, PHINode *> &PHIMap,
6712                                unsigned Depth) {
6713   if (Depth > MaxConstantEvolvingDepth)
6714     return nullptr;
6715 
6716   // Otherwise, we can evaluate this instruction if all of its operands are
6717   // constant or derived from a PHI node themselves.
6718   PHINode *PHI = nullptr;
6719   for (Value *Op : UseInst->operands()) {
6720     if (isa<Constant>(Op)) continue;
6721 
6722     Instruction *OpInst = dyn_cast<Instruction>(Op);
6723     if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
6724 
6725     PHINode *P = dyn_cast<PHINode>(OpInst);
6726     if (!P)
6727       // If this operand is already visited, reuse the prior result.
6728       // We may have P != PHI if this is the deepest point at which the
6729       // inconsistent paths meet.
6730       P = PHIMap.lookup(OpInst);
6731     if (!P) {
6732       // Recurse and memoize the results, whether a phi is found or not.
6733       // This recursive call invalidates pointers into PHIMap.
6734       P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1);
6735       PHIMap[OpInst] = P;
6736     }
6737     if (!P)
6738       return nullptr;  // Not evolving from PHI
6739     if (PHI && PHI != P)
6740       return nullptr;  // Evolving from multiple different PHIs.
6741     PHI = P;
6742   }
6743   // This is a expression evolving from a constant PHI!
6744   return PHI;
6745 }
6746 
6747 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
6748 /// in the loop that V is derived from.  We allow arbitrary operations along the
6749 /// way, but the operands of an operation must either be constants or a value
6750 /// derived from a constant PHI.  If this expression does not fit with these
6751 /// constraints, return null.
6752 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
6753   Instruction *I = dyn_cast<Instruction>(V);
6754   if (!I || !canConstantEvolve(I, L)) return nullptr;
6755 
6756   if (PHINode *PN = dyn_cast<PHINode>(I))
6757     return PN;
6758 
6759   // Record non-constant instructions contained by the loop.
6760   DenseMap<Instruction *, PHINode *> PHIMap;
6761   return getConstantEvolvingPHIOperands(I, L, PHIMap, 0);
6762 }
6763 
6764 /// EvaluateExpression - Given an expression that passes the
6765 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
6766 /// in the loop has the value PHIVal.  If we can't fold this expression for some
6767 /// reason, return null.
6768 static Constant *EvaluateExpression(Value *V, const Loop *L,
6769                                     DenseMap<Instruction *, Constant *> &Vals,
6770                                     const DataLayout &DL,
6771                                     const TargetLibraryInfo *TLI) {
6772   // Convenient constant check, but redundant for recursive calls.
6773   if (Constant *C = dyn_cast<Constant>(V)) return C;
6774   Instruction *I = dyn_cast<Instruction>(V);
6775   if (!I) return nullptr;
6776 
6777   if (Constant *C = Vals.lookup(I)) return C;
6778 
6779   // An instruction inside the loop depends on a value outside the loop that we
6780   // weren't given a mapping for, or a value such as a call inside the loop.
6781   if (!canConstantEvolve(I, L)) return nullptr;
6782 
6783   // An unmapped PHI can be due to a branch or another loop inside this loop,
6784   // or due to this not being the initial iteration through a loop where we
6785   // couldn't compute the evolution of this particular PHI last time.
6786   if (isa<PHINode>(I)) return nullptr;
6787 
6788   std::vector<Constant*> Operands(I->getNumOperands());
6789 
6790   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
6791     Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
6792     if (!Operand) {
6793       Operands[i] = dyn_cast<Constant>(I->getOperand(i));
6794       if (!Operands[i]) return nullptr;
6795       continue;
6796     }
6797     Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
6798     Vals[Operand] = C;
6799     if (!C) return nullptr;
6800     Operands[i] = C;
6801   }
6802 
6803   if (CmpInst *CI = dyn_cast<CmpInst>(I))
6804     return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
6805                                            Operands[1], DL, TLI);
6806   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
6807     if (!LI->isVolatile())
6808       return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
6809   }
6810   return ConstantFoldInstOperands(I, Operands, DL, TLI);
6811 }
6812 
6813 
6814 // If every incoming value to PN except the one for BB is a specific Constant,
6815 // return that, else return nullptr.
6816 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
6817   Constant *IncomingVal = nullptr;
6818 
6819   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
6820     if (PN->getIncomingBlock(i) == BB)
6821       continue;
6822 
6823     auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
6824     if (!CurrentVal)
6825       return nullptr;
6826 
6827     if (IncomingVal != CurrentVal) {
6828       if (IncomingVal)
6829         return nullptr;
6830       IncomingVal = CurrentVal;
6831     }
6832   }
6833 
6834   return IncomingVal;
6835 }
6836 
6837 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
6838 /// in the header of its containing loop, we know the loop executes a
6839 /// constant number of times, and the PHI node is just a recurrence
6840 /// involving constants, fold it.
6841 Constant *
6842 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
6843                                                    const APInt &BEs,
6844                                                    const Loop *L) {
6845   auto I = ConstantEvolutionLoopExitValue.find(PN);
6846   if (I != ConstantEvolutionLoopExitValue.end())
6847     return I->second;
6848 
6849   if (BEs.ugt(MaxBruteForceIterations))
6850     return ConstantEvolutionLoopExitValue[PN] = nullptr;  // Not going to evaluate it.
6851 
6852   Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
6853 
6854   DenseMap<Instruction *, Constant *> CurrentIterVals;
6855   BasicBlock *Header = L->getHeader();
6856   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
6857 
6858   BasicBlock *Latch = L->getLoopLatch();
6859   if (!Latch)
6860     return nullptr;
6861 
6862   for (auto &I : *Header) {
6863     PHINode *PHI = dyn_cast<PHINode>(&I);
6864     if (!PHI) break;
6865     auto *StartCST = getOtherIncomingValue(PHI, Latch);
6866     if (!StartCST) continue;
6867     CurrentIterVals[PHI] = StartCST;
6868   }
6869   if (!CurrentIterVals.count(PN))
6870     return RetVal = nullptr;
6871 
6872   Value *BEValue = PN->getIncomingValueForBlock(Latch);
6873 
6874   // Execute the loop symbolically to determine the exit value.
6875   if (BEs.getActiveBits() >= 32)
6876     return RetVal = nullptr; // More than 2^32-1 iterations?? Not doing it!
6877 
6878   unsigned NumIterations = BEs.getZExtValue(); // must be in range
6879   unsigned IterationNum = 0;
6880   const DataLayout &DL = getDataLayout();
6881   for (; ; ++IterationNum) {
6882     if (IterationNum == NumIterations)
6883       return RetVal = CurrentIterVals[PN];  // Got exit value!
6884 
6885     // Compute the value of the PHIs for the next iteration.
6886     // EvaluateExpression adds non-phi values to the CurrentIterVals map.
6887     DenseMap<Instruction *, Constant *> NextIterVals;
6888     Constant *NextPHI =
6889         EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
6890     if (!NextPHI)
6891       return nullptr;        // Couldn't evaluate!
6892     NextIterVals[PN] = NextPHI;
6893 
6894     bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
6895 
6896     // Also evaluate the other PHI nodes.  However, we don't get to stop if we
6897     // cease to be able to evaluate one of them or if they stop evolving,
6898     // because that doesn't necessarily prevent us from computing PN.
6899     SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
6900     for (const auto &I : CurrentIterVals) {
6901       PHINode *PHI = dyn_cast<PHINode>(I.first);
6902       if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
6903       PHIsToCompute.emplace_back(PHI, I.second);
6904     }
6905     // We use two distinct loops because EvaluateExpression may invalidate any
6906     // iterators into CurrentIterVals.
6907     for (const auto &I : PHIsToCompute) {
6908       PHINode *PHI = I.first;
6909       Constant *&NextPHI = NextIterVals[PHI];
6910       if (!NextPHI) {   // Not already computed.
6911         Value *BEValue = PHI->getIncomingValueForBlock(Latch);
6912         NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
6913       }
6914       if (NextPHI != I.second)
6915         StoppedEvolving = false;
6916     }
6917 
6918     // If all entries in CurrentIterVals == NextIterVals then we can stop
6919     // iterating, the loop can't continue to change.
6920     if (StoppedEvolving)
6921       return RetVal = CurrentIterVals[PN];
6922 
6923     CurrentIterVals.swap(NextIterVals);
6924   }
6925 }
6926 
6927 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
6928                                                           Value *Cond,
6929                                                           bool ExitWhen) {
6930   PHINode *PN = getConstantEvolvingPHI(Cond, L);
6931   if (!PN) return getCouldNotCompute();
6932 
6933   // If the loop is canonicalized, the PHI will have exactly two entries.
6934   // That's the only form we support here.
6935   if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
6936 
6937   DenseMap<Instruction *, Constant *> CurrentIterVals;
6938   BasicBlock *Header = L->getHeader();
6939   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
6940 
6941   BasicBlock *Latch = L->getLoopLatch();
6942   assert(Latch && "Should follow from NumIncomingValues == 2!");
6943 
6944   for (auto &I : *Header) {
6945     PHINode *PHI = dyn_cast<PHINode>(&I);
6946     if (!PHI)
6947       break;
6948     auto *StartCST = getOtherIncomingValue(PHI, Latch);
6949     if (!StartCST) continue;
6950     CurrentIterVals[PHI] = StartCST;
6951   }
6952   if (!CurrentIterVals.count(PN))
6953     return getCouldNotCompute();
6954 
6955   // Okay, we find a PHI node that defines the trip count of this loop.  Execute
6956   // the loop symbolically to determine when the condition gets a value of
6957   // "ExitWhen".
6958   unsigned MaxIterations = MaxBruteForceIterations;   // Limit analysis.
6959   const DataLayout &DL = getDataLayout();
6960   for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
6961     auto *CondVal = dyn_cast_or_null<ConstantInt>(
6962         EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
6963 
6964     // Couldn't symbolically evaluate.
6965     if (!CondVal) return getCouldNotCompute();
6966 
6967     if (CondVal->getValue() == uint64_t(ExitWhen)) {
6968       ++NumBruteForceTripCountsComputed;
6969       return getConstant(Type::getInt32Ty(getContext()), IterationNum);
6970     }
6971 
6972     // Update all the PHI nodes for the next iteration.
6973     DenseMap<Instruction *, Constant *> NextIterVals;
6974 
6975     // Create a list of which PHIs we need to compute. We want to do this before
6976     // calling EvaluateExpression on them because that may invalidate iterators
6977     // into CurrentIterVals.
6978     SmallVector<PHINode *, 8> PHIsToCompute;
6979     for (const auto &I : CurrentIterVals) {
6980       PHINode *PHI = dyn_cast<PHINode>(I.first);
6981       if (!PHI || PHI->getParent() != Header) continue;
6982       PHIsToCompute.push_back(PHI);
6983     }
6984     for (PHINode *PHI : PHIsToCompute) {
6985       Constant *&NextPHI = NextIterVals[PHI];
6986       if (NextPHI) continue;    // Already computed!
6987 
6988       Value *BEValue = PHI->getIncomingValueForBlock(Latch);
6989       NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
6990     }
6991     CurrentIterVals.swap(NextIterVals);
6992   }
6993 
6994   // Too many iterations were needed to evaluate.
6995   return getCouldNotCompute();
6996 }
6997 
6998 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
6999   SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
7000       ValuesAtScopes[V];
7001   // Check to see if we've folded this expression at this loop before.
7002   for (auto &LS : Values)
7003     if (LS.first == L)
7004       return LS.second ? LS.second : V;
7005 
7006   Values.emplace_back(L, nullptr);
7007 
7008   // Otherwise compute it.
7009   const SCEV *C = computeSCEVAtScope(V, L);
7010   for (auto &LS : reverse(ValuesAtScopes[V]))
7011     if (LS.first == L) {
7012       LS.second = C;
7013       break;
7014     }
7015   return C;
7016 }
7017 
7018 /// This builds up a Constant using the ConstantExpr interface.  That way, we
7019 /// will return Constants for objects which aren't represented by a
7020 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
7021 /// Returns NULL if the SCEV isn't representable as a Constant.
7022 static Constant *BuildConstantFromSCEV(const SCEV *V) {
7023   switch (static_cast<SCEVTypes>(V->getSCEVType())) {
7024     case scCouldNotCompute:
7025     case scAddRecExpr:
7026       break;
7027     case scConstant:
7028       return cast<SCEVConstant>(V)->getValue();
7029     case scUnknown:
7030       return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
7031     case scSignExtend: {
7032       const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
7033       if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
7034         return ConstantExpr::getSExt(CastOp, SS->getType());
7035       break;
7036     }
7037     case scZeroExtend: {
7038       const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
7039       if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
7040         return ConstantExpr::getZExt(CastOp, SZ->getType());
7041       break;
7042     }
7043     case scTruncate: {
7044       const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
7045       if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
7046         return ConstantExpr::getTrunc(CastOp, ST->getType());
7047       break;
7048     }
7049     case scAddExpr: {
7050       const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
7051       if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
7052         if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
7053           unsigned AS = PTy->getAddressSpace();
7054           Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
7055           C = ConstantExpr::getBitCast(C, DestPtrTy);
7056         }
7057         for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
7058           Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
7059           if (!C2) return nullptr;
7060 
7061           // First pointer!
7062           if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
7063             unsigned AS = C2->getType()->getPointerAddressSpace();
7064             std::swap(C, C2);
7065             Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
7066             // The offsets have been converted to bytes.  We can add bytes to an
7067             // i8* by GEP with the byte count in the first index.
7068             C = ConstantExpr::getBitCast(C, DestPtrTy);
7069           }
7070 
7071           // Don't bother trying to sum two pointers. We probably can't
7072           // statically compute a load that results from it anyway.
7073           if (C2->getType()->isPointerTy())
7074             return nullptr;
7075 
7076           if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
7077             if (PTy->getElementType()->isStructTy())
7078               C2 = ConstantExpr::getIntegerCast(
7079                   C2, Type::getInt32Ty(C->getContext()), true);
7080             C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2);
7081           } else
7082             C = ConstantExpr::getAdd(C, C2);
7083         }
7084         return C;
7085       }
7086       break;
7087     }
7088     case scMulExpr: {
7089       const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
7090       if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
7091         // Don't bother with pointers at all.
7092         if (C->getType()->isPointerTy()) return nullptr;
7093         for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
7094           Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
7095           if (!C2 || C2->getType()->isPointerTy()) return nullptr;
7096           C = ConstantExpr::getMul(C, C2);
7097         }
7098         return C;
7099       }
7100       break;
7101     }
7102     case scUDivExpr: {
7103       const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
7104       if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
7105         if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
7106           if (LHS->getType() == RHS->getType())
7107             return ConstantExpr::getUDiv(LHS, RHS);
7108       break;
7109     }
7110     case scSMaxExpr:
7111     case scUMaxExpr:
7112       break; // TODO: smax, umax.
7113   }
7114   return nullptr;
7115 }
7116 
7117 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
7118   if (isa<SCEVConstant>(V)) return V;
7119 
7120   // If this instruction is evolved from a constant-evolving PHI, compute the
7121   // exit value from the loop without using SCEVs.
7122   if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
7123     if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
7124       const Loop *LI = this->LI[I->getParent()];
7125       if (LI && LI->getParentLoop() == L)  // Looking for loop exit value.
7126         if (PHINode *PN = dyn_cast<PHINode>(I))
7127           if (PN->getParent() == LI->getHeader()) {
7128             // Okay, there is no closed form solution for the PHI node.  Check
7129             // to see if the loop that contains it has a known backedge-taken
7130             // count.  If so, we may be able to force computation of the exit
7131             // value.
7132             const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
7133             if (const SCEVConstant *BTCC =
7134                   dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
7135               // Okay, we know how many times the containing loop executes.  If
7136               // this is a constant evolving PHI node, get the final value at
7137               // the specified iteration number.
7138               Constant *RV =
7139                   getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI);
7140               if (RV) return getSCEV(RV);
7141             }
7142           }
7143 
7144       // Okay, this is an expression that we cannot symbolically evaluate
7145       // into a SCEV.  Check to see if it's possible to symbolically evaluate
7146       // the arguments into constants, and if so, try to constant propagate the
7147       // result.  This is particularly useful for computing loop exit values.
7148       if (CanConstantFold(I)) {
7149         SmallVector<Constant *, 4> Operands;
7150         bool MadeImprovement = false;
7151         for (Value *Op : I->operands()) {
7152           if (Constant *C = dyn_cast<Constant>(Op)) {
7153             Operands.push_back(C);
7154             continue;
7155           }
7156 
7157           // If any of the operands is non-constant and if they are
7158           // non-integer and non-pointer, don't even try to analyze them
7159           // with scev techniques.
7160           if (!isSCEVable(Op->getType()))
7161             return V;
7162 
7163           const SCEV *OrigV = getSCEV(Op);
7164           const SCEV *OpV = getSCEVAtScope(OrigV, L);
7165           MadeImprovement |= OrigV != OpV;
7166 
7167           Constant *C = BuildConstantFromSCEV(OpV);
7168           if (!C) return V;
7169           if (C->getType() != Op->getType())
7170             C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
7171                                                               Op->getType(),
7172                                                               false),
7173                                       C, Op->getType());
7174           Operands.push_back(C);
7175         }
7176 
7177         // Check to see if getSCEVAtScope actually made an improvement.
7178         if (MadeImprovement) {
7179           Constant *C = nullptr;
7180           const DataLayout &DL = getDataLayout();
7181           if (const CmpInst *CI = dyn_cast<CmpInst>(I))
7182             C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
7183                                                 Operands[1], DL, &TLI);
7184           else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
7185             if (!LI->isVolatile())
7186               C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
7187           } else
7188             C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
7189           if (!C) return V;
7190           return getSCEV(C);
7191         }
7192       }
7193     }
7194 
7195     // This is some other type of SCEVUnknown, just return it.
7196     return V;
7197   }
7198 
7199   if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
7200     // Avoid performing the look-up in the common case where the specified
7201     // expression has no loop-variant portions.
7202     for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
7203       const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
7204       if (OpAtScope != Comm->getOperand(i)) {
7205         // Okay, at least one of these operands is loop variant but might be
7206         // foldable.  Build a new instance of the folded commutative expression.
7207         SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
7208                                             Comm->op_begin()+i);
7209         NewOps.push_back(OpAtScope);
7210 
7211         for (++i; i != e; ++i) {
7212           OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
7213           NewOps.push_back(OpAtScope);
7214         }
7215         if (isa<SCEVAddExpr>(Comm))
7216           return getAddExpr(NewOps);
7217         if (isa<SCEVMulExpr>(Comm))
7218           return getMulExpr(NewOps);
7219         if (isa<SCEVSMaxExpr>(Comm))
7220           return getSMaxExpr(NewOps);
7221         if (isa<SCEVUMaxExpr>(Comm))
7222           return getUMaxExpr(NewOps);
7223         llvm_unreachable("Unknown commutative SCEV type!");
7224       }
7225     }
7226     // If we got here, all operands are loop invariant.
7227     return Comm;
7228   }
7229 
7230   if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
7231     const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
7232     const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
7233     if (LHS == Div->getLHS() && RHS == Div->getRHS())
7234       return Div;   // must be loop invariant
7235     return getUDivExpr(LHS, RHS);
7236   }
7237 
7238   // If this is a loop recurrence for a loop that does not contain L, then we
7239   // are dealing with the final value computed by the loop.
7240   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
7241     // First, attempt to evaluate each operand.
7242     // Avoid performing the look-up in the common case where the specified
7243     // expression has no loop-variant portions.
7244     for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
7245       const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
7246       if (OpAtScope == AddRec->getOperand(i))
7247         continue;
7248 
7249       // Okay, at least one of these operands is loop variant but might be
7250       // foldable.  Build a new instance of the folded commutative expression.
7251       SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
7252                                           AddRec->op_begin()+i);
7253       NewOps.push_back(OpAtScope);
7254       for (++i; i != e; ++i)
7255         NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
7256 
7257       const SCEV *FoldedRec =
7258         getAddRecExpr(NewOps, AddRec->getLoop(),
7259                       AddRec->getNoWrapFlags(SCEV::FlagNW));
7260       AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
7261       // The addrec may be folded to a nonrecurrence, for example, if the
7262       // induction variable is multiplied by zero after constant folding. Go
7263       // ahead and return the folded value.
7264       if (!AddRec)
7265         return FoldedRec;
7266       break;
7267     }
7268 
7269     // If the scope is outside the addrec's loop, evaluate it by using the
7270     // loop exit value of the addrec.
7271     if (!AddRec->getLoop()->contains(L)) {
7272       // To evaluate this recurrence, we need to know how many times the AddRec
7273       // loop iterates.  Compute this now.
7274       const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
7275       if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
7276 
7277       // Then, evaluate the AddRec.
7278       return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
7279     }
7280 
7281     return AddRec;
7282   }
7283 
7284   if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
7285     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
7286     if (Op == Cast->getOperand())
7287       return Cast;  // must be loop invariant
7288     return getZeroExtendExpr(Op, Cast->getType());
7289   }
7290 
7291   if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
7292     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
7293     if (Op == Cast->getOperand())
7294       return Cast;  // must be loop invariant
7295     return getSignExtendExpr(Op, Cast->getType());
7296   }
7297 
7298   if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
7299     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
7300     if (Op == Cast->getOperand())
7301       return Cast;  // must be loop invariant
7302     return getTruncateExpr(Op, Cast->getType());
7303   }
7304 
7305   llvm_unreachable("Unknown SCEV type!");
7306 }
7307 
7308 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
7309   return getSCEVAtScope(getSCEV(V), L);
7310 }
7311 
7312 /// Finds the minimum unsigned root of the following equation:
7313 ///
7314 ///     A * X = B (mod N)
7315 ///
7316 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
7317 /// A and B isn't important.
7318 ///
7319 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
7320 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B,
7321                                                ScalarEvolution &SE) {
7322   uint32_t BW = A.getBitWidth();
7323   assert(BW == SE.getTypeSizeInBits(B->getType()));
7324   assert(A != 0 && "A must be non-zero.");
7325 
7326   // 1. D = gcd(A, N)
7327   //
7328   // The gcd of A and N may have only one prime factor: 2. The number of
7329   // trailing zeros in A is its multiplicity
7330   uint32_t Mult2 = A.countTrailingZeros();
7331   // D = 2^Mult2
7332 
7333   // 2. Check if B is divisible by D.
7334   //
7335   // B is divisible by D if and only if the multiplicity of prime factor 2 for B
7336   // is not less than multiplicity of this prime factor for D.
7337   if (SE.GetMinTrailingZeros(B) < Mult2)
7338     return SE.getCouldNotCompute();
7339 
7340   // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
7341   // modulo (N / D).
7342   //
7343   // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
7344   // (N / D) in general. The inverse itself always fits into BW bits, though,
7345   // so we immediately truncate it.
7346   APInt AD = A.lshr(Mult2).zext(BW + 1);  // AD = A / D
7347   APInt Mod(BW + 1, 0);
7348   Mod.setBit(BW - Mult2);  // Mod = N / D
7349   APInt I = AD.multiplicativeInverse(Mod).trunc(BW);
7350 
7351   // 4. Compute the minimum unsigned root of the equation:
7352   // I * (B / D) mod (N / D)
7353   // To simplify the computation, we factor out the divide by D:
7354   // (I * B mod N) / D
7355   const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
7356   return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
7357 }
7358 
7359 /// Find the roots of the quadratic equation for the given quadratic chrec
7360 /// {L,+,M,+,N}.  This returns either the two roots (which might be the same) or
7361 /// two SCEVCouldNotCompute objects.
7362 ///
7363 static Optional<std::pair<const SCEVConstant *,const SCEVConstant *>>
7364 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
7365   assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
7366   const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
7367   const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
7368   const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
7369 
7370   // We currently can only solve this if the coefficients are constants.
7371   if (!LC || !MC || !NC)
7372     return None;
7373 
7374   uint32_t BitWidth = LC->getAPInt().getBitWidth();
7375   const APInt &L = LC->getAPInt();
7376   const APInt &M = MC->getAPInt();
7377   const APInt &N = NC->getAPInt();
7378   APInt Two(BitWidth, 2);
7379 
7380   // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
7381 
7382   // The A coefficient is N/2
7383   APInt A(N.sdiv(Two));
7384 
7385   // The B coefficient is M-N/2
7386   APInt B(M);
7387   B -= A; // A is the same as N/2.
7388 
7389   // The C coefficient is L.
7390   const APInt& C = L;
7391 
7392   // Compute the B^2-4ac term.
7393   APInt SqrtTerm(B);
7394   SqrtTerm *= B;
7395   SqrtTerm -= 4 * (A * C);
7396 
7397   if (SqrtTerm.isNegative()) {
7398     // The loop is provably infinite.
7399     return None;
7400   }
7401 
7402   // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
7403   // integer value or else APInt::sqrt() will assert.
7404   APInt SqrtVal(SqrtTerm.sqrt());
7405 
7406   // Compute the two solutions for the quadratic formula.
7407   // The divisions must be performed as signed divisions.
7408   APInt NegB(-std::move(B));
7409   APInt TwoA(std::move(A));
7410   TwoA <<= 1;
7411   if (TwoA.isNullValue())
7412     return None;
7413 
7414   LLVMContext &Context = SE.getContext();
7415 
7416   ConstantInt *Solution1 =
7417     ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
7418   ConstantInt *Solution2 =
7419     ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
7420 
7421   return std::make_pair(cast<SCEVConstant>(SE.getConstant(Solution1)),
7422                         cast<SCEVConstant>(SE.getConstant(Solution2)));
7423 }
7424 
7425 ScalarEvolution::ExitLimit
7426 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit,
7427                               bool AllowPredicates) {
7428 
7429   // This is only used for loops with a "x != y" exit test. The exit condition
7430   // is now expressed as a single expression, V = x-y. So the exit test is
7431   // effectively V != 0.  We know and take advantage of the fact that this
7432   // expression only being used in a comparison by zero context.
7433 
7434   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
7435   // If the value is a constant
7436   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
7437     // If the value is already zero, the branch will execute zero times.
7438     if (C->getValue()->isZero()) return C;
7439     return getCouldNotCompute();  // Otherwise it will loop infinitely.
7440   }
7441 
7442   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
7443   if (!AddRec && AllowPredicates)
7444     // Try to make this an AddRec using runtime tests, in the first X
7445     // iterations of this loop, where X is the SCEV expression found by the
7446     // algorithm below.
7447     AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
7448 
7449   if (!AddRec || AddRec->getLoop() != L)
7450     return getCouldNotCompute();
7451 
7452   // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
7453   // the quadratic equation to solve it.
7454   if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
7455     if (auto Roots = SolveQuadraticEquation(AddRec, *this)) {
7456       const SCEVConstant *R1 = Roots->first;
7457       const SCEVConstant *R2 = Roots->second;
7458       // Pick the smallest positive root value.
7459       if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
7460               CmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
7461         if (!CB->getZExtValue())
7462           std::swap(R1, R2); // R1 is the minimum root now.
7463 
7464         // We can only use this value if the chrec ends up with an exact zero
7465         // value at this index.  When solving for "X*X != 5", for example, we
7466         // should not accept a root of 2.
7467         const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
7468         if (Val->isZero())
7469           // We found a quadratic root!
7470           return ExitLimit(R1, R1, false, Predicates);
7471       }
7472     }
7473     return getCouldNotCompute();
7474   }
7475 
7476   // Otherwise we can only handle this if it is affine.
7477   if (!AddRec->isAffine())
7478     return getCouldNotCompute();
7479 
7480   // If this is an affine expression, the execution count of this branch is
7481   // the minimum unsigned root of the following equation:
7482   //
7483   //     Start + Step*N = 0 (mod 2^BW)
7484   //
7485   // equivalent to:
7486   //
7487   //             Step*N = -Start (mod 2^BW)
7488   //
7489   // where BW is the common bit width of Start and Step.
7490 
7491   // Get the initial value for the loop.
7492   const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
7493   const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
7494 
7495   // For now we handle only constant steps.
7496   //
7497   // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
7498   // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
7499   // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
7500   // We have not yet seen any such cases.
7501   const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
7502   if (!StepC || StepC->getValue()->equalsInt(0))
7503     return getCouldNotCompute();
7504 
7505   // For positive steps (counting up until unsigned overflow):
7506   //   N = -Start/Step (as unsigned)
7507   // For negative steps (counting down to zero):
7508   //   N = Start/-Step
7509   // First compute the unsigned distance from zero in the direction of Step.
7510   bool CountDown = StepC->getAPInt().isNegative();
7511   const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
7512 
7513   // Handle unitary steps, which cannot wraparound.
7514   // 1*N = -Start; -1*N = Start (mod 2^BW), so:
7515   //   N = Distance (as unsigned)
7516   if (StepC->getValue()->equalsInt(1) || StepC->getValue()->isAllOnesValue()) {
7517     APInt MaxBECount = getUnsignedRange(Distance).getUnsignedMax();
7518 
7519     // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
7520     // we end up with a loop whose backedge-taken count is n - 1.  Detect this
7521     // case, and see if we can improve the bound.
7522     //
7523     // Explicitly handling this here is necessary because getUnsignedRange
7524     // isn't context-sensitive; it doesn't know that we only care about the
7525     // range inside the loop.
7526     const SCEV *Zero = getZero(Distance->getType());
7527     const SCEV *One = getOne(Distance->getType());
7528     const SCEV *DistancePlusOne = getAddExpr(Distance, One);
7529     if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
7530       // If Distance + 1 doesn't overflow, we can compute the maximum distance
7531       // as "unsigned_max(Distance + 1) - 1".
7532       ConstantRange CR = getUnsignedRange(DistancePlusOne);
7533       MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1);
7534     }
7535     return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates);
7536   }
7537 
7538   // If the condition controls loop exit (the loop exits only if the expression
7539   // is true) and the addition is no-wrap we can use unsigned divide to
7540   // compute the backedge count.  In this case, the step may not divide the
7541   // distance, but we don't care because if the condition is "missed" the loop
7542   // will have undefined behavior due to wrapping.
7543   if (ControlsExit && AddRec->hasNoSelfWrap() &&
7544       loopHasNoAbnormalExits(AddRec->getLoop())) {
7545     const SCEV *Exact =
7546         getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
7547     return ExitLimit(Exact, Exact, false, Predicates);
7548   }
7549 
7550   // Solve the general equation.
7551   const SCEV *E = SolveLinEquationWithOverflow(
7552       StepC->getAPInt(), getNegativeSCEV(Start), *this);
7553   return ExitLimit(E, E, false, Predicates);
7554 }
7555 
7556 ScalarEvolution::ExitLimit
7557 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
7558   // Loops that look like: while (X == 0) are very strange indeed.  We don't
7559   // handle them yet except for the trivial case.  This could be expanded in the
7560   // future as needed.
7561 
7562   // If the value is a constant, check to see if it is known to be non-zero
7563   // already.  If so, the backedge will execute zero times.
7564   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
7565     if (!C->getValue()->isNullValue())
7566       return getZero(C->getType());
7567     return getCouldNotCompute();  // Otherwise it will loop infinitely.
7568   }
7569 
7570   // We could implement others, but I really doubt anyone writes loops like
7571   // this, and if they did, they would already be constant folded.
7572   return getCouldNotCompute();
7573 }
7574 
7575 std::pair<BasicBlock *, BasicBlock *>
7576 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
7577   // If the block has a unique predecessor, then there is no path from the
7578   // predecessor to the block that does not go through the direct edge
7579   // from the predecessor to the block.
7580   if (BasicBlock *Pred = BB->getSinglePredecessor())
7581     return {Pred, BB};
7582 
7583   // A loop's header is defined to be a block that dominates the loop.
7584   // If the header has a unique predecessor outside the loop, it must be
7585   // a block that has exactly one successor that can reach the loop.
7586   if (Loop *L = LI.getLoopFor(BB))
7587     return {L->getLoopPredecessor(), L->getHeader()};
7588 
7589   return {nullptr, nullptr};
7590 }
7591 
7592 /// SCEV structural equivalence is usually sufficient for testing whether two
7593 /// expressions are equal, however for the purposes of looking for a condition
7594 /// guarding a loop, it can be useful to be a little more general, since a
7595 /// front-end may have replicated the controlling expression.
7596 ///
7597 static bool HasSameValue(const SCEV *A, const SCEV *B) {
7598   // Quick check to see if they are the same SCEV.
7599   if (A == B) return true;
7600 
7601   auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
7602     // Not all instructions that are "identical" compute the same value.  For
7603     // instance, two distinct alloca instructions allocating the same type are
7604     // identical and do not read memory; but compute distinct values.
7605     return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
7606   };
7607 
7608   // Otherwise, if they're both SCEVUnknown, it's possible that they hold
7609   // two different instructions with the same value. Check for this case.
7610   if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
7611     if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
7612       if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
7613         if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
7614           if (ComputesEqualValues(AI, BI))
7615             return true;
7616 
7617   // Otherwise assume they may have a different value.
7618   return false;
7619 }
7620 
7621 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
7622                                            const SCEV *&LHS, const SCEV *&RHS,
7623                                            unsigned Depth) {
7624   bool Changed = false;
7625 
7626   // If we hit the max recursion limit bail out.
7627   if (Depth >= 3)
7628     return false;
7629 
7630   // Canonicalize a constant to the right side.
7631   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
7632     // Check for both operands constant.
7633     if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
7634       if (ConstantExpr::getICmp(Pred,
7635                                 LHSC->getValue(),
7636                                 RHSC->getValue())->isNullValue())
7637         goto trivially_false;
7638       else
7639         goto trivially_true;
7640     }
7641     // Otherwise swap the operands to put the constant on the right.
7642     std::swap(LHS, RHS);
7643     Pred = ICmpInst::getSwappedPredicate(Pred);
7644     Changed = true;
7645   }
7646 
7647   // If we're comparing an addrec with a value which is loop-invariant in the
7648   // addrec's loop, put the addrec on the left. Also make a dominance check,
7649   // as both operands could be addrecs loop-invariant in each other's loop.
7650   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
7651     const Loop *L = AR->getLoop();
7652     if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
7653       std::swap(LHS, RHS);
7654       Pred = ICmpInst::getSwappedPredicate(Pred);
7655       Changed = true;
7656     }
7657   }
7658 
7659   // If there's a constant operand, canonicalize comparisons with boundary
7660   // cases, and canonicalize *-or-equal comparisons to regular comparisons.
7661   if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
7662     const APInt &RA = RC->getAPInt();
7663 
7664     bool SimplifiedByConstantRange = false;
7665 
7666     if (!ICmpInst::isEquality(Pred)) {
7667       ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA);
7668       if (ExactCR.isFullSet())
7669         goto trivially_true;
7670       else if (ExactCR.isEmptySet())
7671         goto trivially_false;
7672 
7673       APInt NewRHS;
7674       CmpInst::Predicate NewPred;
7675       if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
7676           ICmpInst::isEquality(NewPred)) {
7677         // We were able to convert an inequality to an equality.
7678         Pred = NewPred;
7679         RHS = getConstant(NewRHS);
7680         Changed = SimplifiedByConstantRange = true;
7681       }
7682     }
7683 
7684     if (!SimplifiedByConstantRange) {
7685       switch (Pred) {
7686       default:
7687         break;
7688       case ICmpInst::ICMP_EQ:
7689       case ICmpInst::ICMP_NE:
7690         // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
7691         if (!RA)
7692           if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
7693             if (const SCEVMulExpr *ME =
7694                     dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
7695               if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
7696                   ME->getOperand(0)->isAllOnesValue()) {
7697                 RHS = AE->getOperand(1);
7698                 LHS = ME->getOperand(1);
7699                 Changed = true;
7700               }
7701         break;
7702 
7703 
7704         // The "Should have been caught earlier!" messages refer to the fact
7705         // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
7706         // should have fired on the corresponding cases, and canonicalized the
7707         // check to trivially_true or trivially_false.
7708 
7709       case ICmpInst::ICMP_UGE:
7710         assert(!RA.isMinValue() && "Should have been caught earlier!");
7711         Pred = ICmpInst::ICMP_UGT;
7712         RHS = getConstant(RA - 1);
7713         Changed = true;
7714         break;
7715       case ICmpInst::ICMP_ULE:
7716         assert(!RA.isMaxValue() && "Should have been caught earlier!");
7717         Pred = ICmpInst::ICMP_ULT;
7718         RHS = getConstant(RA + 1);
7719         Changed = true;
7720         break;
7721       case ICmpInst::ICMP_SGE:
7722         assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
7723         Pred = ICmpInst::ICMP_SGT;
7724         RHS = getConstant(RA - 1);
7725         Changed = true;
7726         break;
7727       case ICmpInst::ICMP_SLE:
7728         assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
7729         Pred = ICmpInst::ICMP_SLT;
7730         RHS = getConstant(RA + 1);
7731         Changed = true;
7732         break;
7733       }
7734     }
7735   }
7736 
7737   // Check for obvious equality.
7738   if (HasSameValue(LHS, RHS)) {
7739     if (ICmpInst::isTrueWhenEqual(Pred))
7740       goto trivially_true;
7741     if (ICmpInst::isFalseWhenEqual(Pred))
7742       goto trivially_false;
7743   }
7744 
7745   // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
7746   // adding or subtracting 1 from one of the operands.
7747   switch (Pred) {
7748   case ICmpInst::ICMP_SLE:
7749     if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) {
7750       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
7751                        SCEV::FlagNSW);
7752       Pred = ICmpInst::ICMP_SLT;
7753       Changed = true;
7754     } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) {
7755       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
7756                        SCEV::FlagNSW);
7757       Pred = ICmpInst::ICMP_SLT;
7758       Changed = true;
7759     }
7760     break;
7761   case ICmpInst::ICMP_SGE:
7762     if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) {
7763       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
7764                        SCEV::FlagNSW);
7765       Pred = ICmpInst::ICMP_SGT;
7766       Changed = true;
7767     } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) {
7768       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
7769                        SCEV::FlagNSW);
7770       Pred = ICmpInst::ICMP_SGT;
7771       Changed = true;
7772     }
7773     break;
7774   case ICmpInst::ICMP_ULE:
7775     if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) {
7776       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
7777                        SCEV::FlagNUW);
7778       Pred = ICmpInst::ICMP_ULT;
7779       Changed = true;
7780     } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) {
7781       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
7782       Pred = ICmpInst::ICMP_ULT;
7783       Changed = true;
7784     }
7785     break;
7786   case ICmpInst::ICMP_UGE:
7787     if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) {
7788       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
7789       Pred = ICmpInst::ICMP_UGT;
7790       Changed = true;
7791     } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) {
7792       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
7793                        SCEV::FlagNUW);
7794       Pred = ICmpInst::ICMP_UGT;
7795       Changed = true;
7796     }
7797     break;
7798   default:
7799     break;
7800   }
7801 
7802   // TODO: More simplifications are possible here.
7803 
7804   // Recursively simplify until we either hit a recursion limit or nothing
7805   // changes.
7806   if (Changed)
7807     return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
7808 
7809   return Changed;
7810 
7811 trivially_true:
7812   // Return 0 == 0.
7813   LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
7814   Pred = ICmpInst::ICMP_EQ;
7815   return true;
7816 
7817 trivially_false:
7818   // Return 0 != 0.
7819   LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
7820   Pred = ICmpInst::ICMP_NE;
7821   return true;
7822 }
7823 
7824 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
7825   return getSignedRange(S).getSignedMax().isNegative();
7826 }
7827 
7828 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
7829   return getSignedRange(S).getSignedMin().isStrictlyPositive();
7830 }
7831 
7832 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
7833   return !getSignedRange(S).getSignedMin().isNegative();
7834 }
7835 
7836 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
7837   return !getSignedRange(S).getSignedMax().isStrictlyPositive();
7838 }
7839 
7840 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
7841   return isKnownNegative(S) || isKnownPositive(S);
7842 }
7843 
7844 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
7845                                        const SCEV *LHS, const SCEV *RHS) {
7846   // Canonicalize the inputs first.
7847   (void)SimplifyICmpOperands(Pred, LHS, RHS);
7848 
7849   // If LHS or RHS is an addrec, check to see if the condition is true in
7850   // every iteration of the loop.
7851   // If LHS and RHS are both addrec, both conditions must be true in
7852   // every iteration of the loop.
7853   const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
7854   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
7855   bool LeftGuarded = false;
7856   bool RightGuarded = false;
7857   if (LAR) {
7858     const Loop *L = LAR->getLoop();
7859     if (isLoopEntryGuardedByCond(L, Pred, LAR->getStart(), RHS) &&
7860         isLoopBackedgeGuardedByCond(L, Pred, LAR->getPostIncExpr(*this), RHS)) {
7861       if (!RAR) return true;
7862       LeftGuarded = true;
7863     }
7864   }
7865   if (RAR) {
7866     const Loop *L = RAR->getLoop();
7867     if (isLoopEntryGuardedByCond(L, Pred, LHS, RAR->getStart()) &&
7868         isLoopBackedgeGuardedByCond(L, Pred, LHS, RAR->getPostIncExpr(*this))) {
7869       if (!LAR) return true;
7870       RightGuarded = true;
7871     }
7872   }
7873   if (LeftGuarded && RightGuarded)
7874     return true;
7875 
7876   if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
7877     return true;
7878 
7879   // Otherwise see what can be done with known constant ranges.
7880   return isKnownPredicateViaConstantRanges(Pred, LHS, RHS);
7881 }
7882 
7883 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS,
7884                                            ICmpInst::Predicate Pred,
7885                                            bool &Increasing) {
7886   bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing);
7887 
7888 #ifndef NDEBUG
7889   // Verify an invariant: inverting the predicate should turn a monotonically
7890   // increasing change to a monotonically decreasing one, and vice versa.
7891   bool IncreasingSwapped;
7892   bool ResultSwapped = isMonotonicPredicateImpl(
7893       LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped);
7894 
7895   assert(Result == ResultSwapped && "should be able to analyze both!");
7896   if (ResultSwapped)
7897     assert(Increasing == !IncreasingSwapped &&
7898            "monotonicity should flip as we flip the predicate");
7899 #endif
7900 
7901   return Result;
7902 }
7903 
7904 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS,
7905                                                ICmpInst::Predicate Pred,
7906                                                bool &Increasing) {
7907 
7908   // A zero step value for LHS means the induction variable is essentially a
7909   // loop invariant value. We don't really depend on the predicate actually
7910   // flipping from false to true (for increasing predicates, and the other way
7911   // around for decreasing predicates), all we care about is that *if* the
7912   // predicate changes then it only changes from false to true.
7913   //
7914   // A zero step value in itself is not very useful, but there may be places
7915   // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
7916   // as general as possible.
7917 
7918   switch (Pred) {
7919   default:
7920     return false; // Conservative answer
7921 
7922   case ICmpInst::ICMP_UGT:
7923   case ICmpInst::ICMP_UGE:
7924   case ICmpInst::ICMP_ULT:
7925   case ICmpInst::ICMP_ULE:
7926     if (!LHS->hasNoUnsignedWrap())
7927       return false;
7928 
7929     Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE;
7930     return true;
7931 
7932   case ICmpInst::ICMP_SGT:
7933   case ICmpInst::ICMP_SGE:
7934   case ICmpInst::ICMP_SLT:
7935   case ICmpInst::ICMP_SLE: {
7936     if (!LHS->hasNoSignedWrap())
7937       return false;
7938 
7939     const SCEV *Step = LHS->getStepRecurrence(*this);
7940 
7941     if (isKnownNonNegative(Step)) {
7942       Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE;
7943       return true;
7944     }
7945 
7946     if (isKnownNonPositive(Step)) {
7947       Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE;
7948       return true;
7949     }
7950 
7951     return false;
7952   }
7953 
7954   }
7955 
7956   llvm_unreachable("switch has default clause!");
7957 }
7958 
7959 bool ScalarEvolution::isLoopInvariantPredicate(
7960     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
7961     ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS,
7962     const SCEV *&InvariantRHS) {
7963 
7964   // If there is a loop-invariant, force it into the RHS, otherwise bail out.
7965   if (!isLoopInvariant(RHS, L)) {
7966     if (!isLoopInvariant(LHS, L))
7967       return false;
7968 
7969     std::swap(LHS, RHS);
7970     Pred = ICmpInst::getSwappedPredicate(Pred);
7971   }
7972 
7973   const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
7974   if (!ArLHS || ArLHS->getLoop() != L)
7975     return false;
7976 
7977   bool Increasing;
7978   if (!isMonotonicPredicate(ArLHS, Pred, Increasing))
7979     return false;
7980 
7981   // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
7982   // true as the loop iterates, and the backedge is control dependent on
7983   // "ArLHS `Pred` RHS" == true then we can reason as follows:
7984   //
7985   //   * if the predicate was false in the first iteration then the predicate
7986   //     is never evaluated again, since the loop exits without taking the
7987   //     backedge.
7988   //   * if the predicate was true in the first iteration then it will
7989   //     continue to be true for all future iterations since it is
7990   //     monotonically increasing.
7991   //
7992   // For both the above possibilities, we can replace the loop varying
7993   // predicate with its value on the first iteration of the loop (which is
7994   // loop invariant).
7995   //
7996   // A similar reasoning applies for a monotonically decreasing predicate, by
7997   // replacing true with false and false with true in the above two bullets.
7998 
7999   auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
8000 
8001   if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
8002     return false;
8003 
8004   InvariantPred = Pred;
8005   InvariantLHS = ArLHS->getStart();
8006   InvariantRHS = RHS;
8007   return true;
8008 }
8009 
8010 bool ScalarEvolution::isKnownPredicateViaConstantRanges(
8011     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
8012   if (HasSameValue(LHS, RHS))
8013     return ICmpInst::isTrueWhenEqual(Pred);
8014 
8015   // This code is split out from isKnownPredicate because it is called from
8016   // within isLoopEntryGuardedByCond.
8017 
8018   auto CheckRanges =
8019       [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) {
8020     return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS)
8021         .contains(RangeLHS);
8022   };
8023 
8024   // The check at the top of the function catches the case where the values are
8025   // known to be equal.
8026   if (Pred == CmpInst::ICMP_EQ)
8027     return false;
8028 
8029   if (Pred == CmpInst::ICMP_NE)
8030     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) ||
8031            CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) ||
8032            isKnownNonZero(getMinusSCEV(LHS, RHS));
8033 
8034   if (CmpInst::isSigned(Pred))
8035     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS));
8036 
8037   return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS));
8038 }
8039 
8040 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
8041                                                     const SCEV *LHS,
8042                                                     const SCEV *RHS) {
8043 
8044   // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer.
8045   // Return Y via OutY.
8046   auto MatchBinaryAddToConst =
8047       [this](const SCEV *Result, const SCEV *X, APInt &OutY,
8048              SCEV::NoWrapFlags ExpectedFlags) {
8049     const SCEV *NonConstOp, *ConstOp;
8050     SCEV::NoWrapFlags FlagsPresent;
8051 
8052     if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) ||
8053         !isa<SCEVConstant>(ConstOp) || NonConstOp != X)
8054       return false;
8055 
8056     OutY = cast<SCEVConstant>(ConstOp)->getAPInt();
8057     return (FlagsPresent & ExpectedFlags) == ExpectedFlags;
8058   };
8059 
8060   APInt C;
8061 
8062   switch (Pred) {
8063   default:
8064     break;
8065 
8066   case ICmpInst::ICMP_SGE:
8067     std::swap(LHS, RHS);
8068   case ICmpInst::ICMP_SLE:
8069     // X s<= (X + C)<nsw> if C >= 0
8070     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative())
8071       return true;
8072 
8073     // (X + C)<nsw> s<= X if C <= 0
8074     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) &&
8075         !C.isStrictlyPositive())
8076       return true;
8077     break;
8078 
8079   case ICmpInst::ICMP_SGT:
8080     std::swap(LHS, RHS);
8081   case ICmpInst::ICMP_SLT:
8082     // X s< (X + C)<nsw> if C > 0
8083     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) &&
8084         C.isStrictlyPositive())
8085       return true;
8086 
8087     // (X + C)<nsw> s< X if C < 0
8088     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative())
8089       return true;
8090     break;
8091   }
8092 
8093   return false;
8094 }
8095 
8096 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
8097                                                    const SCEV *LHS,
8098                                                    const SCEV *RHS) {
8099   if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
8100     return false;
8101 
8102   // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
8103   // the stack can result in exponential time complexity.
8104   SaveAndRestore<bool> Restore(ProvingSplitPredicate, true);
8105 
8106   // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
8107   //
8108   // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
8109   // isKnownPredicate.  isKnownPredicate is more powerful, but also more
8110   // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
8111   // interesting cases seen in practice.  We can consider "upgrading" L >= 0 to
8112   // use isKnownPredicate later if needed.
8113   return isKnownNonNegative(RHS) &&
8114          isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
8115          isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
8116 }
8117 
8118 bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB,
8119                                         ICmpInst::Predicate Pred,
8120                                         const SCEV *LHS, const SCEV *RHS) {
8121   // No need to even try if we know the module has no guards.
8122   if (!HasGuards)
8123     return false;
8124 
8125   return any_of(*BB, [&](Instruction &I) {
8126     using namespace llvm::PatternMatch;
8127 
8128     Value *Condition;
8129     return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
8130                          m_Value(Condition))) &&
8131            isImpliedCond(Pred, LHS, RHS, Condition, false);
8132   });
8133 }
8134 
8135 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
8136 /// protected by a conditional between LHS and RHS.  This is used to
8137 /// to eliminate casts.
8138 bool
8139 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
8140                                              ICmpInst::Predicate Pred,
8141                                              const SCEV *LHS, const SCEV *RHS) {
8142   // Interpret a null as meaning no loop, where there is obviously no guard
8143   // (interprocedural conditions notwithstanding).
8144   if (!L) return true;
8145 
8146   if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS))
8147     return true;
8148 
8149   BasicBlock *Latch = L->getLoopLatch();
8150   if (!Latch)
8151     return false;
8152 
8153   BranchInst *LoopContinuePredicate =
8154     dyn_cast<BranchInst>(Latch->getTerminator());
8155   if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
8156       isImpliedCond(Pred, LHS, RHS,
8157                     LoopContinuePredicate->getCondition(),
8158                     LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
8159     return true;
8160 
8161   // We don't want more than one activation of the following loops on the stack
8162   // -- that can lead to O(n!) time complexity.
8163   if (WalkingBEDominatingConds)
8164     return false;
8165 
8166   SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true);
8167 
8168   // See if we can exploit a trip count to prove the predicate.
8169   const auto &BETakenInfo = getBackedgeTakenInfo(L);
8170   const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
8171   if (LatchBECount != getCouldNotCompute()) {
8172     // We know that Latch branches back to the loop header exactly
8173     // LatchBECount times.  This means the backdege condition at Latch is
8174     // equivalent to  "{0,+,1} u< LatchBECount".
8175     Type *Ty = LatchBECount->getType();
8176     auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
8177     const SCEV *LoopCounter =
8178       getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
8179     if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
8180                       LatchBECount))
8181       return true;
8182   }
8183 
8184   // Check conditions due to any @llvm.assume intrinsics.
8185   for (auto &AssumeVH : AC.assumptions()) {
8186     if (!AssumeVH)
8187       continue;
8188     auto *CI = cast<CallInst>(AssumeVH);
8189     if (!DT.dominates(CI, Latch->getTerminator()))
8190       continue;
8191 
8192     if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
8193       return true;
8194   }
8195 
8196   // If the loop is not reachable from the entry block, we risk running into an
8197   // infinite loop as we walk up into the dom tree.  These loops do not matter
8198   // anyway, so we just return a conservative answer when we see them.
8199   if (!DT.isReachableFromEntry(L->getHeader()))
8200     return false;
8201 
8202   if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
8203     return true;
8204 
8205   for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
8206        DTN != HeaderDTN; DTN = DTN->getIDom()) {
8207 
8208     assert(DTN && "should reach the loop header before reaching the root!");
8209 
8210     BasicBlock *BB = DTN->getBlock();
8211     if (isImpliedViaGuard(BB, Pred, LHS, RHS))
8212       return true;
8213 
8214     BasicBlock *PBB = BB->getSinglePredecessor();
8215     if (!PBB)
8216       continue;
8217 
8218     BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
8219     if (!ContinuePredicate || !ContinuePredicate->isConditional())
8220       continue;
8221 
8222     Value *Condition = ContinuePredicate->getCondition();
8223 
8224     // If we have an edge `E` within the loop body that dominates the only
8225     // latch, the condition guarding `E` also guards the backedge.  This
8226     // reasoning works only for loops with a single latch.
8227 
8228     BasicBlockEdge DominatingEdge(PBB, BB);
8229     if (DominatingEdge.isSingleEdge()) {
8230       // We're constructively (and conservatively) enumerating edges within the
8231       // loop body that dominate the latch.  The dominator tree better agree
8232       // with us on this:
8233       assert(DT.dominates(DominatingEdge, Latch) && "should be!");
8234 
8235       if (isImpliedCond(Pred, LHS, RHS, Condition,
8236                         BB != ContinuePredicate->getSuccessor(0)))
8237         return true;
8238     }
8239   }
8240 
8241   return false;
8242 }
8243 
8244 bool
8245 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
8246                                           ICmpInst::Predicate Pred,
8247                                           const SCEV *LHS, const SCEV *RHS) {
8248   // Interpret a null as meaning no loop, where there is obviously no guard
8249   // (interprocedural conditions notwithstanding).
8250   if (!L) return false;
8251 
8252   if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS))
8253     return true;
8254 
8255   // Starting at the loop predecessor, climb up the predecessor chain, as long
8256   // as there are predecessors that can be found that have unique successors
8257   // leading to the original header.
8258   for (std::pair<BasicBlock *, BasicBlock *>
8259          Pair(L->getLoopPredecessor(), L->getHeader());
8260        Pair.first;
8261        Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
8262 
8263     if (isImpliedViaGuard(Pair.first, Pred, LHS, RHS))
8264       return true;
8265 
8266     BranchInst *LoopEntryPredicate =
8267       dyn_cast<BranchInst>(Pair.first->getTerminator());
8268     if (!LoopEntryPredicate ||
8269         LoopEntryPredicate->isUnconditional())
8270       continue;
8271 
8272     if (isImpliedCond(Pred, LHS, RHS,
8273                       LoopEntryPredicate->getCondition(),
8274                       LoopEntryPredicate->getSuccessor(0) != Pair.second))
8275       return true;
8276   }
8277 
8278   // Check conditions due to any @llvm.assume intrinsics.
8279   for (auto &AssumeVH : AC.assumptions()) {
8280     if (!AssumeVH)
8281       continue;
8282     auto *CI = cast<CallInst>(AssumeVH);
8283     if (!DT.dominates(CI, L->getHeader()))
8284       continue;
8285 
8286     if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
8287       return true;
8288   }
8289 
8290   return false;
8291 }
8292 
8293 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
8294                                     const SCEV *LHS, const SCEV *RHS,
8295                                     Value *FoundCondValue,
8296                                     bool Inverse) {
8297   if (!PendingLoopPredicates.insert(FoundCondValue).second)
8298     return false;
8299 
8300   auto ClearOnExit =
8301       make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
8302 
8303   // Recursively handle And and Or conditions.
8304   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
8305     if (BO->getOpcode() == Instruction::And) {
8306       if (!Inverse)
8307         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
8308                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
8309     } else if (BO->getOpcode() == Instruction::Or) {
8310       if (Inverse)
8311         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
8312                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
8313     }
8314   }
8315 
8316   ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
8317   if (!ICI) return false;
8318 
8319   // Now that we found a conditional branch that dominates the loop or controls
8320   // the loop latch. Check to see if it is the comparison we are looking for.
8321   ICmpInst::Predicate FoundPred;
8322   if (Inverse)
8323     FoundPred = ICI->getInversePredicate();
8324   else
8325     FoundPred = ICI->getPredicate();
8326 
8327   const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
8328   const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
8329 
8330   return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS);
8331 }
8332 
8333 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
8334                                     const SCEV *RHS,
8335                                     ICmpInst::Predicate FoundPred,
8336                                     const SCEV *FoundLHS,
8337                                     const SCEV *FoundRHS) {
8338   // Balance the types.
8339   if (getTypeSizeInBits(LHS->getType()) <
8340       getTypeSizeInBits(FoundLHS->getType())) {
8341     if (CmpInst::isSigned(Pred)) {
8342       LHS = getSignExtendExpr(LHS, FoundLHS->getType());
8343       RHS = getSignExtendExpr(RHS, FoundLHS->getType());
8344     } else {
8345       LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
8346       RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
8347     }
8348   } else if (getTypeSizeInBits(LHS->getType()) >
8349       getTypeSizeInBits(FoundLHS->getType())) {
8350     if (CmpInst::isSigned(FoundPred)) {
8351       FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
8352       FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
8353     } else {
8354       FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
8355       FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
8356     }
8357   }
8358 
8359   // Canonicalize the query to match the way instcombine will have
8360   // canonicalized the comparison.
8361   if (SimplifyICmpOperands(Pred, LHS, RHS))
8362     if (LHS == RHS)
8363       return CmpInst::isTrueWhenEqual(Pred);
8364   if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
8365     if (FoundLHS == FoundRHS)
8366       return CmpInst::isFalseWhenEqual(FoundPred);
8367 
8368   // Check to see if we can make the LHS or RHS match.
8369   if (LHS == FoundRHS || RHS == FoundLHS) {
8370     if (isa<SCEVConstant>(RHS)) {
8371       std::swap(FoundLHS, FoundRHS);
8372       FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
8373     } else {
8374       std::swap(LHS, RHS);
8375       Pred = ICmpInst::getSwappedPredicate(Pred);
8376     }
8377   }
8378 
8379   // Check whether the found predicate is the same as the desired predicate.
8380   if (FoundPred == Pred)
8381     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
8382 
8383   // Check whether swapping the found predicate makes it the same as the
8384   // desired predicate.
8385   if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
8386     if (isa<SCEVConstant>(RHS))
8387       return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
8388     else
8389       return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
8390                                    RHS, LHS, FoundLHS, FoundRHS);
8391   }
8392 
8393   // Unsigned comparison is the same as signed comparison when both the operands
8394   // are non-negative.
8395   if (CmpInst::isUnsigned(FoundPred) &&
8396       CmpInst::getSignedPredicate(FoundPred) == Pred &&
8397       isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS))
8398     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
8399 
8400   // Check if we can make progress by sharpening ranges.
8401   if (FoundPred == ICmpInst::ICMP_NE &&
8402       (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
8403 
8404     const SCEVConstant *C = nullptr;
8405     const SCEV *V = nullptr;
8406 
8407     if (isa<SCEVConstant>(FoundLHS)) {
8408       C = cast<SCEVConstant>(FoundLHS);
8409       V = FoundRHS;
8410     } else {
8411       C = cast<SCEVConstant>(FoundRHS);
8412       V = FoundLHS;
8413     }
8414 
8415     // The guarding predicate tells us that C != V. If the known range
8416     // of V is [C, t), we can sharpen the range to [C + 1, t).  The
8417     // range we consider has to correspond to same signedness as the
8418     // predicate we're interested in folding.
8419 
8420     APInt Min = ICmpInst::isSigned(Pred) ?
8421         getSignedRange(V).getSignedMin() : getUnsignedRange(V).getUnsignedMin();
8422 
8423     if (Min == C->getAPInt()) {
8424       // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
8425       // This is true even if (Min + 1) wraps around -- in case of
8426       // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
8427 
8428       APInt SharperMin = Min + 1;
8429 
8430       switch (Pred) {
8431         case ICmpInst::ICMP_SGE:
8432         case ICmpInst::ICMP_UGE:
8433           // We know V `Pred` SharperMin.  If this implies LHS `Pred`
8434           // RHS, we're done.
8435           if (isImpliedCondOperands(Pred, LHS, RHS, V,
8436                                     getConstant(SharperMin)))
8437             return true;
8438 
8439         case ICmpInst::ICMP_SGT:
8440         case ICmpInst::ICMP_UGT:
8441           // We know from the range information that (V `Pred` Min ||
8442           // V == Min).  We know from the guarding condition that !(V
8443           // == Min).  This gives us
8444           //
8445           //       V `Pred` Min || V == Min && !(V == Min)
8446           //   =>  V `Pred` Min
8447           //
8448           // If V `Pred` Min implies LHS `Pred` RHS, we're done.
8449 
8450           if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min)))
8451             return true;
8452 
8453         default:
8454           // No change
8455           break;
8456       }
8457     }
8458   }
8459 
8460   // Check whether the actual condition is beyond sufficient.
8461   if (FoundPred == ICmpInst::ICMP_EQ)
8462     if (ICmpInst::isTrueWhenEqual(Pred))
8463       if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
8464         return true;
8465   if (Pred == ICmpInst::ICMP_NE)
8466     if (!ICmpInst::isTrueWhenEqual(FoundPred))
8467       if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
8468         return true;
8469 
8470   // Otherwise assume the worst.
8471   return false;
8472 }
8473 
8474 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
8475                                      const SCEV *&L, const SCEV *&R,
8476                                      SCEV::NoWrapFlags &Flags) {
8477   const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
8478   if (!AE || AE->getNumOperands() != 2)
8479     return false;
8480 
8481   L = AE->getOperand(0);
8482   R = AE->getOperand(1);
8483   Flags = AE->getNoWrapFlags();
8484   return true;
8485 }
8486 
8487 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More,
8488                                                            const SCEV *Less) {
8489   // We avoid subtracting expressions here because this function is usually
8490   // fairly deep in the call stack (i.e. is called many times).
8491 
8492   if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
8493     const auto *LAR = cast<SCEVAddRecExpr>(Less);
8494     const auto *MAR = cast<SCEVAddRecExpr>(More);
8495 
8496     if (LAR->getLoop() != MAR->getLoop())
8497       return None;
8498 
8499     // We look at affine expressions only; not for correctness but to keep
8500     // getStepRecurrence cheap.
8501     if (!LAR->isAffine() || !MAR->isAffine())
8502       return None;
8503 
8504     if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
8505       return None;
8506 
8507     Less = LAR->getStart();
8508     More = MAR->getStart();
8509 
8510     // fall through
8511   }
8512 
8513   if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
8514     const auto &M = cast<SCEVConstant>(More)->getAPInt();
8515     const auto &L = cast<SCEVConstant>(Less)->getAPInt();
8516     return M - L;
8517   }
8518 
8519   const SCEV *L, *R;
8520   SCEV::NoWrapFlags Flags;
8521   if (splitBinaryAdd(Less, L, R, Flags))
8522     if (const auto *LC = dyn_cast<SCEVConstant>(L))
8523       if (R == More)
8524         return -(LC->getAPInt());
8525 
8526   if (splitBinaryAdd(More, L, R, Flags))
8527     if (const auto *LC = dyn_cast<SCEVConstant>(L))
8528       if (R == Less)
8529         return LC->getAPInt();
8530 
8531   return None;
8532 }
8533 
8534 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
8535     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
8536     const SCEV *FoundLHS, const SCEV *FoundRHS) {
8537   if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
8538     return false;
8539 
8540   const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
8541   if (!AddRecLHS)
8542     return false;
8543 
8544   const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
8545   if (!AddRecFoundLHS)
8546     return false;
8547 
8548   // We'd like to let SCEV reason about control dependencies, so we constrain
8549   // both the inequalities to be about add recurrences on the same loop.  This
8550   // way we can use isLoopEntryGuardedByCond later.
8551 
8552   const Loop *L = AddRecFoundLHS->getLoop();
8553   if (L != AddRecLHS->getLoop())
8554     return false;
8555 
8556   //  FoundLHS u< FoundRHS u< -C =>  (FoundLHS + C) u< (FoundRHS + C) ... (1)
8557   //
8558   //  FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
8559   //                                                                  ... (2)
8560   //
8561   // Informal proof for (2), assuming (1) [*]:
8562   //
8563   // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
8564   //
8565   // Then
8566   //
8567   //       FoundLHS s< FoundRHS s< INT_MIN - C
8568   // <=>  (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C   [ using (3) ]
8569   // <=>  (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
8570   // <=>  (FoundLHS + INT_MIN + C + INT_MIN) s<
8571   //                        (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
8572   // <=>  FoundLHS + C s< FoundRHS + C
8573   //
8574   // [*]: (1) can be proved by ruling out overflow.
8575   //
8576   // [**]: This can be proved by analyzing all the four possibilities:
8577   //    (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
8578   //    (A s>= 0, B s>= 0).
8579   //
8580   // Note:
8581   // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
8582   // will not sign underflow.  For instance, say FoundLHS = (i8 -128), FoundRHS
8583   // = (i8 -127) and C = (i8 -100).  Then INT_MIN - C = (i8 -28), and FoundRHS
8584   // s< (INT_MIN - C).  Lack of sign overflow / underflow in "FoundRHS + C" is
8585   // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
8586   // C)".
8587 
8588   Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
8589   Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
8590   if (!LDiff || !RDiff || *LDiff != *RDiff)
8591     return false;
8592 
8593   if (LDiff->isMinValue())
8594     return true;
8595 
8596   APInt FoundRHSLimit;
8597 
8598   if (Pred == CmpInst::ICMP_ULT) {
8599     FoundRHSLimit = -(*RDiff);
8600   } else {
8601     assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
8602     FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
8603   }
8604 
8605   // Try to prove (1) or (2), as needed.
8606   return isLoopEntryGuardedByCond(L, Pred, FoundRHS,
8607                                   getConstant(FoundRHSLimit));
8608 }
8609 
8610 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
8611                                             const SCEV *LHS, const SCEV *RHS,
8612                                             const SCEV *FoundLHS,
8613                                             const SCEV *FoundRHS) {
8614   if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
8615     return true;
8616 
8617   if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
8618     return true;
8619 
8620   return isImpliedCondOperandsHelper(Pred, LHS, RHS,
8621                                      FoundLHS, FoundRHS) ||
8622          // ~x < ~y --> x > y
8623          isImpliedCondOperandsHelper(Pred, LHS, RHS,
8624                                      getNotSCEV(FoundRHS),
8625                                      getNotSCEV(FoundLHS));
8626 }
8627 
8628 
8629 /// If Expr computes ~A, return A else return nullptr
8630 static const SCEV *MatchNotExpr(const SCEV *Expr) {
8631   const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
8632   if (!Add || Add->getNumOperands() != 2 ||
8633       !Add->getOperand(0)->isAllOnesValue())
8634     return nullptr;
8635 
8636   const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
8637   if (!AddRHS || AddRHS->getNumOperands() != 2 ||
8638       !AddRHS->getOperand(0)->isAllOnesValue())
8639     return nullptr;
8640 
8641   return AddRHS->getOperand(1);
8642 }
8643 
8644 
8645 /// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values?
8646 template<typename MaxExprType>
8647 static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr,
8648                               const SCEV *Candidate) {
8649   const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr);
8650   if (!MaxExpr) return false;
8651 
8652   return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end();
8653 }
8654 
8655 
8656 /// Is MaybeMinExpr an SMin or UMin of Candidate and some other values?
8657 template<typename MaxExprType>
8658 static bool IsMinConsistingOf(ScalarEvolution &SE,
8659                               const SCEV *MaybeMinExpr,
8660                               const SCEV *Candidate) {
8661   const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr);
8662   if (!MaybeMaxExpr)
8663     return false;
8664 
8665   return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate));
8666 }
8667 
8668 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
8669                                            ICmpInst::Predicate Pred,
8670                                            const SCEV *LHS, const SCEV *RHS) {
8671 
8672   // If both sides are affine addrecs for the same loop, with equal
8673   // steps, and we know the recurrences don't wrap, then we only
8674   // need to check the predicate on the starting values.
8675 
8676   if (!ICmpInst::isRelational(Pred))
8677     return false;
8678 
8679   const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
8680   if (!LAR)
8681     return false;
8682   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
8683   if (!RAR)
8684     return false;
8685   if (LAR->getLoop() != RAR->getLoop())
8686     return false;
8687   if (!LAR->isAffine() || !RAR->isAffine())
8688     return false;
8689 
8690   if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
8691     return false;
8692 
8693   SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
8694                          SCEV::FlagNSW : SCEV::FlagNUW;
8695   if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
8696     return false;
8697 
8698   return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
8699 }
8700 
8701 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
8702 /// expression?
8703 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
8704                                         ICmpInst::Predicate Pred,
8705                                         const SCEV *LHS, const SCEV *RHS) {
8706   switch (Pred) {
8707   default:
8708     return false;
8709 
8710   case ICmpInst::ICMP_SGE:
8711     std::swap(LHS, RHS);
8712     LLVM_FALLTHROUGH;
8713   case ICmpInst::ICMP_SLE:
8714     return
8715       // min(A, ...) <= A
8716       IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) ||
8717       // A <= max(A, ...)
8718       IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
8719 
8720   case ICmpInst::ICMP_UGE:
8721     std::swap(LHS, RHS);
8722     LLVM_FALLTHROUGH;
8723   case ICmpInst::ICMP_ULE:
8724     return
8725       // min(A, ...) <= A
8726       IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) ||
8727       // A <= max(A, ...)
8728       IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
8729   }
8730 
8731   llvm_unreachable("covered switch fell through?!");
8732 }
8733 
8734 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred,
8735                                              const SCEV *LHS, const SCEV *RHS,
8736                                              const SCEV *FoundLHS,
8737                                              const SCEV *FoundRHS,
8738                                              unsigned Depth) {
8739   assert(getTypeSizeInBits(LHS->getType()) ==
8740              getTypeSizeInBits(RHS->getType()) &&
8741          "LHS and RHS have different sizes?");
8742   assert(getTypeSizeInBits(FoundLHS->getType()) ==
8743              getTypeSizeInBits(FoundRHS->getType()) &&
8744          "FoundLHS and FoundRHS have different sizes?");
8745   // We want to avoid hurting the compile time with analysis of too big trees.
8746   if (Depth > MaxSCEVOperationsImplicationDepth)
8747     return false;
8748   // We only want to work with ICMP_SGT comparison so far.
8749   // TODO: Extend to ICMP_UGT?
8750   if (Pred == ICmpInst::ICMP_SLT) {
8751     Pred = ICmpInst::ICMP_SGT;
8752     std::swap(LHS, RHS);
8753     std::swap(FoundLHS, FoundRHS);
8754   }
8755   if (Pred != ICmpInst::ICMP_SGT)
8756     return false;
8757 
8758   auto GetOpFromSExt = [&](const SCEV *S) {
8759     if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
8760       return Ext->getOperand();
8761     // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
8762     // the constant in some cases.
8763     return S;
8764   };
8765 
8766   // Acquire values from extensions.
8767   auto *OrigFoundLHS = FoundLHS;
8768   LHS = GetOpFromSExt(LHS);
8769   FoundLHS = GetOpFromSExt(FoundLHS);
8770 
8771   // Is the SGT predicate can be proved trivially or using the found context.
8772   auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
8773     return isKnownViaSimpleReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
8774            isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
8775                                   FoundRHS, Depth + 1);
8776   };
8777 
8778   if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
8779     // We want to avoid creation of any new non-constant SCEV. Since we are
8780     // going to compare the operands to RHS, we should be certain that we don't
8781     // need any size extensions for this. So let's decline all cases when the
8782     // sizes of types of LHS and RHS do not match.
8783     // TODO: Maybe try to get RHS from sext to catch more cases?
8784     if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType()))
8785       return false;
8786 
8787     // Should not overflow.
8788     if (!LHSAddExpr->hasNoSignedWrap())
8789       return false;
8790 
8791     auto *LL = LHSAddExpr->getOperand(0);
8792     auto *LR = LHSAddExpr->getOperand(1);
8793     auto *MinusOne = getNegativeSCEV(getOne(RHS->getType()));
8794 
8795     // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
8796     auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
8797       return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
8798     };
8799     // Try to prove the following rule:
8800     // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
8801     // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
8802     if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
8803       return true;
8804   } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
8805     Value *LL, *LR;
8806     // FIXME: Once we have SDiv implemented, we can get rid of this matching.
8807     using namespace llvm::PatternMatch;
8808     if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
8809       // Rules for division.
8810       // We are going to perform some comparisons with Denominator and its
8811       // derivative expressions. In general case, creating a SCEV for it may
8812       // lead to a complex analysis of the entire graph, and in particular it
8813       // can request trip count recalculation for the same loop. This would
8814       // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
8815       // this, we only want to create SCEVs that are constants in this section.
8816       // So we bail if Denominator is not a constant.
8817       if (!isa<ConstantInt>(LR))
8818         return false;
8819 
8820       auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
8821 
8822       // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
8823       // then a SCEV for the numerator already exists and matches with FoundLHS.
8824       auto *Numerator = getExistingSCEV(LL);
8825       if (!Numerator || Numerator->getType() != FoundLHS->getType())
8826         return false;
8827 
8828       // Make sure that the numerator matches with FoundLHS and the denominator
8829       // is positive.
8830       if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
8831         return false;
8832 
8833       auto *DTy = Denominator->getType();
8834       auto *FRHSTy = FoundRHS->getType();
8835       if (DTy->isPointerTy() != FRHSTy->isPointerTy())
8836         // One of types is a pointer and another one is not. We cannot extend
8837         // them properly to a wider type, so let us just reject this case.
8838         // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
8839         // to avoid this check.
8840         return false;
8841 
8842       // Given that:
8843       // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
8844       auto *WTy = getWiderType(DTy, FRHSTy);
8845       auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
8846       auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
8847 
8848       // Try to prove the following rule:
8849       // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
8850       // For example, given that FoundLHS > 2. It means that FoundLHS is at
8851       // least 3. If we divide it by Denominator < 4, we will have at least 1.
8852       auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
8853       if (isKnownNonPositive(RHS) &&
8854           IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
8855         return true;
8856 
8857       // Try to prove the following rule:
8858       // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
8859       // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
8860       // If we divide it by Denominator > 2, then:
8861       // 1. If FoundLHS is negative, then the result is 0.
8862       // 2. If FoundLHS is non-negative, then the result is non-negative.
8863       // Anyways, the result is non-negative.
8864       auto *MinusOne = getNegativeSCEV(getOne(WTy));
8865       auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
8866       if (isKnownNegative(RHS) &&
8867           IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
8868         return true;
8869     }
8870   }
8871 
8872   return false;
8873 }
8874 
8875 bool
8876 ScalarEvolution::isKnownViaSimpleReasoning(ICmpInst::Predicate Pred,
8877                                            const SCEV *LHS, const SCEV *RHS) {
8878   return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
8879          IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
8880          IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
8881          isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
8882 }
8883 
8884 bool
8885 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
8886                                              const SCEV *LHS, const SCEV *RHS,
8887                                              const SCEV *FoundLHS,
8888                                              const SCEV *FoundRHS) {
8889   switch (Pred) {
8890   default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
8891   case ICmpInst::ICMP_EQ:
8892   case ICmpInst::ICMP_NE:
8893     if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
8894       return true;
8895     break;
8896   case ICmpInst::ICMP_SLT:
8897   case ICmpInst::ICMP_SLE:
8898     if (isKnownViaSimpleReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
8899         isKnownViaSimpleReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS))
8900       return true;
8901     break;
8902   case ICmpInst::ICMP_SGT:
8903   case ICmpInst::ICMP_SGE:
8904     if (isKnownViaSimpleReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
8905         isKnownViaSimpleReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS))
8906       return true;
8907     break;
8908   case ICmpInst::ICMP_ULT:
8909   case ICmpInst::ICMP_ULE:
8910     if (isKnownViaSimpleReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
8911         isKnownViaSimpleReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS))
8912       return true;
8913     break;
8914   case ICmpInst::ICMP_UGT:
8915   case ICmpInst::ICMP_UGE:
8916     if (isKnownViaSimpleReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
8917         isKnownViaSimpleReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS))
8918       return true;
8919     break;
8920   }
8921 
8922   // Maybe it can be proved via operations?
8923   if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
8924     return true;
8925 
8926   return false;
8927 }
8928 
8929 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
8930                                                      const SCEV *LHS,
8931                                                      const SCEV *RHS,
8932                                                      const SCEV *FoundLHS,
8933                                                      const SCEV *FoundRHS) {
8934   if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
8935     // The restriction on `FoundRHS` be lifted easily -- it exists only to
8936     // reduce the compile time impact of this optimization.
8937     return false;
8938 
8939   Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
8940   if (!Addend)
8941     return false;
8942 
8943   const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
8944 
8945   // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
8946   // antecedent "`FoundLHS` `Pred` `FoundRHS`".
8947   ConstantRange FoundLHSRange =
8948       ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS);
8949 
8950   // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
8951   ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
8952 
8953   // We can also compute the range of values for `LHS` that satisfy the
8954   // consequent, "`LHS` `Pred` `RHS`":
8955   const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
8956   ConstantRange SatisfyingLHSRange =
8957       ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS);
8958 
8959   // The antecedent implies the consequent if every value of `LHS` that
8960   // satisfies the antecedent also satisfies the consequent.
8961   return SatisfyingLHSRange.contains(LHSRange);
8962 }
8963 
8964 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
8965                                          bool IsSigned, bool NoWrap) {
8966   assert(isKnownPositive(Stride) && "Positive stride expected!");
8967 
8968   if (NoWrap) return false;
8969 
8970   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
8971   const SCEV *One = getOne(Stride->getType());
8972 
8973   if (IsSigned) {
8974     APInt MaxRHS = getSignedRange(RHS).getSignedMax();
8975     APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
8976     APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
8977                                 .getSignedMax();
8978 
8979     // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
8980     return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS);
8981   }
8982 
8983   APInt MaxRHS = getUnsignedRange(RHS).getUnsignedMax();
8984   APInt MaxValue = APInt::getMaxValue(BitWidth);
8985   APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
8986                               .getUnsignedMax();
8987 
8988   // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
8989   return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS);
8990 }
8991 
8992 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
8993                                          bool IsSigned, bool NoWrap) {
8994   if (NoWrap) return false;
8995 
8996   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
8997   const SCEV *One = getOne(Stride->getType());
8998 
8999   if (IsSigned) {
9000     APInt MinRHS = getSignedRange(RHS).getSignedMin();
9001     APInt MinValue = APInt::getSignedMinValue(BitWidth);
9002     APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
9003                                .getSignedMax();
9004 
9005     // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
9006     return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS);
9007   }
9008 
9009   APInt MinRHS = getUnsignedRange(RHS).getUnsignedMin();
9010   APInt MinValue = APInt::getMinValue(BitWidth);
9011   APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
9012                             .getUnsignedMax();
9013 
9014   // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
9015   return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS);
9016 }
9017 
9018 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step,
9019                                             bool Equality) {
9020   const SCEV *One = getOne(Step->getType());
9021   Delta = Equality ? getAddExpr(Delta, Step)
9022                    : getAddExpr(Delta, getMinusSCEV(Step, One));
9023   return getUDivExpr(Delta, Step);
9024 }
9025 
9026 ScalarEvolution::ExitLimit
9027 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
9028                                   const Loop *L, bool IsSigned,
9029                                   bool ControlsExit, bool AllowPredicates) {
9030   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
9031   // We handle only IV < Invariant
9032   if (!isLoopInvariant(RHS, L))
9033     return getCouldNotCompute();
9034 
9035   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
9036   bool PredicatedIV = false;
9037 
9038   if (!IV && AllowPredicates) {
9039     // Try to make this an AddRec using runtime tests, in the first X
9040     // iterations of this loop, where X is the SCEV expression found by the
9041     // algorithm below.
9042     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
9043     PredicatedIV = true;
9044   }
9045 
9046   // Avoid weird loops
9047   if (!IV || IV->getLoop() != L || !IV->isAffine())
9048     return getCouldNotCompute();
9049 
9050   bool NoWrap = ControlsExit &&
9051                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
9052 
9053   const SCEV *Stride = IV->getStepRecurrence(*this);
9054 
9055   bool PositiveStride = isKnownPositive(Stride);
9056 
9057   // Avoid negative or zero stride values.
9058   if (!PositiveStride) {
9059     // We can compute the correct backedge taken count for loops with unknown
9060     // strides if we can prove that the loop is not an infinite loop with side
9061     // effects. Here's the loop structure we are trying to handle -
9062     //
9063     // i = start
9064     // do {
9065     //   A[i] = i;
9066     //   i += s;
9067     // } while (i < end);
9068     //
9069     // The backedge taken count for such loops is evaluated as -
9070     // (max(end, start + stride) - start - 1) /u stride
9071     //
9072     // The additional preconditions that we need to check to prove correctness
9073     // of the above formula is as follows -
9074     //
9075     // a) IV is either nuw or nsw depending upon signedness (indicated by the
9076     //    NoWrap flag).
9077     // b) loop is single exit with no side effects.
9078     //
9079     //
9080     // Precondition a) implies that if the stride is negative, this is a single
9081     // trip loop. The backedge taken count formula reduces to zero in this case.
9082     //
9083     // Precondition b) implies that the unknown stride cannot be zero otherwise
9084     // we have UB.
9085     //
9086     // The positive stride case is the same as isKnownPositive(Stride) returning
9087     // true (original behavior of the function).
9088     //
9089     // We want to make sure that the stride is truly unknown as there are edge
9090     // cases where ScalarEvolution propagates no wrap flags to the
9091     // post-increment/decrement IV even though the increment/decrement operation
9092     // itself is wrapping. The computed backedge taken count may be wrong in
9093     // such cases. This is prevented by checking that the stride is not known to
9094     // be either positive or non-positive. For example, no wrap flags are
9095     // propagated to the post-increment IV of this loop with a trip count of 2 -
9096     //
9097     // unsigned char i;
9098     // for(i=127; i<128; i+=129)
9099     //   A[i] = i;
9100     //
9101     if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) ||
9102         !loopHasNoSideEffects(L))
9103       return getCouldNotCompute();
9104 
9105   } else if (!Stride->isOne() &&
9106              doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap))
9107     // Avoid proven overflow cases: this will ensure that the backedge taken
9108     // count will not generate any unsigned overflow. Relaxed no-overflow
9109     // conditions exploit NoWrapFlags, allowing to optimize in presence of
9110     // undefined behaviors like the case of C language.
9111     return getCouldNotCompute();
9112 
9113   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT
9114                                       : ICmpInst::ICMP_ULT;
9115   const SCEV *Start = IV->getStart();
9116   const SCEV *End = RHS;
9117   // If the backedge is taken at least once, then it will be taken
9118   // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start
9119   // is the LHS value of the less-than comparison the first time it is evaluated
9120   // and End is the RHS.
9121   const SCEV *BECountIfBackedgeTaken =
9122     computeBECount(getMinusSCEV(End, Start), Stride, false);
9123   // If the loop entry is guarded by the result of the backedge test of the
9124   // first loop iteration, then we know the backedge will be taken at least
9125   // once and so the backedge taken count is as above. If not then we use the
9126   // expression (max(End,Start)-Start)/Stride to describe the backedge count,
9127   // as if the backedge is taken at least once max(End,Start) is End and so the
9128   // result is as above, and if not max(End,Start) is Start so we get a backedge
9129   // count of zero.
9130   const SCEV *BECount;
9131   if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS))
9132     BECount = BECountIfBackedgeTaken;
9133   else {
9134     End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
9135     BECount = computeBECount(getMinusSCEV(End, Start), Stride, false);
9136   }
9137 
9138   const SCEV *MaxBECount;
9139   bool MaxOrZero = false;
9140   if (isa<SCEVConstant>(BECount))
9141     MaxBECount = BECount;
9142   else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) {
9143     // If we know exactly how many times the backedge will be taken if it's
9144     // taken at least once, then the backedge count will either be that or
9145     // zero.
9146     MaxBECount = BECountIfBackedgeTaken;
9147     MaxOrZero = true;
9148   } else {
9149     // Calculate the maximum backedge count based on the range of values
9150     // permitted by Start, End, and Stride.
9151     APInt MinStart = IsSigned ? getSignedRange(Start).getSignedMin()
9152                               : getUnsignedRange(Start).getUnsignedMin();
9153 
9154     unsigned BitWidth = getTypeSizeInBits(LHS->getType());
9155 
9156     APInt StrideForMaxBECount;
9157 
9158     if (PositiveStride)
9159       StrideForMaxBECount =
9160         IsSigned ? getSignedRange(Stride).getSignedMin()
9161                  : getUnsignedRange(Stride).getUnsignedMin();
9162     else
9163       // Using a stride of 1 is safe when computing max backedge taken count for
9164       // a loop with unknown stride.
9165       StrideForMaxBECount = APInt(BitWidth, 1, IsSigned);
9166 
9167     APInt Limit =
9168       IsSigned ? APInt::getSignedMaxValue(BitWidth) - (StrideForMaxBECount - 1)
9169                : APInt::getMaxValue(BitWidth) - (StrideForMaxBECount - 1);
9170 
9171     // Although End can be a MAX expression we estimate MaxEnd considering only
9172     // the case End = RHS. This is safe because in the other case (End - Start)
9173     // is zero, leading to a zero maximum backedge taken count.
9174     APInt MaxEnd =
9175       IsSigned ? APIntOps::smin(getSignedRange(RHS).getSignedMax(), Limit)
9176                : APIntOps::umin(getUnsignedRange(RHS).getUnsignedMax(), Limit);
9177 
9178     MaxBECount = computeBECount(getConstant(MaxEnd - MinStart),
9179                                 getConstant(StrideForMaxBECount), false);
9180   }
9181 
9182   if (isa<SCEVCouldNotCompute>(MaxBECount))
9183     MaxBECount = BECount;
9184 
9185   return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates);
9186 }
9187 
9188 ScalarEvolution::ExitLimit
9189 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
9190                                      const Loop *L, bool IsSigned,
9191                                      bool ControlsExit, bool AllowPredicates) {
9192   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
9193   // We handle only IV > Invariant
9194   if (!isLoopInvariant(RHS, L))
9195     return getCouldNotCompute();
9196 
9197   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
9198   if (!IV && AllowPredicates)
9199     // Try to make this an AddRec using runtime tests, in the first X
9200     // iterations of this loop, where X is the SCEV expression found by the
9201     // algorithm below.
9202     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
9203 
9204   // Avoid weird loops
9205   if (!IV || IV->getLoop() != L || !IV->isAffine())
9206     return getCouldNotCompute();
9207 
9208   bool NoWrap = ControlsExit &&
9209                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
9210 
9211   const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
9212 
9213   // Avoid negative or zero stride values
9214   if (!isKnownPositive(Stride))
9215     return getCouldNotCompute();
9216 
9217   // Avoid proven overflow cases: this will ensure that the backedge taken count
9218   // will not generate any unsigned overflow. Relaxed no-overflow conditions
9219   // exploit NoWrapFlags, allowing to optimize in presence of undefined
9220   // behaviors like the case of C language.
9221   if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap))
9222     return getCouldNotCompute();
9223 
9224   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT
9225                                       : ICmpInst::ICMP_UGT;
9226 
9227   const SCEV *Start = IV->getStart();
9228   const SCEV *End = RHS;
9229   if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS))
9230     End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
9231 
9232   const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false);
9233 
9234   APInt MaxStart = IsSigned ? getSignedRange(Start).getSignedMax()
9235                             : getUnsignedRange(Start).getUnsignedMax();
9236 
9237   APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin()
9238                              : getUnsignedRange(Stride).getUnsignedMin();
9239 
9240   unsigned BitWidth = getTypeSizeInBits(LHS->getType());
9241   APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
9242                          : APInt::getMinValue(BitWidth) + (MinStride - 1);
9243 
9244   // Although End can be a MIN expression we estimate MinEnd considering only
9245   // the case End = RHS. This is safe because in the other case (Start - End)
9246   // is zero, leading to a zero maximum backedge taken count.
9247   APInt MinEnd =
9248     IsSigned ? APIntOps::smax(getSignedRange(RHS).getSignedMin(), Limit)
9249              : APIntOps::umax(getUnsignedRange(RHS).getUnsignedMin(), Limit);
9250 
9251 
9252   const SCEV *MaxBECount = getCouldNotCompute();
9253   if (isa<SCEVConstant>(BECount))
9254     MaxBECount = BECount;
9255   else
9256     MaxBECount = computeBECount(getConstant(MaxStart - MinEnd),
9257                                 getConstant(MinStride), false);
9258 
9259   if (isa<SCEVCouldNotCompute>(MaxBECount))
9260     MaxBECount = BECount;
9261 
9262   return ExitLimit(BECount, MaxBECount, false, Predicates);
9263 }
9264 
9265 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range,
9266                                                     ScalarEvolution &SE) const {
9267   if (Range.isFullSet())  // Infinite loop.
9268     return SE.getCouldNotCompute();
9269 
9270   // If the start is a non-zero constant, shift the range to simplify things.
9271   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
9272     if (!SC->getValue()->isZero()) {
9273       SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
9274       Operands[0] = SE.getZero(SC->getType());
9275       const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
9276                                              getNoWrapFlags(FlagNW));
9277       if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
9278         return ShiftedAddRec->getNumIterationsInRange(
9279             Range.subtract(SC->getAPInt()), SE);
9280       // This is strange and shouldn't happen.
9281       return SE.getCouldNotCompute();
9282     }
9283 
9284   // The only time we can solve this is when we have all constant indices.
9285   // Otherwise, we cannot determine the overflow conditions.
9286   if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
9287     return SE.getCouldNotCompute();
9288 
9289   // Okay at this point we know that all elements of the chrec are constants and
9290   // that the start element is zero.
9291 
9292   // First check to see if the range contains zero.  If not, the first
9293   // iteration exits.
9294   unsigned BitWidth = SE.getTypeSizeInBits(getType());
9295   if (!Range.contains(APInt(BitWidth, 0)))
9296     return SE.getZero(getType());
9297 
9298   if (isAffine()) {
9299     // If this is an affine expression then we have this situation:
9300     //   Solve {0,+,A} in Range  ===  Ax in Range
9301 
9302     // We know that zero is in the range.  If A is positive then we know that
9303     // the upper value of the range must be the first possible exit value.
9304     // If A is negative then the lower of the range is the last possible loop
9305     // value.  Also note that we already checked for a full range.
9306     APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
9307     APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower();
9308 
9309     // The exit value should be (End+A)/A.
9310     APInt ExitVal = (End + A).udiv(A);
9311     ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
9312 
9313     // Evaluate at the exit value.  If we really did fall out of the valid
9314     // range, then we computed our trip count, otherwise wrap around or other
9315     // things must have happened.
9316     ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
9317     if (Range.contains(Val->getValue()))
9318       return SE.getCouldNotCompute();  // Something strange happened
9319 
9320     // Ensure that the previous value is in the range.  This is a sanity check.
9321     assert(Range.contains(
9322            EvaluateConstantChrecAtConstant(this,
9323            ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&
9324            "Linear scev computation is off in a bad way!");
9325     return SE.getConstant(ExitValue);
9326   } else if (isQuadratic()) {
9327     // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
9328     // quadratic equation to solve it.  To do this, we must frame our problem in
9329     // terms of figuring out when zero is crossed, instead of when
9330     // Range.getUpper() is crossed.
9331     SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
9332     NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
9333     const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(), FlagAnyWrap);
9334 
9335     // Next, solve the constructed addrec
9336     if (auto Roots =
9337             SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE)) {
9338       const SCEVConstant *R1 = Roots->first;
9339       const SCEVConstant *R2 = Roots->second;
9340       // Pick the smallest positive root value.
9341       if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
9342               ICmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
9343         if (!CB->getZExtValue())
9344           std::swap(R1, R2); // R1 is the minimum root now.
9345 
9346         // Make sure the root is not off by one.  The returned iteration should
9347         // not be in the range, but the previous one should be.  When solving
9348         // for "X*X < 5", for example, we should not return a root of 2.
9349         ConstantInt *R1Val =
9350             EvaluateConstantChrecAtConstant(this, R1->getValue(), SE);
9351         if (Range.contains(R1Val->getValue())) {
9352           // The next iteration must be out of the range...
9353           ConstantInt *NextVal =
9354               ConstantInt::get(SE.getContext(), R1->getAPInt() + 1);
9355 
9356           R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
9357           if (!Range.contains(R1Val->getValue()))
9358             return SE.getConstant(NextVal);
9359           return SE.getCouldNotCompute(); // Something strange happened
9360         }
9361 
9362         // If R1 was not in the range, then it is a good return value.  Make
9363         // sure that R1-1 WAS in the range though, just in case.
9364         ConstantInt *NextVal =
9365             ConstantInt::get(SE.getContext(), R1->getAPInt() - 1);
9366         R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
9367         if (Range.contains(R1Val->getValue()))
9368           return R1;
9369         return SE.getCouldNotCompute(); // Something strange happened
9370       }
9371     }
9372   }
9373 
9374   return SE.getCouldNotCompute();
9375 }
9376 
9377 // Return true when S contains at least an undef value.
9378 static inline bool containsUndefs(const SCEV *S) {
9379   return SCEVExprContains(S, [](const SCEV *S) {
9380     if (const auto *SU = dyn_cast<SCEVUnknown>(S))
9381       return isa<UndefValue>(SU->getValue());
9382     else if (const auto *SC = dyn_cast<SCEVConstant>(S))
9383       return isa<UndefValue>(SC->getValue());
9384     return false;
9385   });
9386 }
9387 
9388 namespace {
9389 // Collect all steps of SCEV expressions.
9390 struct SCEVCollectStrides {
9391   ScalarEvolution &SE;
9392   SmallVectorImpl<const SCEV *> &Strides;
9393 
9394   SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S)
9395       : SE(SE), Strides(S) {}
9396 
9397   bool follow(const SCEV *S) {
9398     if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
9399       Strides.push_back(AR->getStepRecurrence(SE));
9400     return true;
9401   }
9402   bool isDone() const { return false; }
9403 };
9404 
9405 // Collect all SCEVUnknown and SCEVMulExpr expressions.
9406 struct SCEVCollectTerms {
9407   SmallVectorImpl<const SCEV *> &Terms;
9408 
9409   SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T)
9410       : Terms(T) {}
9411 
9412   bool follow(const SCEV *S) {
9413     if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) ||
9414         isa<SCEVSignExtendExpr>(S)) {
9415       if (!containsUndefs(S))
9416         Terms.push_back(S);
9417 
9418       // Stop recursion: once we collected a term, do not walk its operands.
9419       return false;
9420     }
9421 
9422     // Keep looking.
9423     return true;
9424   }
9425   bool isDone() const { return false; }
9426 };
9427 
9428 // Check if a SCEV contains an AddRecExpr.
9429 struct SCEVHasAddRec {
9430   bool &ContainsAddRec;
9431 
9432   SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) {
9433    ContainsAddRec = false;
9434   }
9435 
9436   bool follow(const SCEV *S) {
9437     if (isa<SCEVAddRecExpr>(S)) {
9438       ContainsAddRec = true;
9439 
9440       // Stop recursion: once we collected a term, do not walk its operands.
9441       return false;
9442     }
9443 
9444     // Keep looking.
9445     return true;
9446   }
9447   bool isDone() const { return false; }
9448 };
9449 
9450 // Find factors that are multiplied with an expression that (possibly as a
9451 // subexpression) contains an AddRecExpr. In the expression:
9452 //
9453 //  8 * (100 +  %p * %q * (%a + {0, +, 1}_loop))
9454 //
9455 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)"
9456 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size
9457 // parameters as they form a product with an induction variable.
9458 //
9459 // This collector expects all array size parameters to be in the same MulExpr.
9460 // It might be necessary to later add support for collecting parameters that are
9461 // spread over different nested MulExpr.
9462 struct SCEVCollectAddRecMultiplies {
9463   SmallVectorImpl<const SCEV *> &Terms;
9464   ScalarEvolution &SE;
9465 
9466   SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE)
9467       : Terms(T), SE(SE) {}
9468 
9469   bool follow(const SCEV *S) {
9470     if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) {
9471       bool HasAddRec = false;
9472       SmallVector<const SCEV *, 0> Operands;
9473       for (auto Op : Mul->operands()) {
9474         if (isa<SCEVUnknown>(Op)) {
9475           Operands.push_back(Op);
9476         } else {
9477           bool ContainsAddRec;
9478           SCEVHasAddRec ContiansAddRec(ContainsAddRec);
9479           visitAll(Op, ContiansAddRec);
9480           HasAddRec |= ContainsAddRec;
9481         }
9482       }
9483       if (Operands.size() == 0)
9484         return true;
9485 
9486       if (!HasAddRec)
9487         return false;
9488 
9489       Terms.push_back(SE.getMulExpr(Operands));
9490       // Stop recursion: once we collected a term, do not walk its operands.
9491       return false;
9492     }
9493 
9494     // Keep looking.
9495     return true;
9496   }
9497   bool isDone() const { return false; }
9498 };
9499 }
9500 
9501 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in
9502 /// two places:
9503 ///   1) The strides of AddRec expressions.
9504 ///   2) Unknowns that are multiplied with AddRec expressions.
9505 void ScalarEvolution::collectParametricTerms(const SCEV *Expr,
9506     SmallVectorImpl<const SCEV *> &Terms) {
9507   SmallVector<const SCEV *, 4> Strides;
9508   SCEVCollectStrides StrideCollector(*this, Strides);
9509   visitAll(Expr, StrideCollector);
9510 
9511   DEBUG({
9512       dbgs() << "Strides:\n";
9513       for (const SCEV *S : Strides)
9514         dbgs() << *S << "\n";
9515     });
9516 
9517   for (const SCEV *S : Strides) {
9518     SCEVCollectTerms TermCollector(Terms);
9519     visitAll(S, TermCollector);
9520   }
9521 
9522   DEBUG({
9523       dbgs() << "Terms:\n";
9524       for (const SCEV *T : Terms)
9525         dbgs() << *T << "\n";
9526     });
9527 
9528   SCEVCollectAddRecMultiplies MulCollector(Terms, *this);
9529   visitAll(Expr, MulCollector);
9530 }
9531 
9532 static bool findArrayDimensionsRec(ScalarEvolution &SE,
9533                                    SmallVectorImpl<const SCEV *> &Terms,
9534                                    SmallVectorImpl<const SCEV *> &Sizes) {
9535   int Last = Terms.size() - 1;
9536   const SCEV *Step = Terms[Last];
9537 
9538   // End of recursion.
9539   if (Last == 0) {
9540     if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) {
9541       SmallVector<const SCEV *, 2> Qs;
9542       for (const SCEV *Op : M->operands())
9543         if (!isa<SCEVConstant>(Op))
9544           Qs.push_back(Op);
9545 
9546       Step = SE.getMulExpr(Qs);
9547     }
9548 
9549     Sizes.push_back(Step);
9550     return true;
9551   }
9552 
9553   for (const SCEV *&Term : Terms) {
9554     // Normalize the terms before the next call to findArrayDimensionsRec.
9555     const SCEV *Q, *R;
9556     SCEVDivision::divide(SE, Term, Step, &Q, &R);
9557 
9558     // Bail out when GCD does not evenly divide one of the terms.
9559     if (!R->isZero())
9560       return false;
9561 
9562     Term = Q;
9563   }
9564 
9565   // Remove all SCEVConstants.
9566   Terms.erase(
9567       remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }),
9568       Terms.end());
9569 
9570   if (Terms.size() > 0)
9571     if (!findArrayDimensionsRec(SE, Terms, Sizes))
9572       return false;
9573 
9574   Sizes.push_back(Step);
9575   return true;
9576 }
9577 
9578 
9579 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter.
9580 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) {
9581   for (const SCEV *T : Terms)
9582     if (SCEVExprContains(T, isa<SCEVUnknown, const SCEV *>))
9583       return true;
9584   return false;
9585 }
9586 
9587 // Return the number of product terms in S.
9588 static inline int numberOfTerms(const SCEV *S) {
9589   if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S))
9590     return Expr->getNumOperands();
9591   return 1;
9592 }
9593 
9594 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) {
9595   if (isa<SCEVConstant>(T))
9596     return nullptr;
9597 
9598   if (isa<SCEVUnknown>(T))
9599     return T;
9600 
9601   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) {
9602     SmallVector<const SCEV *, 2> Factors;
9603     for (const SCEV *Op : M->operands())
9604       if (!isa<SCEVConstant>(Op))
9605         Factors.push_back(Op);
9606 
9607     return SE.getMulExpr(Factors);
9608   }
9609 
9610   return T;
9611 }
9612 
9613 /// Return the size of an element read or written by Inst.
9614 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
9615   Type *Ty;
9616   if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
9617     Ty = Store->getValueOperand()->getType();
9618   else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
9619     Ty = Load->getType();
9620   else
9621     return nullptr;
9622 
9623   Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
9624   return getSizeOfExpr(ETy, Ty);
9625 }
9626 
9627 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
9628                                           SmallVectorImpl<const SCEV *> &Sizes,
9629                                           const SCEV *ElementSize) {
9630   if (Terms.size() < 1 || !ElementSize)
9631     return;
9632 
9633   // Early return when Terms do not contain parameters: we do not delinearize
9634   // non parametric SCEVs.
9635   if (!containsParameters(Terms))
9636     return;
9637 
9638   DEBUG({
9639       dbgs() << "Terms:\n";
9640       for (const SCEV *T : Terms)
9641         dbgs() << *T << "\n";
9642     });
9643 
9644   // Remove duplicates.
9645   array_pod_sort(Terms.begin(), Terms.end());
9646   Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end());
9647 
9648   // Put larger terms first.
9649   std::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) {
9650     return numberOfTerms(LHS) > numberOfTerms(RHS);
9651   });
9652 
9653   // Try to divide all terms by the element size. If term is not divisible by
9654   // element size, proceed with the original term.
9655   for (const SCEV *&Term : Terms) {
9656     const SCEV *Q, *R;
9657     SCEVDivision::divide(*this, Term, ElementSize, &Q, &R);
9658     if (!Q->isZero())
9659       Term = Q;
9660   }
9661 
9662   SmallVector<const SCEV *, 4> NewTerms;
9663 
9664   // Remove constant factors.
9665   for (const SCEV *T : Terms)
9666     if (const SCEV *NewT = removeConstantFactors(*this, T))
9667       NewTerms.push_back(NewT);
9668 
9669   DEBUG({
9670       dbgs() << "Terms after sorting:\n";
9671       for (const SCEV *T : NewTerms)
9672         dbgs() << *T << "\n";
9673     });
9674 
9675   if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) {
9676     Sizes.clear();
9677     return;
9678   }
9679 
9680   // The last element to be pushed into Sizes is the size of an element.
9681   Sizes.push_back(ElementSize);
9682 
9683   DEBUG({
9684       dbgs() << "Sizes:\n";
9685       for (const SCEV *S : Sizes)
9686         dbgs() << *S << "\n";
9687     });
9688 }
9689 
9690 void ScalarEvolution::computeAccessFunctions(
9691     const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts,
9692     SmallVectorImpl<const SCEV *> &Sizes) {
9693 
9694   // Early exit in case this SCEV is not an affine multivariate function.
9695   if (Sizes.empty())
9696     return;
9697 
9698   if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr))
9699     if (!AR->isAffine())
9700       return;
9701 
9702   const SCEV *Res = Expr;
9703   int Last = Sizes.size() - 1;
9704   for (int i = Last; i >= 0; i--) {
9705     const SCEV *Q, *R;
9706     SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R);
9707 
9708     DEBUG({
9709         dbgs() << "Res: " << *Res << "\n";
9710         dbgs() << "Sizes[i]: " << *Sizes[i] << "\n";
9711         dbgs() << "Res divided by Sizes[i]:\n";
9712         dbgs() << "Quotient: " << *Q << "\n";
9713         dbgs() << "Remainder: " << *R << "\n";
9714       });
9715 
9716     Res = Q;
9717 
9718     // Do not record the last subscript corresponding to the size of elements in
9719     // the array.
9720     if (i == Last) {
9721 
9722       // Bail out if the remainder is too complex.
9723       if (isa<SCEVAddRecExpr>(R)) {
9724         Subscripts.clear();
9725         Sizes.clear();
9726         return;
9727       }
9728 
9729       continue;
9730     }
9731 
9732     // Record the access function for the current subscript.
9733     Subscripts.push_back(R);
9734   }
9735 
9736   // Also push in last position the remainder of the last division: it will be
9737   // the access function of the innermost dimension.
9738   Subscripts.push_back(Res);
9739 
9740   std::reverse(Subscripts.begin(), Subscripts.end());
9741 
9742   DEBUG({
9743       dbgs() << "Subscripts:\n";
9744       for (const SCEV *S : Subscripts)
9745         dbgs() << *S << "\n";
9746     });
9747 }
9748 
9749 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and
9750 /// sizes of an array access. Returns the remainder of the delinearization that
9751 /// is the offset start of the array.  The SCEV->delinearize algorithm computes
9752 /// the multiples of SCEV coefficients: that is a pattern matching of sub
9753 /// expressions in the stride and base of a SCEV corresponding to the
9754 /// computation of a GCD (greatest common divisor) of base and stride.  When
9755 /// SCEV->delinearize fails, it returns the SCEV unchanged.
9756 ///
9757 /// For example: when analyzing the memory access A[i][j][k] in this loop nest
9758 ///
9759 ///  void foo(long n, long m, long o, double A[n][m][o]) {
9760 ///
9761 ///    for (long i = 0; i < n; i++)
9762 ///      for (long j = 0; j < m; j++)
9763 ///        for (long k = 0; k < o; k++)
9764 ///          A[i][j][k] = 1.0;
9765 ///  }
9766 ///
9767 /// the delinearization input is the following AddRec SCEV:
9768 ///
9769 ///  AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k>
9770 ///
9771 /// From this SCEV, we are able to say that the base offset of the access is %A
9772 /// because it appears as an offset that does not divide any of the strides in
9773 /// the loops:
9774 ///
9775 ///  CHECK: Base offset: %A
9776 ///
9777 /// and then SCEV->delinearize determines the size of some of the dimensions of
9778 /// the array as these are the multiples by which the strides are happening:
9779 ///
9780 ///  CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes.
9781 ///
9782 /// Note that the outermost dimension remains of UnknownSize because there are
9783 /// no strides that would help identifying the size of the last dimension: when
9784 /// the array has been statically allocated, one could compute the size of that
9785 /// dimension by dividing the overall size of the array by the size of the known
9786 /// dimensions: %m * %o * 8.
9787 ///
9788 /// Finally delinearize provides the access functions for the array reference
9789 /// that does correspond to A[i][j][k] of the above C testcase:
9790 ///
9791 ///  CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>]
9792 ///
9793 /// The testcases are checking the output of a function pass:
9794 /// DelinearizationPass that walks through all loads and stores of a function
9795 /// asking for the SCEV of the memory access with respect to all enclosing
9796 /// loops, calling SCEV->delinearize on that and printing the results.
9797 
9798 void ScalarEvolution::delinearize(const SCEV *Expr,
9799                                  SmallVectorImpl<const SCEV *> &Subscripts,
9800                                  SmallVectorImpl<const SCEV *> &Sizes,
9801                                  const SCEV *ElementSize) {
9802   // First step: collect parametric terms.
9803   SmallVector<const SCEV *, 4> Terms;
9804   collectParametricTerms(Expr, Terms);
9805 
9806   if (Terms.empty())
9807     return;
9808 
9809   // Second step: find subscript sizes.
9810   findArrayDimensions(Terms, Sizes, ElementSize);
9811 
9812   if (Sizes.empty())
9813     return;
9814 
9815   // Third step: compute the access functions for each subscript.
9816   computeAccessFunctions(Expr, Subscripts, Sizes);
9817 
9818   if (Subscripts.empty())
9819     return;
9820 
9821   DEBUG({
9822       dbgs() << "succeeded to delinearize " << *Expr << "\n";
9823       dbgs() << "ArrayDecl[UnknownSize]";
9824       for (const SCEV *S : Sizes)
9825         dbgs() << "[" << *S << "]";
9826 
9827       dbgs() << "\nArrayRef";
9828       for (const SCEV *S : Subscripts)
9829         dbgs() << "[" << *S << "]";
9830       dbgs() << "\n";
9831     });
9832 }
9833 
9834 //===----------------------------------------------------------------------===//
9835 //                   SCEVCallbackVH Class Implementation
9836 //===----------------------------------------------------------------------===//
9837 
9838 void ScalarEvolution::SCEVCallbackVH::deleted() {
9839   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
9840   if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
9841     SE->ConstantEvolutionLoopExitValue.erase(PN);
9842   SE->eraseValueFromMap(getValPtr());
9843   // this now dangles!
9844 }
9845 
9846 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
9847   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
9848 
9849   // Forget all the expressions associated with users of the old value,
9850   // so that future queries will recompute the expressions using the new
9851   // value.
9852   Value *Old = getValPtr();
9853   SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end());
9854   SmallPtrSet<User *, 8> Visited;
9855   while (!Worklist.empty()) {
9856     User *U = Worklist.pop_back_val();
9857     // Deleting the Old value will cause this to dangle. Postpone
9858     // that until everything else is done.
9859     if (U == Old)
9860       continue;
9861     if (!Visited.insert(U).second)
9862       continue;
9863     if (PHINode *PN = dyn_cast<PHINode>(U))
9864       SE->ConstantEvolutionLoopExitValue.erase(PN);
9865     SE->eraseValueFromMap(U);
9866     Worklist.insert(Worklist.end(), U->user_begin(), U->user_end());
9867   }
9868   // Delete the Old value.
9869   if (PHINode *PN = dyn_cast<PHINode>(Old))
9870     SE->ConstantEvolutionLoopExitValue.erase(PN);
9871   SE->eraseValueFromMap(Old);
9872   // this now dangles!
9873 }
9874 
9875 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
9876   : CallbackVH(V), SE(se) {}
9877 
9878 //===----------------------------------------------------------------------===//
9879 //                   ScalarEvolution Class Implementation
9880 //===----------------------------------------------------------------------===//
9881 
9882 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
9883                                  AssumptionCache &AC, DominatorTree &DT,
9884                                  LoopInfo &LI)
9885     : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
9886       CouldNotCompute(new SCEVCouldNotCompute()),
9887       WalkingBEDominatingConds(false), ProvingSplitPredicate(false),
9888       ValuesAtScopes(64), LoopDispositions(64), BlockDispositions(64),
9889       FirstUnknown(nullptr) {
9890 
9891   // To use guards for proving predicates, we need to scan every instruction in
9892   // relevant basic blocks, and not just terminators.  Doing this is a waste of
9893   // time if the IR does not actually contain any calls to
9894   // @llvm.experimental.guard, so do a quick check and remember this beforehand.
9895   //
9896   // This pessimizes the case where a pass that preserves ScalarEvolution wants
9897   // to _add_ guards to the module when there weren't any before, and wants
9898   // ScalarEvolution to optimize based on those guards.  For now we prefer to be
9899   // efficient in lieu of being smart in that rather obscure case.
9900 
9901   auto *GuardDecl = F.getParent()->getFunction(
9902       Intrinsic::getName(Intrinsic::experimental_guard));
9903   HasGuards = GuardDecl && !GuardDecl->use_empty();
9904 }
9905 
9906 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
9907     : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT),
9908       LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
9909       ValueExprMap(std::move(Arg.ValueExprMap)),
9910       PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
9911       WalkingBEDominatingConds(false), ProvingSplitPredicate(false),
9912       MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)),
9913       BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
9914       PredicatedBackedgeTakenCounts(
9915           std::move(Arg.PredicatedBackedgeTakenCounts)),
9916       ConstantEvolutionLoopExitValue(
9917           std::move(Arg.ConstantEvolutionLoopExitValue)),
9918       ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
9919       LoopDispositions(std::move(Arg.LoopDispositions)),
9920       LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
9921       BlockDispositions(std::move(Arg.BlockDispositions)),
9922       UnsignedRanges(std::move(Arg.UnsignedRanges)),
9923       SignedRanges(std::move(Arg.SignedRanges)),
9924       UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
9925       UniquePreds(std::move(Arg.UniquePreds)),
9926       SCEVAllocator(std::move(Arg.SCEVAllocator)),
9927       FirstUnknown(Arg.FirstUnknown) {
9928   Arg.FirstUnknown = nullptr;
9929 }
9930 
9931 ScalarEvolution::~ScalarEvolution() {
9932   // Iterate through all the SCEVUnknown instances and call their
9933   // destructors, so that they release their references to their values.
9934   for (SCEVUnknown *U = FirstUnknown; U;) {
9935     SCEVUnknown *Tmp = U;
9936     U = U->Next;
9937     Tmp->~SCEVUnknown();
9938   }
9939   FirstUnknown = nullptr;
9940 
9941   ExprValueMap.clear();
9942   ValueExprMap.clear();
9943   HasRecMap.clear();
9944 
9945   // Free any extra memory created for ExitNotTakenInfo in the unlikely event
9946   // that a loop had multiple computable exits.
9947   for (auto &BTCI : BackedgeTakenCounts)
9948     BTCI.second.clear();
9949   for (auto &BTCI : PredicatedBackedgeTakenCounts)
9950     BTCI.second.clear();
9951 
9952   assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
9953   assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
9954   assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
9955 }
9956 
9957 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
9958   return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
9959 }
9960 
9961 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
9962                           const Loop *L) {
9963   // Print all inner loops first
9964   for (Loop *I : *L)
9965     PrintLoopInfo(OS, SE, I);
9966 
9967   OS << "Loop ";
9968   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9969   OS << ": ";
9970 
9971   SmallVector<BasicBlock *, 8> ExitBlocks;
9972   L->getExitBlocks(ExitBlocks);
9973   if (ExitBlocks.size() != 1)
9974     OS << "<multiple exits> ";
9975 
9976   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
9977     OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
9978   } else {
9979     OS << "Unpredictable backedge-taken count. ";
9980   }
9981 
9982   OS << "\n"
9983         "Loop ";
9984   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9985   OS << ": ";
9986 
9987   if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
9988     OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
9989     if (SE->isBackedgeTakenCountMaxOrZero(L))
9990       OS << ", actual taken count either this or zero.";
9991   } else {
9992     OS << "Unpredictable max backedge-taken count. ";
9993   }
9994 
9995   OS << "\n"
9996         "Loop ";
9997   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9998   OS << ": ";
9999 
10000   SCEVUnionPredicate Pred;
10001   auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred);
10002   if (!isa<SCEVCouldNotCompute>(PBT)) {
10003     OS << "Predicated backedge-taken count is " << *PBT << "\n";
10004     OS << " Predicates:\n";
10005     Pred.print(OS, 4);
10006   } else {
10007     OS << "Unpredictable predicated backedge-taken count. ";
10008   }
10009   OS << "\n";
10010 
10011   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
10012     OS << "Loop ";
10013     L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
10014     OS << ": ";
10015     OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
10016   }
10017 }
10018 
10019 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) {
10020   switch (LD) {
10021   case ScalarEvolution::LoopVariant:
10022     return "Variant";
10023   case ScalarEvolution::LoopInvariant:
10024     return "Invariant";
10025   case ScalarEvolution::LoopComputable:
10026     return "Computable";
10027   }
10028   llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!");
10029 }
10030 
10031 void ScalarEvolution::print(raw_ostream &OS) const {
10032   // ScalarEvolution's implementation of the print method is to print
10033   // out SCEV values of all instructions that are interesting. Doing
10034   // this potentially causes it to create new SCEV objects though,
10035   // which technically conflicts with the const qualifier. This isn't
10036   // observable from outside the class though, so casting away the
10037   // const isn't dangerous.
10038   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
10039 
10040   OS << "Classifying expressions for: ";
10041   F.printAsOperand(OS, /*PrintType=*/false);
10042   OS << "\n";
10043   for (Instruction &I : instructions(F))
10044     if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
10045       OS << I << '\n';
10046       OS << "  -->  ";
10047       const SCEV *SV = SE.getSCEV(&I);
10048       SV->print(OS);
10049       if (!isa<SCEVCouldNotCompute>(SV)) {
10050         OS << " U: ";
10051         SE.getUnsignedRange(SV).print(OS);
10052         OS << " S: ";
10053         SE.getSignedRange(SV).print(OS);
10054       }
10055 
10056       const Loop *L = LI.getLoopFor(I.getParent());
10057 
10058       const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
10059       if (AtUse != SV) {
10060         OS << "  -->  ";
10061         AtUse->print(OS);
10062         if (!isa<SCEVCouldNotCompute>(AtUse)) {
10063           OS << " U: ";
10064           SE.getUnsignedRange(AtUse).print(OS);
10065           OS << " S: ";
10066           SE.getSignedRange(AtUse).print(OS);
10067         }
10068       }
10069 
10070       if (L) {
10071         OS << "\t\t" "Exits: ";
10072         const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
10073         if (!SE.isLoopInvariant(ExitValue, L)) {
10074           OS << "<<Unknown>>";
10075         } else {
10076           OS << *ExitValue;
10077         }
10078 
10079         bool First = true;
10080         for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
10081           if (First) {
10082             OS << "\t\t" "LoopDispositions: { ";
10083             First = false;
10084           } else {
10085             OS << ", ";
10086           }
10087 
10088           Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
10089           OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter));
10090         }
10091 
10092         for (auto *InnerL : depth_first(L)) {
10093           if (InnerL == L)
10094             continue;
10095           if (First) {
10096             OS << "\t\t" "LoopDispositions: { ";
10097             First = false;
10098           } else {
10099             OS << ", ";
10100           }
10101 
10102           InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
10103           OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL));
10104         }
10105 
10106         OS << " }";
10107       }
10108 
10109       OS << "\n";
10110     }
10111 
10112   OS << "Determining loop execution counts for: ";
10113   F.printAsOperand(OS, /*PrintType=*/false);
10114   OS << "\n";
10115   for (Loop *I : LI)
10116     PrintLoopInfo(OS, &SE, I);
10117 }
10118 
10119 ScalarEvolution::LoopDisposition
10120 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
10121   auto &Values = LoopDispositions[S];
10122   for (auto &V : Values) {
10123     if (V.getPointer() == L)
10124       return V.getInt();
10125   }
10126   Values.emplace_back(L, LoopVariant);
10127   LoopDisposition D = computeLoopDisposition(S, L);
10128   auto &Values2 = LoopDispositions[S];
10129   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
10130     if (V.getPointer() == L) {
10131       V.setInt(D);
10132       break;
10133     }
10134   }
10135   return D;
10136 }
10137 
10138 ScalarEvolution::LoopDisposition
10139 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
10140   switch (static_cast<SCEVTypes>(S->getSCEVType())) {
10141   case scConstant:
10142     return LoopInvariant;
10143   case scTruncate:
10144   case scZeroExtend:
10145   case scSignExtend:
10146     return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
10147   case scAddRecExpr: {
10148     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
10149 
10150     // If L is the addrec's loop, it's computable.
10151     if (AR->getLoop() == L)
10152       return LoopComputable;
10153 
10154     // Add recurrences are never invariant in the function-body (null loop).
10155     if (!L)
10156       return LoopVariant;
10157 
10158     // This recurrence is variant w.r.t. L if L contains AR's loop.
10159     if (L->contains(AR->getLoop()))
10160       return LoopVariant;
10161 
10162     // This recurrence is invariant w.r.t. L if AR's loop contains L.
10163     if (AR->getLoop()->contains(L))
10164       return LoopInvariant;
10165 
10166     // This recurrence is variant w.r.t. L if any of its operands
10167     // are variant.
10168     for (auto *Op : AR->operands())
10169       if (!isLoopInvariant(Op, L))
10170         return LoopVariant;
10171 
10172     // Otherwise it's loop-invariant.
10173     return LoopInvariant;
10174   }
10175   case scAddExpr:
10176   case scMulExpr:
10177   case scUMaxExpr:
10178   case scSMaxExpr: {
10179     bool HasVarying = false;
10180     for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) {
10181       LoopDisposition D = getLoopDisposition(Op, L);
10182       if (D == LoopVariant)
10183         return LoopVariant;
10184       if (D == LoopComputable)
10185         HasVarying = true;
10186     }
10187     return HasVarying ? LoopComputable : LoopInvariant;
10188   }
10189   case scUDivExpr: {
10190     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
10191     LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
10192     if (LD == LoopVariant)
10193       return LoopVariant;
10194     LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
10195     if (RD == LoopVariant)
10196       return LoopVariant;
10197     return (LD == LoopInvariant && RD == LoopInvariant) ?
10198            LoopInvariant : LoopComputable;
10199   }
10200   case scUnknown:
10201     // All non-instruction values are loop invariant.  All instructions are loop
10202     // invariant if they are not contained in the specified loop.
10203     // Instructions are never considered invariant in the function body
10204     // (null loop) because they are defined within the "loop".
10205     if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
10206       return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
10207     return LoopInvariant;
10208   case scCouldNotCompute:
10209     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
10210   }
10211   llvm_unreachable("Unknown SCEV kind!");
10212 }
10213 
10214 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
10215   return getLoopDisposition(S, L) == LoopInvariant;
10216 }
10217 
10218 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
10219   return getLoopDisposition(S, L) == LoopComputable;
10220 }
10221 
10222 ScalarEvolution::BlockDisposition
10223 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
10224   auto &Values = BlockDispositions[S];
10225   for (auto &V : Values) {
10226     if (V.getPointer() == BB)
10227       return V.getInt();
10228   }
10229   Values.emplace_back(BB, DoesNotDominateBlock);
10230   BlockDisposition D = computeBlockDisposition(S, BB);
10231   auto &Values2 = BlockDispositions[S];
10232   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
10233     if (V.getPointer() == BB) {
10234       V.setInt(D);
10235       break;
10236     }
10237   }
10238   return D;
10239 }
10240 
10241 ScalarEvolution::BlockDisposition
10242 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
10243   switch (static_cast<SCEVTypes>(S->getSCEVType())) {
10244   case scConstant:
10245     return ProperlyDominatesBlock;
10246   case scTruncate:
10247   case scZeroExtend:
10248   case scSignExtend:
10249     return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
10250   case scAddRecExpr: {
10251     // This uses a "dominates" query instead of "properly dominates" query
10252     // to test for proper dominance too, because the instruction which
10253     // produces the addrec's value is a PHI, and a PHI effectively properly
10254     // dominates its entire containing block.
10255     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
10256     if (!DT.dominates(AR->getLoop()->getHeader(), BB))
10257       return DoesNotDominateBlock;
10258 
10259     // Fall through into SCEVNAryExpr handling.
10260     LLVM_FALLTHROUGH;
10261   }
10262   case scAddExpr:
10263   case scMulExpr:
10264   case scUMaxExpr:
10265   case scSMaxExpr: {
10266     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
10267     bool Proper = true;
10268     for (const SCEV *NAryOp : NAry->operands()) {
10269       BlockDisposition D = getBlockDisposition(NAryOp, BB);
10270       if (D == DoesNotDominateBlock)
10271         return DoesNotDominateBlock;
10272       if (D == DominatesBlock)
10273         Proper = false;
10274     }
10275     return Proper ? ProperlyDominatesBlock : DominatesBlock;
10276   }
10277   case scUDivExpr: {
10278     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
10279     const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
10280     BlockDisposition LD = getBlockDisposition(LHS, BB);
10281     if (LD == DoesNotDominateBlock)
10282       return DoesNotDominateBlock;
10283     BlockDisposition RD = getBlockDisposition(RHS, BB);
10284     if (RD == DoesNotDominateBlock)
10285       return DoesNotDominateBlock;
10286     return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
10287       ProperlyDominatesBlock : DominatesBlock;
10288   }
10289   case scUnknown:
10290     if (Instruction *I =
10291           dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
10292       if (I->getParent() == BB)
10293         return DominatesBlock;
10294       if (DT.properlyDominates(I->getParent(), BB))
10295         return ProperlyDominatesBlock;
10296       return DoesNotDominateBlock;
10297     }
10298     return ProperlyDominatesBlock;
10299   case scCouldNotCompute:
10300     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
10301   }
10302   llvm_unreachable("Unknown SCEV kind!");
10303 }
10304 
10305 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
10306   return getBlockDisposition(S, BB) >= DominatesBlock;
10307 }
10308 
10309 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
10310   return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
10311 }
10312 
10313 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
10314   return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; });
10315 }
10316 
10317 void ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
10318   ValuesAtScopes.erase(S);
10319   LoopDispositions.erase(S);
10320   BlockDispositions.erase(S);
10321   UnsignedRanges.erase(S);
10322   SignedRanges.erase(S);
10323   ExprValueMap.erase(S);
10324   HasRecMap.erase(S);
10325   MinTrailingZerosCache.erase(S);
10326 
10327   auto RemoveSCEVFromBackedgeMap =
10328       [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
10329         for (auto I = Map.begin(), E = Map.end(); I != E;) {
10330           BackedgeTakenInfo &BEInfo = I->second;
10331           if (BEInfo.hasOperand(S, this)) {
10332             BEInfo.clear();
10333             Map.erase(I++);
10334           } else
10335             ++I;
10336         }
10337       };
10338 
10339   RemoveSCEVFromBackedgeMap(BackedgeTakenCounts);
10340   RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts);
10341 }
10342 
10343 void ScalarEvolution::verify() const {
10344   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
10345   ScalarEvolution SE2(F, TLI, AC, DT, LI);
10346 
10347   SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end());
10348 
10349   // Map's SCEV expressions from one ScalarEvolution "universe" to another.
10350   struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> {
10351     const SCEV *visitConstant(const SCEVConstant *Constant) {
10352       return SE.getConstant(Constant->getAPInt());
10353     }
10354     const SCEV *visitUnknown(const SCEVUnknown *Expr) {
10355       return SE.getUnknown(Expr->getValue());
10356     }
10357 
10358     const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
10359       return SE.getCouldNotCompute();
10360     }
10361     SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {}
10362   };
10363 
10364   SCEVMapper SCM(SE2);
10365 
10366   while (!LoopStack.empty()) {
10367     auto *L = LoopStack.pop_back_val();
10368     LoopStack.insert(LoopStack.end(), L->begin(), L->end());
10369 
10370     auto *CurBECount = SCM.visit(
10371         const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L));
10372     auto *NewBECount = SE2.getBackedgeTakenCount(L);
10373 
10374     if (CurBECount == SE2.getCouldNotCompute() ||
10375         NewBECount == SE2.getCouldNotCompute()) {
10376       // NB! This situation is legal, but is very suspicious -- whatever pass
10377       // change the loop to make a trip count go from could not compute to
10378       // computable or vice-versa *should have* invalidated SCEV.  However, we
10379       // choose not to assert here (for now) since we don't want false
10380       // positives.
10381       continue;
10382     }
10383 
10384     if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) {
10385       // SCEV treats "undef" as an unknown but consistent value (i.e. it does
10386       // not propagate undef aggressively).  This means we can (and do) fail
10387       // verification in cases where a transform makes the trip count of a loop
10388       // go from "undef" to "undef+1" (say).  The transform is fine, since in
10389       // both cases the loop iterates "undef" times, but SCEV thinks we
10390       // increased the trip count of the loop by 1 incorrectly.
10391       continue;
10392     }
10393 
10394     if (SE.getTypeSizeInBits(CurBECount->getType()) >
10395         SE.getTypeSizeInBits(NewBECount->getType()))
10396       NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType());
10397     else if (SE.getTypeSizeInBits(CurBECount->getType()) <
10398              SE.getTypeSizeInBits(NewBECount->getType()))
10399       CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType());
10400 
10401     auto *ConstantDelta =
10402         dyn_cast<SCEVConstant>(SE2.getMinusSCEV(CurBECount, NewBECount));
10403 
10404     if (ConstantDelta && ConstantDelta->getAPInt() != 0) {
10405       dbgs() << "Trip Count Changed!\n";
10406       dbgs() << "Old: " << *CurBECount << "\n";
10407       dbgs() << "New: " << *NewBECount << "\n";
10408       dbgs() << "Delta: " << *ConstantDelta << "\n";
10409       std::abort();
10410     }
10411   }
10412 }
10413 
10414 bool ScalarEvolution::invalidate(
10415     Function &F, const PreservedAnalyses &PA,
10416     FunctionAnalysisManager::Invalidator &Inv) {
10417   // Invalidate the ScalarEvolution object whenever it isn't preserved or one
10418   // of its dependencies is invalidated.
10419   auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
10420   return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
10421          Inv.invalidate<AssumptionAnalysis>(F, PA) ||
10422          Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
10423          Inv.invalidate<LoopAnalysis>(F, PA);
10424 }
10425 
10426 AnalysisKey ScalarEvolutionAnalysis::Key;
10427 
10428 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
10429                                              FunctionAnalysisManager &AM) {
10430   return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F),
10431                          AM.getResult<AssumptionAnalysis>(F),
10432                          AM.getResult<DominatorTreeAnalysis>(F),
10433                          AM.getResult<LoopAnalysis>(F));
10434 }
10435 
10436 PreservedAnalyses
10437 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
10438   AM.getResult<ScalarEvolutionAnalysis>(F).print(OS);
10439   return PreservedAnalyses::all();
10440 }
10441 
10442 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
10443                       "Scalar Evolution Analysis", false, true)
10444 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
10445 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
10446 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
10447 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
10448 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
10449                     "Scalar Evolution Analysis", false, true)
10450 char ScalarEvolutionWrapperPass::ID = 0;
10451 
10452 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
10453   initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
10454 }
10455 
10456 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
10457   SE.reset(new ScalarEvolution(
10458       F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
10459       getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
10460       getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
10461       getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
10462   return false;
10463 }
10464 
10465 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
10466 
10467 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
10468   SE->print(OS);
10469 }
10470 
10471 void ScalarEvolutionWrapperPass::verifyAnalysis() const {
10472   if (!VerifySCEV)
10473     return;
10474 
10475   SE->verify();
10476 }
10477 
10478 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
10479   AU.setPreservesAll();
10480   AU.addRequiredTransitive<AssumptionCacheTracker>();
10481   AU.addRequiredTransitive<LoopInfoWrapperPass>();
10482   AU.addRequiredTransitive<DominatorTreeWrapperPass>();
10483   AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
10484 }
10485 
10486 const SCEVPredicate *
10487 ScalarEvolution::getEqualPredicate(const SCEVUnknown *LHS,
10488                                    const SCEVConstant *RHS) {
10489   FoldingSetNodeID ID;
10490   // Unique this node based on the arguments
10491   ID.AddInteger(SCEVPredicate::P_Equal);
10492   ID.AddPointer(LHS);
10493   ID.AddPointer(RHS);
10494   void *IP = nullptr;
10495   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
10496     return S;
10497   SCEVEqualPredicate *Eq = new (SCEVAllocator)
10498       SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS);
10499   UniquePreds.InsertNode(Eq, IP);
10500   return Eq;
10501 }
10502 
10503 const SCEVPredicate *ScalarEvolution::getWrapPredicate(
10504     const SCEVAddRecExpr *AR,
10505     SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
10506   FoldingSetNodeID ID;
10507   // Unique this node based on the arguments
10508   ID.AddInteger(SCEVPredicate::P_Wrap);
10509   ID.AddPointer(AR);
10510   ID.AddInteger(AddedFlags);
10511   void *IP = nullptr;
10512   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
10513     return S;
10514   auto *OF = new (SCEVAllocator)
10515       SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
10516   UniquePreds.InsertNode(OF, IP);
10517   return OF;
10518 }
10519 
10520 namespace {
10521 
10522 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
10523 public:
10524   /// Rewrites \p S in the context of a loop L and the SCEV predication
10525   /// infrastructure.
10526   ///
10527   /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
10528   /// equivalences present in \p Pred.
10529   ///
10530   /// If \p NewPreds is non-null, rewrite is free to add further predicates to
10531   /// \p NewPreds such that the result will be an AddRecExpr.
10532   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
10533                              SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
10534                              SCEVUnionPredicate *Pred) {
10535     SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
10536     return Rewriter.visit(S);
10537   }
10538 
10539   SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE,
10540                         SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
10541                         SCEVUnionPredicate *Pred)
10542       : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
10543 
10544   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
10545     if (Pred) {
10546       auto ExprPreds = Pred->getPredicatesForExpr(Expr);
10547       for (auto *Pred : ExprPreds)
10548         if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred))
10549           if (IPred->getLHS() == Expr)
10550             return IPred->getRHS();
10551     }
10552 
10553     return Expr;
10554   }
10555 
10556   const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
10557     const SCEV *Operand = visit(Expr->getOperand());
10558     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
10559     if (AR && AR->getLoop() == L && AR->isAffine()) {
10560       // This couldn't be folded because the operand didn't have the nuw
10561       // flag. Add the nusw flag as an assumption that we could make.
10562       const SCEV *Step = AR->getStepRecurrence(SE);
10563       Type *Ty = Expr->getType();
10564       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
10565         return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
10566                                 SE.getSignExtendExpr(Step, Ty), L,
10567                                 AR->getNoWrapFlags());
10568     }
10569     return SE.getZeroExtendExpr(Operand, Expr->getType());
10570   }
10571 
10572   const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
10573     const SCEV *Operand = visit(Expr->getOperand());
10574     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
10575     if (AR && AR->getLoop() == L && AR->isAffine()) {
10576       // This couldn't be folded because the operand didn't have the nsw
10577       // flag. Add the nssw flag as an assumption that we could make.
10578       const SCEV *Step = AR->getStepRecurrence(SE);
10579       Type *Ty = Expr->getType();
10580       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
10581         return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
10582                                 SE.getSignExtendExpr(Step, Ty), L,
10583                                 AR->getNoWrapFlags());
10584     }
10585     return SE.getSignExtendExpr(Operand, Expr->getType());
10586   }
10587 
10588 private:
10589   bool addOverflowAssumption(const SCEVAddRecExpr *AR,
10590                              SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
10591     auto *A = SE.getWrapPredicate(AR, AddedFlags);
10592     if (!NewPreds) {
10593       // Check if we've already made this assumption.
10594       return Pred && Pred->implies(A);
10595     }
10596     NewPreds->insert(A);
10597     return true;
10598   }
10599 
10600   SmallPtrSetImpl<const SCEVPredicate *> *NewPreds;
10601   SCEVUnionPredicate *Pred;
10602   const Loop *L;
10603 };
10604 } // end anonymous namespace
10605 
10606 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
10607                                                    SCEVUnionPredicate &Preds) {
10608   return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
10609 }
10610 
10611 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates(
10612     const SCEV *S, const Loop *L,
10613     SmallPtrSetImpl<const SCEVPredicate *> &Preds) {
10614 
10615   SmallPtrSet<const SCEVPredicate *, 4> TransformPreds;
10616   S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
10617   auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
10618 
10619   if (!AddRec)
10620     return nullptr;
10621 
10622   // Since the transformation was successful, we can now transfer the SCEV
10623   // predicates.
10624   for (auto *P : TransformPreds)
10625     Preds.insert(P);
10626 
10627   return AddRec;
10628 }
10629 
10630 /// SCEV predicates
10631 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
10632                              SCEVPredicateKind Kind)
10633     : FastID(ID), Kind(Kind) {}
10634 
10635 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID,
10636                                        const SCEVUnknown *LHS,
10637                                        const SCEVConstant *RHS)
10638     : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {}
10639 
10640 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const {
10641   const auto *Op = dyn_cast<SCEVEqualPredicate>(N);
10642 
10643   if (!Op)
10644     return false;
10645 
10646   return Op->LHS == LHS && Op->RHS == RHS;
10647 }
10648 
10649 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; }
10650 
10651 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; }
10652 
10653 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const {
10654   OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
10655 }
10656 
10657 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
10658                                      const SCEVAddRecExpr *AR,
10659                                      IncrementWrapFlags Flags)
10660     : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
10661 
10662 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; }
10663 
10664 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const {
10665   const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
10666 
10667   return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags;
10668 }
10669 
10670 bool SCEVWrapPredicate::isAlwaysTrue() const {
10671   SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
10672   IncrementWrapFlags IFlags = Flags;
10673 
10674   if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
10675     IFlags = clearFlags(IFlags, IncrementNSSW);
10676 
10677   return IFlags == IncrementAnyWrap;
10678 }
10679 
10680 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
10681   OS.indent(Depth) << *getExpr() << " Added Flags: ";
10682   if (SCEVWrapPredicate::IncrementNUSW & getFlags())
10683     OS << "<nusw>";
10684   if (SCEVWrapPredicate::IncrementNSSW & getFlags())
10685     OS << "<nssw>";
10686   OS << "\n";
10687 }
10688 
10689 SCEVWrapPredicate::IncrementWrapFlags
10690 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR,
10691                                    ScalarEvolution &SE) {
10692   IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
10693   SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
10694 
10695   // We can safely transfer the NSW flag as NSSW.
10696   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
10697     ImpliedFlags = IncrementNSSW;
10698 
10699   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
10700     // If the increment is positive, the SCEV NUW flag will also imply the
10701     // WrapPredicate NUSW flag.
10702     if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
10703       if (Step->getValue()->getValue().isNonNegative())
10704         ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
10705   }
10706 
10707   return ImpliedFlags;
10708 }
10709 
10710 /// Union predicates don't get cached so create a dummy set ID for it.
10711 SCEVUnionPredicate::SCEVUnionPredicate()
10712     : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {}
10713 
10714 bool SCEVUnionPredicate::isAlwaysTrue() const {
10715   return all_of(Preds,
10716                 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
10717 }
10718 
10719 ArrayRef<const SCEVPredicate *>
10720 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) {
10721   auto I = SCEVToPreds.find(Expr);
10722   if (I == SCEVToPreds.end())
10723     return ArrayRef<const SCEVPredicate *>();
10724   return I->second;
10725 }
10726 
10727 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
10728   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
10729     return all_of(Set->Preds,
10730                   [this](const SCEVPredicate *I) { return this->implies(I); });
10731 
10732   auto ScevPredsIt = SCEVToPreds.find(N->getExpr());
10733   if (ScevPredsIt == SCEVToPreds.end())
10734     return false;
10735   auto &SCEVPreds = ScevPredsIt->second;
10736 
10737   return any_of(SCEVPreds,
10738                 [N](const SCEVPredicate *I) { return I->implies(N); });
10739 }
10740 
10741 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; }
10742 
10743 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
10744   for (auto Pred : Preds)
10745     Pred->print(OS, Depth);
10746 }
10747 
10748 void SCEVUnionPredicate::add(const SCEVPredicate *N) {
10749   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
10750     for (auto Pred : Set->Preds)
10751       add(Pred);
10752     return;
10753   }
10754 
10755   if (implies(N))
10756     return;
10757 
10758   const SCEV *Key = N->getExpr();
10759   assert(Key && "Only SCEVUnionPredicate doesn't have an "
10760                 " associated expression!");
10761 
10762   SCEVToPreds[Key].push_back(N);
10763   Preds.push_back(N);
10764 }
10765 
10766 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
10767                                                      Loop &L)
10768     : SE(SE), L(L), Generation(0), BackedgeCount(nullptr) {}
10769 
10770 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
10771   const SCEV *Expr = SE.getSCEV(V);
10772   RewriteEntry &Entry = RewriteMap[Expr];
10773 
10774   // If we already have an entry and the version matches, return it.
10775   if (Entry.second && Generation == Entry.first)
10776     return Entry.second;
10777 
10778   // We found an entry but it's stale. Rewrite the stale entry
10779   // according to the current predicate.
10780   if (Entry.second)
10781     Expr = Entry.second;
10782 
10783   const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds);
10784   Entry = {Generation, NewSCEV};
10785 
10786   return NewSCEV;
10787 }
10788 
10789 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() {
10790   if (!BackedgeCount) {
10791     SCEVUnionPredicate BackedgePred;
10792     BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred);
10793     addPredicate(BackedgePred);
10794   }
10795   return BackedgeCount;
10796 }
10797 
10798 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
10799   if (Preds.implies(&Pred))
10800     return;
10801   Preds.add(&Pred);
10802   updateGeneration();
10803 }
10804 
10805 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const {
10806   return Preds;
10807 }
10808 
10809 void PredicatedScalarEvolution::updateGeneration() {
10810   // If the generation number wrapped recompute everything.
10811   if (++Generation == 0) {
10812     for (auto &II : RewriteMap) {
10813       const SCEV *Rewritten = II.second.second;
10814       II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)};
10815     }
10816   }
10817 }
10818 
10819 void PredicatedScalarEvolution::setNoOverflow(
10820     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
10821   const SCEV *Expr = getSCEV(V);
10822   const auto *AR = cast<SCEVAddRecExpr>(Expr);
10823 
10824   auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE);
10825 
10826   // Clear the statically implied flags.
10827   Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags);
10828   addPredicate(*SE.getWrapPredicate(AR, Flags));
10829 
10830   auto II = FlagsMap.insert({V, Flags});
10831   if (!II.second)
10832     II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second);
10833 }
10834 
10835 bool PredicatedScalarEvolution::hasNoOverflow(
10836     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
10837   const SCEV *Expr = getSCEV(V);
10838   const auto *AR = cast<SCEVAddRecExpr>(Expr);
10839 
10840   Flags = SCEVWrapPredicate::clearFlags(
10841       Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
10842 
10843   auto II = FlagsMap.find(V);
10844 
10845   if (II != FlagsMap.end())
10846     Flags = SCEVWrapPredicate::clearFlags(Flags, II->second);
10847 
10848   return Flags == SCEVWrapPredicate::IncrementAnyWrap;
10849 }
10850 
10851 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) {
10852   const SCEV *Expr = this->getSCEV(V);
10853   SmallPtrSet<const SCEVPredicate *, 4> NewPreds;
10854   auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
10855 
10856   if (!New)
10857     return nullptr;
10858 
10859   for (auto *P : NewPreds)
10860     Preds.add(P);
10861 
10862   updateGeneration();
10863   RewriteMap[SE.getSCEV(V)] = {Generation, New};
10864   return New;
10865 }
10866 
10867 PredicatedScalarEvolution::PredicatedScalarEvolution(
10868     const PredicatedScalarEvolution &Init)
10869     : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds),
10870       Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
10871   for (const auto &I : Init.FlagsMap)
10872     FlagsMap.insert(I);
10873 }
10874 
10875 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const {
10876   // For each block.
10877   for (auto *BB : L.getBlocks())
10878     for (auto &I : *BB) {
10879       if (!SE.isSCEVable(I.getType()))
10880         continue;
10881 
10882       auto *Expr = SE.getSCEV(&I);
10883       auto II = RewriteMap.find(Expr);
10884 
10885       if (II == RewriteMap.end())
10886         continue;
10887 
10888       // Don't print things that are not interesting.
10889       if (II->second.second == Expr)
10890         continue;
10891 
10892       OS.indent(Depth) << "[PSE]" << I << ":\n";
10893       OS.indent(Depth + 2) << *Expr << "\n";
10894       OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
10895     }
10896 }
10897