xref: /freebsd/contrib/llvm-project/llvm/lib/Analysis/ScalarEvolution.cpp (revision 1db9f3b21e39176dd5b67cf8ac378633b172463e)
1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains the implementation of the scalar evolution analysis
10 // engine, which is used primarily to analyze expressions involving induction
11 // variables in loops.
12 //
13 // There are several aspects to this library.  First is the representation of
14 // scalar expressions, which are represented as subclasses of the SCEV class.
15 // These classes are used to represent certain types of subexpressions that we
16 // can handle. We only create one SCEV of a particular shape, so
17 // pointer-comparisons for equality are legal.
18 //
19 // One important aspect of the SCEV objects is that they are never cyclic, even
20 // if there is a cycle in the dataflow for an expression (ie, a PHI node).  If
21 // the PHI node is one of the idioms that we can represent (e.g., a polynomial
22 // recurrence) then we represent it directly as a recurrence node, otherwise we
23 // represent it as a SCEVUnknown node.
24 //
25 // In addition to being able to represent expressions of various types, we also
26 // have folders that are used to build the *canonical* representation for a
27 // particular expression.  These folders are capable of using a variety of
28 // rewrite rules to simplify the expressions.
29 //
30 // Once the folders are defined, we can implement the more interesting
31 // higher-level code, such as the code that recognizes PHI nodes of various
32 // types, computes the execution count of a loop, etc.
33 //
34 // TODO: We should use these routines and value representations to implement
35 // dependence analysis!
36 //
37 //===----------------------------------------------------------------------===//
38 //
39 // There are several good references for the techniques used in this analysis.
40 //
41 //  Chains of recurrences -- a method to expedite the evaluation
42 //  of closed-form functions
43 //  Olaf Bachmann, Paul S. Wang, Eugene V. Zima
44 //
45 //  On computational properties of chains of recurrences
46 //  Eugene V. Zima
47 //
48 //  Symbolic Evaluation of Chains of Recurrences for Loop Optimization
49 //  Robert A. van Engelen
50 //
51 //  Efficient Symbolic Analysis for Optimizing Compilers
52 //  Robert A. van Engelen
53 //
54 //  Using the chains of recurrences algebra for data dependence testing and
55 //  induction variable substitution
56 //  MS Thesis, Johnie Birch
57 //
58 //===----------------------------------------------------------------------===//
59 
60 #include "llvm/Analysis/ScalarEvolution.h"
61 #include "llvm/ADT/APInt.h"
62 #include "llvm/ADT/ArrayRef.h"
63 #include "llvm/ADT/DenseMap.h"
64 #include "llvm/ADT/DepthFirstIterator.h"
65 #include "llvm/ADT/EquivalenceClasses.h"
66 #include "llvm/ADT/FoldingSet.h"
67 #include "llvm/ADT/STLExtras.h"
68 #include "llvm/ADT/ScopeExit.h"
69 #include "llvm/ADT/Sequence.h"
70 #include "llvm/ADT/SmallPtrSet.h"
71 #include "llvm/ADT/SmallSet.h"
72 #include "llvm/ADT/SmallVector.h"
73 #include "llvm/ADT/Statistic.h"
74 #include "llvm/ADT/StringExtras.h"
75 #include "llvm/ADT/StringRef.h"
76 #include "llvm/Analysis/AssumptionCache.h"
77 #include "llvm/Analysis/ConstantFolding.h"
78 #include "llvm/Analysis/InstructionSimplify.h"
79 #include "llvm/Analysis/LoopInfo.h"
80 #include "llvm/Analysis/MemoryBuiltins.h"
81 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
82 #include "llvm/Analysis/TargetLibraryInfo.h"
83 #include "llvm/Analysis/ValueTracking.h"
84 #include "llvm/Config/llvm-config.h"
85 #include "llvm/IR/Argument.h"
86 #include "llvm/IR/BasicBlock.h"
87 #include "llvm/IR/CFG.h"
88 #include "llvm/IR/Constant.h"
89 #include "llvm/IR/ConstantRange.h"
90 #include "llvm/IR/Constants.h"
91 #include "llvm/IR/DataLayout.h"
92 #include "llvm/IR/DerivedTypes.h"
93 #include "llvm/IR/Dominators.h"
94 #include "llvm/IR/Function.h"
95 #include "llvm/IR/GlobalAlias.h"
96 #include "llvm/IR/GlobalValue.h"
97 #include "llvm/IR/InstIterator.h"
98 #include "llvm/IR/InstrTypes.h"
99 #include "llvm/IR/Instruction.h"
100 #include "llvm/IR/Instructions.h"
101 #include "llvm/IR/IntrinsicInst.h"
102 #include "llvm/IR/Intrinsics.h"
103 #include "llvm/IR/LLVMContext.h"
104 #include "llvm/IR/Operator.h"
105 #include "llvm/IR/PatternMatch.h"
106 #include "llvm/IR/Type.h"
107 #include "llvm/IR/Use.h"
108 #include "llvm/IR/User.h"
109 #include "llvm/IR/Value.h"
110 #include "llvm/IR/Verifier.h"
111 #include "llvm/InitializePasses.h"
112 #include "llvm/Pass.h"
113 #include "llvm/Support/Casting.h"
114 #include "llvm/Support/CommandLine.h"
115 #include "llvm/Support/Compiler.h"
116 #include "llvm/Support/Debug.h"
117 #include "llvm/Support/ErrorHandling.h"
118 #include "llvm/Support/KnownBits.h"
119 #include "llvm/Support/SaveAndRestore.h"
120 #include "llvm/Support/raw_ostream.h"
121 #include <algorithm>
122 #include <cassert>
123 #include <climits>
124 #include <cstdint>
125 #include <cstdlib>
126 #include <map>
127 #include <memory>
128 #include <numeric>
129 #include <optional>
130 #include <tuple>
131 #include <utility>
132 #include <vector>
133 
134 using namespace llvm;
135 using namespace PatternMatch;
136 
137 #define DEBUG_TYPE "scalar-evolution"
138 
139 STATISTIC(NumExitCountsComputed,
140           "Number of loop exits with predictable exit counts");
141 STATISTIC(NumExitCountsNotComputed,
142           "Number of loop exits without predictable exit counts");
143 STATISTIC(NumBruteForceTripCountsComputed,
144           "Number of loops with trip counts computed by force");
145 
146 #ifdef EXPENSIVE_CHECKS
147 bool llvm::VerifySCEV = true;
148 #else
149 bool llvm::VerifySCEV = false;
150 #endif
151 
152 static cl::opt<unsigned>
153     MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
154                             cl::desc("Maximum number of iterations SCEV will "
155                                      "symbolically execute a constant "
156                                      "derived loop"),
157                             cl::init(100));
158 
159 static cl::opt<bool, true> VerifySCEVOpt(
160     "verify-scev", cl::Hidden, cl::location(VerifySCEV),
161     cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
162 static cl::opt<bool> VerifySCEVStrict(
163     "verify-scev-strict", cl::Hidden,
164     cl::desc("Enable stricter verification with -verify-scev is passed"));
165 
166 static cl::opt<bool> VerifyIR(
167     "scev-verify-ir", cl::Hidden,
168     cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"),
169     cl::init(false));
170 
171 static cl::opt<unsigned> MulOpsInlineThreshold(
172     "scev-mulops-inline-threshold", cl::Hidden,
173     cl::desc("Threshold for inlining multiplication operands into a SCEV"),
174     cl::init(32));
175 
176 static cl::opt<unsigned> AddOpsInlineThreshold(
177     "scev-addops-inline-threshold", cl::Hidden,
178     cl::desc("Threshold for inlining addition operands into a SCEV"),
179     cl::init(500));
180 
181 static cl::opt<unsigned> MaxSCEVCompareDepth(
182     "scalar-evolution-max-scev-compare-depth", cl::Hidden,
183     cl::desc("Maximum depth of recursive SCEV complexity comparisons"),
184     cl::init(32));
185 
186 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth(
187     "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden,
188     cl::desc("Maximum depth of recursive SCEV operations implication analysis"),
189     cl::init(2));
190 
191 static cl::opt<unsigned> MaxValueCompareDepth(
192     "scalar-evolution-max-value-compare-depth", cl::Hidden,
193     cl::desc("Maximum depth of recursive value complexity comparisons"),
194     cl::init(2));
195 
196 static cl::opt<unsigned>
197     MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden,
198                   cl::desc("Maximum depth of recursive arithmetics"),
199                   cl::init(32));
200 
201 static cl::opt<unsigned> MaxConstantEvolvingDepth(
202     "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
203     cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
204 
205 static cl::opt<unsigned>
206     MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden,
207                  cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"),
208                  cl::init(8));
209 
210 static cl::opt<unsigned>
211     MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden,
212                   cl::desc("Max coefficients in AddRec during evolving"),
213                   cl::init(8));
214 
215 static cl::opt<unsigned>
216     HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden,
217                   cl::desc("Size of the expression which is considered huge"),
218                   cl::init(4096));
219 
220 static cl::opt<unsigned> RangeIterThreshold(
221     "scev-range-iter-threshold", cl::Hidden,
222     cl::desc("Threshold for switching to iteratively computing SCEV ranges"),
223     cl::init(32));
224 
225 static cl::opt<bool>
226 ClassifyExpressions("scalar-evolution-classify-expressions",
227     cl::Hidden, cl::init(true),
228     cl::desc("When printing analysis, include information on every instruction"));
229 
230 static cl::opt<bool> UseExpensiveRangeSharpening(
231     "scalar-evolution-use-expensive-range-sharpening", cl::Hidden,
232     cl::init(false),
233     cl::desc("Use more powerful methods of sharpening expression ranges. May "
234              "be costly in terms of compile time"));
235 
236 static cl::opt<unsigned> MaxPhiSCCAnalysisSize(
237     "scalar-evolution-max-scc-analysis-depth", cl::Hidden,
238     cl::desc("Maximum amount of nodes to process while searching SCEVUnknown "
239              "Phi strongly connected components"),
240     cl::init(8));
241 
242 static cl::opt<bool>
243     EnableFiniteLoopControl("scalar-evolution-finite-loop", cl::Hidden,
244                             cl::desc("Handle <= and >= in finite loops"),
245                             cl::init(true));
246 
247 static cl::opt<bool> UseContextForNoWrapFlagInference(
248     "scalar-evolution-use-context-for-no-wrap-flag-strenghening", cl::Hidden,
249     cl::desc("Infer nuw/nsw flags using context where suitable"),
250     cl::init(true));
251 
252 //===----------------------------------------------------------------------===//
253 //                           SCEV class definitions
254 //===----------------------------------------------------------------------===//
255 
256 //===----------------------------------------------------------------------===//
257 // Implementation of the SCEV class.
258 //
259 
260 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
261 LLVM_DUMP_METHOD void SCEV::dump() const {
262   print(dbgs());
263   dbgs() << '\n';
264 }
265 #endif
266 
267 void SCEV::print(raw_ostream &OS) const {
268   switch (getSCEVType()) {
269   case scConstant:
270     cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
271     return;
272   case scVScale:
273     OS << "vscale";
274     return;
275   case scPtrToInt: {
276     const SCEVPtrToIntExpr *PtrToInt = cast<SCEVPtrToIntExpr>(this);
277     const SCEV *Op = PtrToInt->getOperand();
278     OS << "(ptrtoint " << *Op->getType() << " " << *Op << " to "
279        << *PtrToInt->getType() << ")";
280     return;
281   }
282   case scTruncate: {
283     const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
284     const SCEV *Op = Trunc->getOperand();
285     OS << "(trunc " << *Op->getType() << " " << *Op << " to "
286        << *Trunc->getType() << ")";
287     return;
288   }
289   case scZeroExtend: {
290     const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
291     const SCEV *Op = ZExt->getOperand();
292     OS << "(zext " << *Op->getType() << " " << *Op << " to "
293        << *ZExt->getType() << ")";
294     return;
295   }
296   case scSignExtend: {
297     const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
298     const SCEV *Op = SExt->getOperand();
299     OS << "(sext " << *Op->getType() << " " << *Op << " to "
300        << *SExt->getType() << ")";
301     return;
302   }
303   case scAddRecExpr: {
304     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
305     OS << "{" << *AR->getOperand(0);
306     for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
307       OS << ",+," << *AR->getOperand(i);
308     OS << "}<";
309     if (AR->hasNoUnsignedWrap())
310       OS << "nuw><";
311     if (AR->hasNoSignedWrap())
312       OS << "nsw><";
313     if (AR->hasNoSelfWrap() &&
314         !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
315       OS << "nw><";
316     AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
317     OS << ">";
318     return;
319   }
320   case scAddExpr:
321   case scMulExpr:
322   case scUMaxExpr:
323   case scSMaxExpr:
324   case scUMinExpr:
325   case scSMinExpr:
326   case scSequentialUMinExpr: {
327     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
328     const char *OpStr = nullptr;
329     switch (NAry->getSCEVType()) {
330     case scAddExpr: OpStr = " + "; break;
331     case scMulExpr: OpStr = " * "; break;
332     case scUMaxExpr: OpStr = " umax "; break;
333     case scSMaxExpr: OpStr = " smax "; break;
334     case scUMinExpr:
335       OpStr = " umin ";
336       break;
337     case scSMinExpr:
338       OpStr = " smin ";
339       break;
340     case scSequentialUMinExpr:
341       OpStr = " umin_seq ";
342       break;
343     default:
344       llvm_unreachable("There are no other nary expression types.");
345     }
346     OS << "(";
347     ListSeparator LS(OpStr);
348     for (const SCEV *Op : NAry->operands())
349       OS << LS << *Op;
350     OS << ")";
351     switch (NAry->getSCEVType()) {
352     case scAddExpr:
353     case scMulExpr:
354       if (NAry->hasNoUnsignedWrap())
355         OS << "<nuw>";
356       if (NAry->hasNoSignedWrap())
357         OS << "<nsw>";
358       break;
359     default:
360       // Nothing to print for other nary expressions.
361       break;
362     }
363     return;
364   }
365   case scUDivExpr: {
366     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
367     OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
368     return;
369   }
370   case scUnknown:
371     cast<SCEVUnknown>(this)->getValue()->printAsOperand(OS, false);
372     return;
373   case scCouldNotCompute:
374     OS << "***COULDNOTCOMPUTE***";
375     return;
376   }
377   llvm_unreachable("Unknown SCEV kind!");
378 }
379 
380 Type *SCEV::getType() const {
381   switch (getSCEVType()) {
382   case scConstant:
383     return cast<SCEVConstant>(this)->getType();
384   case scVScale:
385     return cast<SCEVVScale>(this)->getType();
386   case scPtrToInt:
387   case scTruncate:
388   case scZeroExtend:
389   case scSignExtend:
390     return cast<SCEVCastExpr>(this)->getType();
391   case scAddRecExpr:
392     return cast<SCEVAddRecExpr>(this)->getType();
393   case scMulExpr:
394     return cast<SCEVMulExpr>(this)->getType();
395   case scUMaxExpr:
396   case scSMaxExpr:
397   case scUMinExpr:
398   case scSMinExpr:
399     return cast<SCEVMinMaxExpr>(this)->getType();
400   case scSequentialUMinExpr:
401     return cast<SCEVSequentialMinMaxExpr>(this)->getType();
402   case scAddExpr:
403     return cast<SCEVAddExpr>(this)->getType();
404   case scUDivExpr:
405     return cast<SCEVUDivExpr>(this)->getType();
406   case scUnknown:
407     return cast<SCEVUnknown>(this)->getType();
408   case scCouldNotCompute:
409     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
410   }
411   llvm_unreachable("Unknown SCEV kind!");
412 }
413 
414 ArrayRef<const SCEV *> SCEV::operands() const {
415   switch (getSCEVType()) {
416   case scConstant:
417   case scVScale:
418   case scUnknown:
419     return {};
420   case scPtrToInt:
421   case scTruncate:
422   case scZeroExtend:
423   case scSignExtend:
424     return cast<SCEVCastExpr>(this)->operands();
425   case scAddRecExpr:
426   case scAddExpr:
427   case scMulExpr:
428   case scUMaxExpr:
429   case scSMaxExpr:
430   case scUMinExpr:
431   case scSMinExpr:
432   case scSequentialUMinExpr:
433     return cast<SCEVNAryExpr>(this)->operands();
434   case scUDivExpr:
435     return cast<SCEVUDivExpr>(this)->operands();
436   case scCouldNotCompute:
437     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
438   }
439   llvm_unreachable("Unknown SCEV kind!");
440 }
441 
442 bool SCEV::isZero() const {
443   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
444     return SC->getValue()->isZero();
445   return false;
446 }
447 
448 bool SCEV::isOne() const {
449   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
450     return SC->getValue()->isOne();
451   return false;
452 }
453 
454 bool SCEV::isAllOnesValue() const {
455   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
456     return SC->getValue()->isMinusOne();
457   return false;
458 }
459 
460 bool SCEV::isNonConstantNegative() const {
461   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
462   if (!Mul) return false;
463 
464   // If there is a constant factor, it will be first.
465   const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
466   if (!SC) return false;
467 
468   // Return true if the value is negative, this matches things like (-42 * V).
469   return SC->getAPInt().isNegative();
470 }
471 
472 SCEVCouldNotCompute::SCEVCouldNotCompute() :
473   SCEV(FoldingSetNodeIDRef(), scCouldNotCompute, 0) {}
474 
475 bool SCEVCouldNotCompute::classof(const SCEV *S) {
476   return S->getSCEVType() == scCouldNotCompute;
477 }
478 
479 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
480   FoldingSetNodeID ID;
481   ID.AddInteger(scConstant);
482   ID.AddPointer(V);
483   void *IP = nullptr;
484   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
485   SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
486   UniqueSCEVs.InsertNode(S, IP);
487   return S;
488 }
489 
490 const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
491   return getConstant(ConstantInt::get(getContext(), Val));
492 }
493 
494 const SCEV *
495 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
496   IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
497   return getConstant(ConstantInt::get(ITy, V, isSigned));
498 }
499 
500 const SCEV *ScalarEvolution::getVScale(Type *Ty) {
501   FoldingSetNodeID ID;
502   ID.AddInteger(scVScale);
503   ID.AddPointer(Ty);
504   void *IP = nullptr;
505   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
506     return S;
507   SCEV *S = new (SCEVAllocator) SCEVVScale(ID.Intern(SCEVAllocator), Ty);
508   UniqueSCEVs.InsertNode(S, IP);
509   return S;
510 }
511 
512 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy,
513                            const SCEV *op, Type *ty)
514     : SCEV(ID, SCEVTy, computeExpressionSize(op)), Op(op), Ty(ty) {}
515 
516 SCEVPtrToIntExpr::SCEVPtrToIntExpr(const FoldingSetNodeIDRef ID, const SCEV *Op,
517                                    Type *ITy)
518     : SCEVCastExpr(ID, scPtrToInt, Op, ITy) {
519   assert(getOperand()->getType()->isPointerTy() && Ty->isIntegerTy() &&
520          "Must be a non-bit-width-changing pointer-to-integer cast!");
521 }
522 
523 SCEVIntegralCastExpr::SCEVIntegralCastExpr(const FoldingSetNodeIDRef ID,
524                                            SCEVTypes SCEVTy, const SCEV *op,
525                                            Type *ty)
526     : SCEVCastExpr(ID, SCEVTy, op, ty) {}
527 
528 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, const SCEV *op,
529                                    Type *ty)
530     : SCEVIntegralCastExpr(ID, scTruncate, op, ty) {
531   assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
532          "Cannot truncate non-integer value!");
533 }
534 
535 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
536                                        const SCEV *op, Type *ty)
537     : SCEVIntegralCastExpr(ID, scZeroExtend, op, ty) {
538   assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
539          "Cannot zero extend non-integer value!");
540 }
541 
542 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
543                                        const SCEV *op, Type *ty)
544     : SCEVIntegralCastExpr(ID, scSignExtend, op, ty) {
545   assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
546          "Cannot sign extend non-integer value!");
547 }
548 
549 void SCEVUnknown::deleted() {
550   // Clear this SCEVUnknown from various maps.
551   SE->forgetMemoizedResults(this);
552 
553   // Remove this SCEVUnknown from the uniquing map.
554   SE->UniqueSCEVs.RemoveNode(this);
555 
556   // Release the value.
557   setValPtr(nullptr);
558 }
559 
560 void SCEVUnknown::allUsesReplacedWith(Value *New) {
561   // Clear this SCEVUnknown from various maps.
562   SE->forgetMemoizedResults(this);
563 
564   // Remove this SCEVUnknown from the uniquing map.
565   SE->UniqueSCEVs.RemoveNode(this);
566 
567   // Replace the value pointer in case someone is still using this SCEVUnknown.
568   setValPtr(New);
569 }
570 
571 //===----------------------------------------------------------------------===//
572 //                               SCEV Utilities
573 //===----------------------------------------------------------------------===//
574 
575 /// Compare the two values \p LV and \p RV in terms of their "complexity" where
576 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order
577 /// operands in SCEV expressions.  \p EqCache is a set of pairs of values that
578 /// have been previously deemed to be "equally complex" by this routine.  It is
579 /// intended to avoid exponential time complexity in cases like:
580 ///
581 ///   %a = f(%x, %y)
582 ///   %b = f(%a, %a)
583 ///   %c = f(%b, %b)
584 ///
585 ///   %d = f(%x, %y)
586 ///   %e = f(%d, %d)
587 ///   %f = f(%e, %e)
588 ///
589 ///   CompareValueComplexity(%f, %c)
590 ///
591 /// Since we do not continue running this routine on expression trees once we
592 /// have seen unequal values, there is no need to track them in the cache.
593 static int
594 CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue,
595                        const LoopInfo *const LI, Value *LV, Value *RV,
596                        unsigned Depth) {
597   if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV))
598     return 0;
599 
600   // Order pointer values after integer values. This helps SCEVExpander form
601   // GEPs.
602   bool LIsPointer = LV->getType()->isPointerTy(),
603        RIsPointer = RV->getType()->isPointerTy();
604   if (LIsPointer != RIsPointer)
605     return (int)LIsPointer - (int)RIsPointer;
606 
607   // Compare getValueID values.
608   unsigned LID = LV->getValueID(), RID = RV->getValueID();
609   if (LID != RID)
610     return (int)LID - (int)RID;
611 
612   // Sort arguments by their position.
613   if (const auto *LA = dyn_cast<Argument>(LV)) {
614     const auto *RA = cast<Argument>(RV);
615     unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
616     return (int)LArgNo - (int)RArgNo;
617   }
618 
619   if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
620     const auto *RGV = cast<GlobalValue>(RV);
621 
622     const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
623       auto LT = GV->getLinkage();
624       return !(GlobalValue::isPrivateLinkage(LT) ||
625                GlobalValue::isInternalLinkage(LT));
626     };
627 
628     // Use the names to distinguish the two values, but only if the
629     // names are semantically important.
630     if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
631       return LGV->getName().compare(RGV->getName());
632   }
633 
634   // For instructions, compare their loop depth, and their operand count.  This
635   // is pretty loose.
636   if (const auto *LInst = dyn_cast<Instruction>(LV)) {
637     const auto *RInst = cast<Instruction>(RV);
638 
639     // Compare loop depths.
640     const BasicBlock *LParent = LInst->getParent(),
641                      *RParent = RInst->getParent();
642     if (LParent != RParent) {
643       unsigned LDepth = LI->getLoopDepth(LParent),
644                RDepth = LI->getLoopDepth(RParent);
645       if (LDepth != RDepth)
646         return (int)LDepth - (int)RDepth;
647     }
648 
649     // Compare the number of operands.
650     unsigned LNumOps = LInst->getNumOperands(),
651              RNumOps = RInst->getNumOperands();
652     if (LNumOps != RNumOps)
653       return (int)LNumOps - (int)RNumOps;
654 
655     for (unsigned Idx : seq(LNumOps)) {
656       int Result =
657           CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx),
658                                  RInst->getOperand(Idx), Depth + 1);
659       if (Result != 0)
660         return Result;
661     }
662   }
663 
664   EqCacheValue.unionSets(LV, RV);
665   return 0;
666 }
667 
668 // Return negative, zero, or positive, if LHS is less than, equal to, or greater
669 // than RHS, respectively. A three-way result allows recursive comparisons to be
670 // more efficient.
671 // If the max analysis depth was reached, return std::nullopt, assuming we do
672 // not know if they are equivalent for sure.
673 static std::optional<int>
674 CompareSCEVComplexity(EquivalenceClasses<const SCEV *> &EqCacheSCEV,
675                       EquivalenceClasses<const Value *> &EqCacheValue,
676                       const LoopInfo *const LI, const SCEV *LHS,
677                       const SCEV *RHS, DominatorTree &DT, unsigned Depth = 0) {
678   // Fast-path: SCEVs are uniqued so we can do a quick equality check.
679   if (LHS == RHS)
680     return 0;
681 
682   // Primarily, sort the SCEVs by their getSCEVType().
683   SCEVTypes LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
684   if (LType != RType)
685     return (int)LType - (int)RType;
686 
687   if (EqCacheSCEV.isEquivalent(LHS, RHS))
688     return 0;
689 
690   if (Depth > MaxSCEVCompareDepth)
691     return std::nullopt;
692 
693   // Aside from the getSCEVType() ordering, the particular ordering
694   // isn't very important except that it's beneficial to be consistent,
695   // so that (a + b) and (b + a) don't end up as different expressions.
696   switch (LType) {
697   case scUnknown: {
698     const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
699     const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
700 
701     int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(),
702                                    RU->getValue(), Depth + 1);
703     if (X == 0)
704       EqCacheSCEV.unionSets(LHS, RHS);
705     return X;
706   }
707 
708   case scConstant: {
709     const SCEVConstant *LC = cast<SCEVConstant>(LHS);
710     const SCEVConstant *RC = cast<SCEVConstant>(RHS);
711 
712     // Compare constant values.
713     const APInt &LA = LC->getAPInt();
714     const APInt &RA = RC->getAPInt();
715     unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
716     if (LBitWidth != RBitWidth)
717       return (int)LBitWidth - (int)RBitWidth;
718     return LA.ult(RA) ? -1 : 1;
719   }
720 
721   case scVScale: {
722     const auto *LTy = cast<IntegerType>(cast<SCEVVScale>(LHS)->getType());
723     const auto *RTy = cast<IntegerType>(cast<SCEVVScale>(RHS)->getType());
724     return LTy->getBitWidth() - RTy->getBitWidth();
725   }
726 
727   case scAddRecExpr: {
728     const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
729     const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
730 
731     // There is always a dominance between two recs that are used by one SCEV,
732     // so we can safely sort recs by loop header dominance. We require such
733     // order in getAddExpr.
734     const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
735     if (LLoop != RLoop) {
736       const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
737       assert(LHead != RHead && "Two loops share the same header?");
738       if (DT.dominates(LHead, RHead))
739         return 1;
740       assert(DT.dominates(RHead, LHead) &&
741              "No dominance between recurrences used by one SCEV?");
742       return -1;
743     }
744 
745     [[fallthrough]];
746   }
747 
748   case scTruncate:
749   case scZeroExtend:
750   case scSignExtend:
751   case scPtrToInt:
752   case scAddExpr:
753   case scMulExpr:
754   case scUDivExpr:
755   case scSMaxExpr:
756   case scUMaxExpr:
757   case scSMinExpr:
758   case scUMinExpr:
759   case scSequentialUMinExpr: {
760     ArrayRef<const SCEV *> LOps = LHS->operands();
761     ArrayRef<const SCEV *> ROps = RHS->operands();
762 
763     // Lexicographically compare n-ary-like expressions.
764     unsigned LNumOps = LOps.size(), RNumOps = ROps.size();
765     if (LNumOps != RNumOps)
766       return (int)LNumOps - (int)RNumOps;
767 
768     for (unsigned i = 0; i != LNumOps; ++i) {
769       auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LOps[i],
770                                      ROps[i], DT, Depth + 1);
771       if (X != 0)
772         return X;
773     }
774     EqCacheSCEV.unionSets(LHS, RHS);
775     return 0;
776   }
777 
778   case scCouldNotCompute:
779     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
780   }
781   llvm_unreachable("Unknown SCEV kind!");
782 }
783 
784 /// Given a list of SCEV objects, order them by their complexity, and group
785 /// objects of the same complexity together by value.  When this routine is
786 /// finished, we know that any duplicates in the vector are consecutive and that
787 /// complexity is monotonically increasing.
788 ///
789 /// Note that we go take special precautions to ensure that we get deterministic
790 /// results from this routine.  In other words, we don't want the results of
791 /// this to depend on where the addresses of various SCEV objects happened to
792 /// land in memory.
793 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
794                               LoopInfo *LI, DominatorTree &DT) {
795   if (Ops.size() < 2) return;  // Noop
796 
797   EquivalenceClasses<const SCEV *> EqCacheSCEV;
798   EquivalenceClasses<const Value *> EqCacheValue;
799 
800   // Whether LHS has provably less complexity than RHS.
801   auto IsLessComplex = [&](const SCEV *LHS, const SCEV *RHS) {
802     auto Complexity =
803         CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LHS, RHS, DT);
804     return Complexity && *Complexity < 0;
805   };
806   if (Ops.size() == 2) {
807     // This is the common case, which also happens to be trivially simple.
808     // Special case it.
809     const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
810     if (IsLessComplex(RHS, LHS))
811       std::swap(LHS, RHS);
812     return;
813   }
814 
815   // Do the rough sort by complexity.
816   llvm::stable_sort(Ops, [&](const SCEV *LHS, const SCEV *RHS) {
817     return IsLessComplex(LHS, RHS);
818   });
819 
820   // Now that we are sorted by complexity, group elements of the same
821   // complexity.  Note that this is, at worst, N^2, but the vector is likely to
822   // be extremely short in practice.  Note that we take this approach because we
823   // do not want to depend on the addresses of the objects we are grouping.
824   for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
825     const SCEV *S = Ops[i];
826     unsigned Complexity = S->getSCEVType();
827 
828     // If there are any objects of the same complexity and same value as this
829     // one, group them.
830     for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
831       if (Ops[j] == S) { // Found a duplicate.
832         // Move it to immediately after i'th element.
833         std::swap(Ops[i+1], Ops[j]);
834         ++i;   // no need to rescan it.
835         if (i == e-2) return;  // Done!
836       }
837     }
838   }
839 }
840 
841 /// Returns true if \p Ops contains a huge SCEV (the subtree of S contains at
842 /// least HugeExprThreshold nodes).
843 static bool hasHugeExpression(ArrayRef<const SCEV *> Ops) {
844   return any_of(Ops, [](const SCEV *S) {
845     return S->getExpressionSize() >= HugeExprThreshold;
846   });
847 }
848 
849 //===----------------------------------------------------------------------===//
850 //                      Simple SCEV method implementations
851 //===----------------------------------------------------------------------===//
852 
853 /// Compute BC(It, K).  The result has width W.  Assume, K > 0.
854 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
855                                        ScalarEvolution &SE,
856                                        Type *ResultTy) {
857   // Handle the simplest case efficiently.
858   if (K == 1)
859     return SE.getTruncateOrZeroExtend(It, ResultTy);
860 
861   // We are using the following formula for BC(It, K):
862   //
863   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
864   //
865   // Suppose, W is the bitwidth of the return value.  We must be prepared for
866   // overflow.  Hence, we must assure that the result of our computation is
867   // equal to the accurate one modulo 2^W.  Unfortunately, division isn't
868   // safe in modular arithmetic.
869   //
870   // However, this code doesn't use exactly that formula; the formula it uses
871   // is something like the following, where T is the number of factors of 2 in
872   // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
873   // exponentiation:
874   //
875   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
876   //
877   // This formula is trivially equivalent to the previous formula.  However,
878   // this formula can be implemented much more efficiently.  The trick is that
879   // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
880   // arithmetic.  To do exact division in modular arithmetic, all we have
881   // to do is multiply by the inverse.  Therefore, this step can be done at
882   // width W.
883   //
884   // The next issue is how to safely do the division by 2^T.  The way this
885   // is done is by doing the multiplication step at a width of at least W + T
886   // bits.  This way, the bottom W+T bits of the product are accurate. Then,
887   // when we perform the division by 2^T (which is equivalent to a right shift
888   // by T), the bottom W bits are accurate.  Extra bits are okay; they'll get
889   // truncated out after the division by 2^T.
890   //
891   // In comparison to just directly using the first formula, this technique
892   // is much more efficient; using the first formula requires W * K bits,
893   // but this formula less than W + K bits. Also, the first formula requires
894   // a division step, whereas this formula only requires multiplies and shifts.
895   //
896   // It doesn't matter whether the subtraction step is done in the calculation
897   // width or the input iteration count's width; if the subtraction overflows,
898   // the result must be zero anyway.  We prefer here to do it in the width of
899   // the induction variable because it helps a lot for certain cases; CodeGen
900   // isn't smart enough to ignore the overflow, which leads to much less
901   // efficient code if the width of the subtraction is wider than the native
902   // register width.
903   //
904   // (It's possible to not widen at all by pulling out factors of 2 before
905   // the multiplication; for example, K=2 can be calculated as
906   // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
907   // extra arithmetic, so it's not an obvious win, and it gets
908   // much more complicated for K > 3.)
909 
910   // Protection from insane SCEVs; this bound is conservative,
911   // but it probably doesn't matter.
912   if (K > 1000)
913     return SE.getCouldNotCompute();
914 
915   unsigned W = SE.getTypeSizeInBits(ResultTy);
916 
917   // Calculate K! / 2^T and T; we divide out the factors of two before
918   // multiplying for calculating K! / 2^T to avoid overflow.
919   // Other overflow doesn't matter because we only care about the bottom
920   // W bits of the result.
921   APInt OddFactorial(W, 1);
922   unsigned T = 1;
923   for (unsigned i = 3; i <= K; ++i) {
924     APInt Mult(W, i);
925     unsigned TwoFactors = Mult.countr_zero();
926     T += TwoFactors;
927     Mult.lshrInPlace(TwoFactors);
928     OddFactorial *= Mult;
929   }
930 
931   // We need at least W + T bits for the multiplication step
932   unsigned CalculationBits = W + T;
933 
934   // Calculate 2^T, at width T+W.
935   APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
936 
937   // Calculate the multiplicative inverse of K! / 2^T;
938   // this multiplication factor will perform the exact division by
939   // K! / 2^T.
940   APInt Mod = APInt::getSignedMinValue(W+1);
941   APInt MultiplyFactor = OddFactorial.zext(W+1);
942   MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
943   MultiplyFactor = MultiplyFactor.trunc(W);
944 
945   // Calculate the product, at width T+W
946   IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
947                                                       CalculationBits);
948   const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
949   for (unsigned i = 1; i != K; ++i) {
950     const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
951     Dividend = SE.getMulExpr(Dividend,
952                              SE.getTruncateOrZeroExtend(S, CalculationTy));
953   }
954 
955   // Divide by 2^T
956   const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
957 
958   // Truncate the result, and divide by K! / 2^T.
959 
960   return SE.getMulExpr(SE.getConstant(MultiplyFactor),
961                        SE.getTruncateOrZeroExtend(DivResult, ResultTy));
962 }
963 
964 /// Return the value of this chain of recurrences at the specified iteration
965 /// number.  We can evaluate this recurrence by multiplying each element in the
966 /// chain by the binomial coefficient corresponding to it.  In other words, we
967 /// can evaluate {A,+,B,+,C,+,D} as:
968 ///
969 ///   A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
970 ///
971 /// where BC(It, k) stands for binomial coefficient.
972 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
973                                                 ScalarEvolution &SE) const {
974   return evaluateAtIteration(operands(), It, SE);
975 }
976 
977 const SCEV *
978 SCEVAddRecExpr::evaluateAtIteration(ArrayRef<const SCEV *> Operands,
979                                     const SCEV *It, ScalarEvolution &SE) {
980   assert(Operands.size() > 0);
981   const SCEV *Result = Operands[0];
982   for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
983     // The computation is correct in the face of overflow provided that the
984     // multiplication is performed _after_ the evaluation of the binomial
985     // coefficient.
986     const SCEV *Coeff = BinomialCoefficient(It, i, SE, Result->getType());
987     if (isa<SCEVCouldNotCompute>(Coeff))
988       return Coeff;
989 
990     Result = SE.getAddExpr(Result, SE.getMulExpr(Operands[i], Coeff));
991   }
992   return Result;
993 }
994 
995 //===----------------------------------------------------------------------===//
996 //                    SCEV Expression folder implementations
997 //===----------------------------------------------------------------------===//
998 
999 const SCEV *ScalarEvolution::getLosslessPtrToIntExpr(const SCEV *Op,
1000                                                      unsigned Depth) {
1001   assert(Depth <= 1 &&
1002          "getLosslessPtrToIntExpr() should self-recurse at most once.");
1003 
1004   // We could be called with an integer-typed operands during SCEV rewrites.
1005   // Since the operand is an integer already, just perform zext/trunc/self cast.
1006   if (!Op->getType()->isPointerTy())
1007     return Op;
1008 
1009   // What would be an ID for such a SCEV cast expression?
1010   FoldingSetNodeID ID;
1011   ID.AddInteger(scPtrToInt);
1012   ID.AddPointer(Op);
1013 
1014   void *IP = nullptr;
1015 
1016   // Is there already an expression for such a cast?
1017   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1018     return S;
1019 
1020   // It isn't legal for optimizations to construct new ptrtoint expressions
1021   // for non-integral pointers.
1022   if (getDataLayout().isNonIntegralPointerType(Op->getType()))
1023     return getCouldNotCompute();
1024 
1025   Type *IntPtrTy = getDataLayout().getIntPtrType(Op->getType());
1026 
1027   // We can only trivially model ptrtoint if SCEV's effective (integer) type
1028   // is sufficiently wide to represent all possible pointer values.
1029   // We could theoretically teach SCEV to truncate wider pointers, but
1030   // that isn't implemented for now.
1031   if (getDataLayout().getTypeSizeInBits(getEffectiveSCEVType(Op->getType())) !=
1032       getDataLayout().getTypeSizeInBits(IntPtrTy))
1033     return getCouldNotCompute();
1034 
1035   // If not, is this expression something we can't reduce any further?
1036   if (auto *U = dyn_cast<SCEVUnknown>(Op)) {
1037     // Perform some basic constant folding. If the operand of the ptr2int cast
1038     // is a null pointer, don't create a ptr2int SCEV expression (that will be
1039     // left as-is), but produce a zero constant.
1040     // NOTE: We could handle a more general case, but lack motivational cases.
1041     if (isa<ConstantPointerNull>(U->getValue()))
1042       return getZero(IntPtrTy);
1043 
1044     // Create an explicit cast node.
1045     // We can reuse the existing insert position since if we get here,
1046     // we won't have made any changes which would invalidate it.
1047     SCEV *S = new (SCEVAllocator)
1048         SCEVPtrToIntExpr(ID.Intern(SCEVAllocator), Op, IntPtrTy);
1049     UniqueSCEVs.InsertNode(S, IP);
1050     registerUser(S, Op);
1051     return S;
1052   }
1053 
1054   assert(Depth == 0 && "getLosslessPtrToIntExpr() should not self-recurse for "
1055                        "non-SCEVUnknown's.");
1056 
1057   // Otherwise, we've got some expression that is more complex than just a
1058   // single SCEVUnknown. But we don't want to have a SCEVPtrToIntExpr of an
1059   // arbitrary expression, we want to have SCEVPtrToIntExpr of an SCEVUnknown
1060   // only, and the expressions must otherwise be integer-typed.
1061   // So sink the cast down to the SCEVUnknown's.
1062 
1063   /// The SCEVPtrToIntSinkingRewriter takes a scalar evolution expression,
1064   /// which computes a pointer-typed value, and rewrites the whole expression
1065   /// tree so that *all* the computations are done on integers, and the only
1066   /// pointer-typed operands in the expression are SCEVUnknown.
1067   class SCEVPtrToIntSinkingRewriter
1068       : public SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter> {
1069     using Base = SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter>;
1070 
1071   public:
1072     SCEVPtrToIntSinkingRewriter(ScalarEvolution &SE) : SCEVRewriteVisitor(SE) {}
1073 
1074     static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE) {
1075       SCEVPtrToIntSinkingRewriter Rewriter(SE);
1076       return Rewriter.visit(Scev);
1077     }
1078 
1079     const SCEV *visit(const SCEV *S) {
1080       Type *STy = S->getType();
1081       // If the expression is not pointer-typed, just keep it as-is.
1082       if (!STy->isPointerTy())
1083         return S;
1084       // Else, recursively sink the cast down into it.
1085       return Base::visit(S);
1086     }
1087 
1088     const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
1089       SmallVector<const SCEV *, 2> Operands;
1090       bool Changed = false;
1091       for (const auto *Op : Expr->operands()) {
1092         Operands.push_back(visit(Op));
1093         Changed |= Op != Operands.back();
1094       }
1095       return !Changed ? Expr : SE.getAddExpr(Operands, Expr->getNoWrapFlags());
1096     }
1097 
1098     const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
1099       SmallVector<const SCEV *, 2> Operands;
1100       bool Changed = false;
1101       for (const auto *Op : Expr->operands()) {
1102         Operands.push_back(visit(Op));
1103         Changed |= Op != Operands.back();
1104       }
1105       return !Changed ? Expr : SE.getMulExpr(Operands, Expr->getNoWrapFlags());
1106     }
1107 
1108     const SCEV *visitUnknown(const SCEVUnknown *Expr) {
1109       assert(Expr->getType()->isPointerTy() &&
1110              "Should only reach pointer-typed SCEVUnknown's.");
1111       return SE.getLosslessPtrToIntExpr(Expr, /*Depth=*/1);
1112     }
1113   };
1114 
1115   // And actually perform the cast sinking.
1116   const SCEV *IntOp = SCEVPtrToIntSinkingRewriter::rewrite(Op, *this);
1117   assert(IntOp->getType()->isIntegerTy() &&
1118          "We must have succeeded in sinking the cast, "
1119          "and ending up with an integer-typed expression!");
1120   return IntOp;
1121 }
1122 
1123 const SCEV *ScalarEvolution::getPtrToIntExpr(const SCEV *Op, Type *Ty) {
1124   assert(Ty->isIntegerTy() && "Target type must be an integer type!");
1125 
1126   const SCEV *IntOp = getLosslessPtrToIntExpr(Op);
1127   if (isa<SCEVCouldNotCompute>(IntOp))
1128     return IntOp;
1129 
1130   return getTruncateOrZeroExtend(IntOp, Ty);
1131 }
1132 
1133 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, Type *Ty,
1134                                              unsigned Depth) {
1135   assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1136          "This is not a truncating conversion!");
1137   assert(isSCEVable(Ty) &&
1138          "This is not a conversion to a SCEVable type!");
1139   assert(!Op->getType()->isPointerTy() && "Can't truncate pointer!");
1140   Ty = getEffectiveSCEVType(Ty);
1141 
1142   FoldingSetNodeID ID;
1143   ID.AddInteger(scTruncate);
1144   ID.AddPointer(Op);
1145   ID.AddPointer(Ty);
1146   void *IP = nullptr;
1147   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1148 
1149   // Fold if the operand is constant.
1150   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1151     return getConstant(
1152       cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1153 
1154   // trunc(trunc(x)) --> trunc(x)
1155   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
1156     return getTruncateExpr(ST->getOperand(), Ty, Depth + 1);
1157 
1158   // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1159   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1160     return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1);
1161 
1162   // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1163   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1164     return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1);
1165 
1166   if (Depth > MaxCastDepth) {
1167     SCEV *S =
1168         new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty);
1169     UniqueSCEVs.InsertNode(S, IP);
1170     registerUser(S, Op);
1171     return S;
1172   }
1173 
1174   // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and
1175   // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN),
1176   // if after transforming we have at most one truncate, not counting truncates
1177   // that replace other casts.
1178   if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) {
1179     auto *CommOp = cast<SCEVCommutativeExpr>(Op);
1180     SmallVector<const SCEV *, 4> Operands;
1181     unsigned numTruncs = 0;
1182     for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2;
1183          ++i) {
1184       const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1);
1185       if (!isa<SCEVIntegralCastExpr>(CommOp->getOperand(i)) &&
1186           isa<SCEVTruncateExpr>(S))
1187         numTruncs++;
1188       Operands.push_back(S);
1189     }
1190     if (numTruncs < 2) {
1191       if (isa<SCEVAddExpr>(Op))
1192         return getAddExpr(Operands);
1193       if (isa<SCEVMulExpr>(Op))
1194         return getMulExpr(Operands);
1195       llvm_unreachable("Unexpected SCEV type for Op.");
1196     }
1197     // Although we checked in the beginning that ID is not in the cache, it is
1198     // possible that during recursion and different modification ID was inserted
1199     // into the cache. So if we find it, just return it.
1200     if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1201       return S;
1202   }
1203 
1204   // If the input value is a chrec scev, truncate the chrec's operands.
1205   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1206     SmallVector<const SCEV *, 4> Operands;
1207     for (const SCEV *Op : AddRec->operands())
1208       Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1));
1209     return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1210   }
1211 
1212   // Return zero if truncating to known zeros.
1213   uint32_t MinTrailingZeros = getMinTrailingZeros(Op);
1214   if (MinTrailingZeros >= getTypeSizeInBits(Ty))
1215     return getZero(Ty);
1216 
1217   // The cast wasn't folded; create an explicit cast node. We can reuse
1218   // the existing insert position since if we get here, we won't have
1219   // made any changes which would invalidate it.
1220   SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1221                                                  Op, Ty);
1222   UniqueSCEVs.InsertNode(S, IP);
1223   registerUser(S, Op);
1224   return S;
1225 }
1226 
1227 // Get the limit of a recurrence such that incrementing by Step cannot cause
1228 // signed overflow as long as the value of the recurrence within the
1229 // loop does not exceed this limit before incrementing.
1230 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1231                                                  ICmpInst::Predicate *Pred,
1232                                                  ScalarEvolution *SE) {
1233   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1234   if (SE->isKnownPositive(Step)) {
1235     *Pred = ICmpInst::ICMP_SLT;
1236     return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1237                            SE->getSignedRangeMax(Step));
1238   }
1239   if (SE->isKnownNegative(Step)) {
1240     *Pred = ICmpInst::ICMP_SGT;
1241     return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1242                            SE->getSignedRangeMin(Step));
1243   }
1244   return nullptr;
1245 }
1246 
1247 // Get the limit of a recurrence such that incrementing by Step cannot cause
1248 // unsigned overflow as long as the value of the recurrence within the loop does
1249 // not exceed this limit before incrementing.
1250 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1251                                                    ICmpInst::Predicate *Pred,
1252                                                    ScalarEvolution *SE) {
1253   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1254   *Pred = ICmpInst::ICMP_ULT;
1255 
1256   return SE->getConstant(APInt::getMinValue(BitWidth) -
1257                          SE->getUnsignedRangeMax(Step));
1258 }
1259 
1260 namespace {
1261 
1262 struct ExtendOpTraitsBase {
1263   typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *,
1264                                                           unsigned);
1265 };
1266 
1267 // Used to make code generic over signed and unsigned overflow.
1268 template <typename ExtendOp> struct ExtendOpTraits {
1269   // Members present:
1270   //
1271   // static const SCEV::NoWrapFlags WrapType;
1272   //
1273   // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1274   //
1275   // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1276   //                                           ICmpInst::Predicate *Pred,
1277   //                                           ScalarEvolution *SE);
1278 };
1279 
1280 template <>
1281 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1282   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1283 
1284   static const GetExtendExprTy GetExtendExpr;
1285 
1286   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1287                                              ICmpInst::Predicate *Pred,
1288                                              ScalarEvolution *SE) {
1289     return getSignedOverflowLimitForStep(Step, Pred, SE);
1290   }
1291 };
1292 
1293 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1294     SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr;
1295 
1296 template <>
1297 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1298   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1299 
1300   static const GetExtendExprTy GetExtendExpr;
1301 
1302   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1303                                              ICmpInst::Predicate *Pred,
1304                                              ScalarEvolution *SE) {
1305     return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1306   }
1307 };
1308 
1309 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1310     SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr;
1311 
1312 } // end anonymous namespace
1313 
1314 // The recurrence AR has been shown to have no signed/unsigned wrap or something
1315 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1316 // easily prove NSW/NUW for its preincrement or postincrement sibling. This
1317 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1318 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1319 // expression "Step + sext/zext(PreIncAR)" is congruent with
1320 // "sext/zext(PostIncAR)"
1321 template <typename ExtendOpTy>
1322 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1323                                         ScalarEvolution *SE, unsigned Depth) {
1324   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1325   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1326 
1327   const Loop *L = AR->getLoop();
1328   const SCEV *Start = AR->getStart();
1329   const SCEV *Step = AR->getStepRecurrence(*SE);
1330 
1331   // Check for a simple looking step prior to loop entry.
1332   const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1333   if (!SA)
1334     return nullptr;
1335 
1336   // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1337   // subtraction is expensive. For this purpose, perform a quick and dirty
1338   // difference, by checking for Step in the operand list. Note, that
1339   // SA might have repeated ops, like %a + %a + ..., so only remove one.
1340   SmallVector<const SCEV *, 4> DiffOps(SA->operands());
1341   for (auto It = DiffOps.begin(); It != DiffOps.end(); ++It)
1342     if (*It == Step) {
1343       DiffOps.erase(It);
1344       break;
1345     }
1346 
1347   if (DiffOps.size() == SA->getNumOperands())
1348     return nullptr;
1349 
1350   // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1351   // `Step`:
1352 
1353   // 1. NSW/NUW flags on the step increment.
1354   auto PreStartFlags =
1355     ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
1356   const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1357   const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1358       SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1359 
1360   // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1361   // "S+X does not sign/unsign-overflow".
1362   //
1363 
1364   const SCEV *BECount = SE->getBackedgeTakenCount(L);
1365   if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1366       !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1367     return PreStart;
1368 
1369   // 2. Direct overflow check on the step operation's expression.
1370   unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1371   Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1372   const SCEV *OperandExtendedStart =
1373       SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
1374                      (SE->*GetExtendExpr)(Step, WideTy, Depth));
1375   if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
1376     if (PreAR && AR->getNoWrapFlags(WrapType)) {
1377       // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1378       // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1379       // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`.  Cache this fact.
1380       SE->setNoWrapFlags(const_cast<SCEVAddRecExpr *>(PreAR), WrapType);
1381     }
1382     return PreStart;
1383   }
1384 
1385   // 3. Loop precondition.
1386   ICmpInst::Predicate Pred;
1387   const SCEV *OverflowLimit =
1388       ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1389 
1390   if (OverflowLimit &&
1391       SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1392     return PreStart;
1393 
1394   return nullptr;
1395 }
1396 
1397 // Get the normalized zero or sign extended expression for this AddRec's Start.
1398 template <typename ExtendOpTy>
1399 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1400                                         ScalarEvolution *SE,
1401                                         unsigned Depth) {
1402   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1403 
1404   const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth);
1405   if (!PreStart)
1406     return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth);
1407 
1408   return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty,
1409                                              Depth),
1410                         (SE->*GetExtendExpr)(PreStart, Ty, Depth));
1411 }
1412 
1413 // Try to prove away overflow by looking at "nearby" add recurrences.  A
1414 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1415 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1416 //
1417 // Formally:
1418 //
1419 //     {S,+,X} == {S-T,+,X} + T
1420 //  => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1421 //
1422 // If ({S-T,+,X} + T) does not overflow  ... (1)
1423 //
1424 //  RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1425 //
1426 // If {S-T,+,X} does not overflow  ... (2)
1427 //
1428 //  RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1429 //      == {Ext(S-T)+Ext(T),+,Ext(X)}
1430 //
1431 // If (S-T)+T does not overflow  ... (3)
1432 //
1433 //  RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1434 //      == {Ext(S),+,Ext(X)} == LHS
1435 //
1436 // Thus, if (1), (2) and (3) are true for some T, then
1437 //   Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1438 //
1439 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1440 // does not overflow" restricted to the 0th iteration.  Therefore we only need
1441 // to check for (1) and (2).
1442 //
1443 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1444 // is `Delta` (defined below).
1445 template <typename ExtendOpTy>
1446 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1447                                                 const SCEV *Step,
1448                                                 const Loop *L) {
1449   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1450 
1451   // We restrict `Start` to a constant to prevent SCEV from spending too much
1452   // time here.  It is correct (but more expensive) to continue with a
1453   // non-constant `Start` and do a general SCEV subtraction to compute
1454   // `PreStart` below.
1455   const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1456   if (!StartC)
1457     return false;
1458 
1459   APInt StartAI = StartC->getAPInt();
1460 
1461   for (unsigned Delta : {-2, -1, 1, 2}) {
1462     const SCEV *PreStart = getConstant(StartAI - Delta);
1463 
1464     FoldingSetNodeID ID;
1465     ID.AddInteger(scAddRecExpr);
1466     ID.AddPointer(PreStart);
1467     ID.AddPointer(Step);
1468     ID.AddPointer(L);
1469     void *IP = nullptr;
1470     const auto *PreAR =
1471       static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1472 
1473     // Give up if we don't already have the add recurrence we need because
1474     // actually constructing an add recurrence is relatively expensive.
1475     if (PreAR && PreAR->getNoWrapFlags(WrapType)) {  // proves (2)
1476       const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1477       ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1478       const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1479           DeltaS, &Pred, this);
1480       if (Limit && isKnownPredicate(Pred, PreAR, Limit))  // proves (1)
1481         return true;
1482     }
1483   }
1484 
1485   return false;
1486 }
1487 
1488 // Finds an integer D for an expression (C + x + y + ...) such that the top
1489 // level addition in (D + (C - D + x + y + ...)) would not wrap (signed or
1490 // unsigned) and the number of trailing zeros of (C - D + x + y + ...) is
1491 // maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and
1492 // the (C + x + y + ...) expression is \p WholeAddExpr.
1493 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE,
1494                                             const SCEVConstant *ConstantTerm,
1495                                             const SCEVAddExpr *WholeAddExpr) {
1496   const APInt &C = ConstantTerm->getAPInt();
1497   const unsigned BitWidth = C.getBitWidth();
1498   // Find number of trailing zeros of (x + y + ...) w/o the C first:
1499   uint32_t TZ = BitWidth;
1500   for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I)
1501     TZ = std::min(TZ, SE.getMinTrailingZeros(WholeAddExpr->getOperand(I)));
1502   if (TZ) {
1503     // Set D to be as many least significant bits of C as possible while still
1504     // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap:
1505     return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C;
1506   }
1507   return APInt(BitWidth, 0);
1508 }
1509 
1510 // Finds an integer D for an affine AddRec expression {C,+,x} such that the top
1511 // level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the
1512 // number of trailing zeros of (C - D + x * n) is maximized, where C is the \p
1513 // ConstantStart, x is an arbitrary \p Step, and n is the loop trip count.
1514 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE,
1515                                             const APInt &ConstantStart,
1516                                             const SCEV *Step) {
1517   const unsigned BitWidth = ConstantStart.getBitWidth();
1518   const uint32_t TZ = SE.getMinTrailingZeros(Step);
1519   if (TZ)
1520     return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth)
1521                          : ConstantStart;
1522   return APInt(BitWidth, 0);
1523 }
1524 
1525 static void insertFoldCacheEntry(
1526     const ScalarEvolution::FoldID &ID, const SCEV *S,
1527     DenseMap<ScalarEvolution::FoldID, const SCEV *> &FoldCache,
1528     DenseMap<const SCEV *, SmallVector<ScalarEvolution::FoldID, 2>>
1529         &FoldCacheUser) {
1530   auto I = FoldCache.insert({ID, S});
1531   if (!I.second) {
1532     // Remove FoldCacheUser entry for ID when replacing an existing FoldCache
1533     // entry.
1534     auto &UserIDs = FoldCacheUser[I.first->second];
1535     assert(count(UserIDs, ID) == 1 && "unexpected duplicates in UserIDs");
1536     for (unsigned I = 0; I != UserIDs.size(); ++I)
1537       if (UserIDs[I] == ID) {
1538         std::swap(UserIDs[I], UserIDs.back());
1539         break;
1540       }
1541     UserIDs.pop_back();
1542     I.first->second = S;
1543   }
1544   auto R = FoldCacheUser.insert({S, {}});
1545   R.first->second.push_back(ID);
1546 }
1547 
1548 const SCEV *
1549 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1550   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1551          "This is not an extending conversion!");
1552   assert(isSCEVable(Ty) &&
1553          "This is not a conversion to a SCEVable type!");
1554   assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1555   Ty = getEffectiveSCEVType(Ty);
1556 
1557   FoldID ID(scZeroExtend, Op, Ty);
1558   auto Iter = FoldCache.find(ID);
1559   if (Iter != FoldCache.end())
1560     return Iter->second;
1561 
1562   const SCEV *S = getZeroExtendExprImpl(Op, Ty, Depth);
1563   if (!isa<SCEVZeroExtendExpr>(S))
1564     insertFoldCacheEntry(ID, S, FoldCache, FoldCacheUser);
1565   return S;
1566 }
1567 
1568 const SCEV *ScalarEvolution::getZeroExtendExprImpl(const SCEV *Op, Type *Ty,
1569                                                    unsigned Depth) {
1570   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1571          "This is not an extending conversion!");
1572   assert(isSCEVable(Ty) && "This is not a conversion to a SCEVable type!");
1573   assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1574 
1575   // Fold if the operand is constant.
1576   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1577     return getConstant(SC->getAPInt().zext(getTypeSizeInBits(Ty)));
1578 
1579   // zext(zext(x)) --> zext(x)
1580   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1581     return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1582 
1583   // Before doing any expensive analysis, check to see if we've already
1584   // computed a SCEV for this Op and Ty.
1585   FoldingSetNodeID ID;
1586   ID.AddInteger(scZeroExtend);
1587   ID.AddPointer(Op);
1588   ID.AddPointer(Ty);
1589   void *IP = nullptr;
1590   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1591   if (Depth > MaxCastDepth) {
1592     SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1593                                                      Op, Ty);
1594     UniqueSCEVs.InsertNode(S, IP);
1595     registerUser(S, Op);
1596     return S;
1597   }
1598 
1599   // zext(trunc(x)) --> zext(x) or x or trunc(x)
1600   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1601     // It's possible the bits taken off by the truncate were all zero bits. If
1602     // so, we should be able to simplify this further.
1603     const SCEV *X = ST->getOperand();
1604     ConstantRange CR = getUnsignedRange(X);
1605     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1606     unsigned NewBits = getTypeSizeInBits(Ty);
1607     if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1608             CR.zextOrTrunc(NewBits)))
1609       return getTruncateOrZeroExtend(X, Ty, Depth);
1610   }
1611 
1612   // If the input value is a chrec scev, and we can prove that the value
1613   // did not overflow the old, smaller, value, we can zero extend all of the
1614   // operands (often constants).  This allows analysis of something like
1615   // this:  for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1616   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1617     if (AR->isAffine()) {
1618       const SCEV *Start = AR->getStart();
1619       const SCEV *Step = AR->getStepRecurrence(*this);
1620       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1621       const Loop *L = AR->getLoop();
1622 
1623       // If we have special knowledge that this addrec won't overflow,
1624       // we don't need to do any further analysis.
1625       if (AR->hasNoUnsignedWrap()) {
1626         Start =
1627             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1);
1628         Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1629         return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1630       }
1631 
1632       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1633       // Note that this serves two purposes: It filters out loops that are
1634       // simply not analyzable, and it covers the case where this code is
1635       // being called from within backedge-taken count analysis, such that
1636       // attempting to ask for the backedge-taken count would likely result
1637       // in infinite recursion. In the later case, the analysis code will
1638       // cope with a conservative value, and it will take care to purge
1639       // that value once it has finished.
1640       const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
1641       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1642         // Manually compute the final value for AR, checking for overflow.
1643 
1644         // Check whether the backedge-taken count can be losslessly casted to
1645         // the addrec's type. The count is always unsigned.
1646         const SCEV *CastedMaxBECount =
1647             getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
1648         const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
1649             CastedMaxBECount, MaxBECount->getType(), Depth);
1650         if (MaxBECount == RecastedMaxBECount) {
1651           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1652           // Check whether Start+Step*MaxBECount has no unsigned overflow.
1653           const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step,
1654                                         SCEV::FlagAnyWrap, Depth + 1);
1655           const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul,
1656                                                           SCEV::FlagAnyWrap,
1657                                                           Depth + 1),
1658                                                WideTy, Depth + 1);
1659           const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
1660           const SCEV *WideMaxBECount =
1661             getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1662           const SCEV *OperandExtendedAdd =
1663             getAddExpr(WideStart,
1664                        getMulExpr(WideMaxBECount,
1665                                   getZeroExtendExpr(Step, WideTy, Depth + 1),
1666                                   SCEV::FlagAnyWrap, Depth + 1),
1667                        SCEV::FlagAnyWrap, Depth + 1);
1668           if (ZAdd == OperandExtendedAdd) {
1669             // Cache knowledge of AR NUW, which is propagated to this AddRec.
1670             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1671             // Return the expression with the addrec on the outside.
1672             Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1673                                                              Depth + 1);
1674             Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1675             return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1676           }
1677           // Similar to above, only this time treat the step value as signed.
1678           // This covers loops that count down.
1679           OperandExtendedAdd =
1680             getAddExpr(WideStart,
1681                        getMulExpr(WideMaxBECount,
1682                                   getSignExtendExpr(Step, WideTy, Depth + 1),
1683                                   SCEV::FlagAnyWrap, Depth + 1),
1684                        SCEV::FlagAnyWrap, Depth + 1);
1685           if (ZAdd == OperandExtendedAdd) {
1686             // Cache knowledge of AR NW, which is propagated to this AddRec.
1687             // Negative step causes unsigned wrap, but it still can't self-wrap.
1688             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1689             // Return the expression with the addrec on the outside.
1690             Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1691                                                              Depth + 1);
1692             Step = getSignExtendExpr(Step, Ty, Depth + 1);
1693             return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1694           }
1695         }
1696       }
1697 
1698       // Normally, in the cases we can prove no-overflow via a
1699       // backedge guarding condition, we can also compute a backedge
1700       // taken count for the loop.  The exceptions are assumptions and
1701       // guards present in the loop -- SCEV is not great at exploiting
1702       // these to compute max backedge taken counts, but can still use
1703       // these to prove lack of overflow.  Use this fact to avoid
1704       // doing extra work that may not pay off.
1705       if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1706           !AC.assumptions().empty()) {
1707 
1708         auto NewFlags = proveNoUnsignedWrapViaInduction(AR);
1709         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1710         if (AR->hasNoUnsignedWrap()) {
1711           // Same as nuw case above - duplicated here to avoid a compile time
1712           // issue.  It's not clear that the order of checks does matter, but
1713           // it's one of two issue possible causes for a change which was
1714           // reverted.  Be conservative for the moment.
1715           Start =
1716               getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1);
1717           Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1718           return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1719         }
1720 
1721         // For a negative step, we can extend the operands iff doing so only
1722         // traverses values in the range zext([0,UINT_MAX]).
1723         if (isKnownNegative(Step)) {
1724           const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1725                                       getSignedRangeMin(Step));
1726           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1727               isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) {
1728             // Cache knowledge of AR NW, which is propagated to this
1729             // AddRec.  Negative step causes unsigned wrap, but it
1730             // still can't self-wrap.
1731             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1732             // Return the expression with the addrec on the outside.
1733             Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1734                                                              Depth + 1);
1735             Step = getSignExtendExpr(Step, Ty, Depth + 1);
1736             return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1737           }
1738         }
1739       }
1740 
1741       // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw>
1742       // if D + (C - D + Step * n) could be proven to not unsigned wrap
1743       // where D maximizes the number of trailing zeros of (C - D + Step * n)
1744       if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
1745         const APInt &C = SC->getAPInt();
1746         const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
1747         if (D != 0) {
1748           const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1749           const SCEV *SResidual =
1750               getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
1751           const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1752           return getAddExpr(SZExtD, SZExtR,
1753                             (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1754                             Depth + 1);
1755         }
1756       }
1757 
1758       if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1759         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1760         Start =
1761             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1);
1762         Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1763         return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1764       }
1765     }
1766 
1767   // zext(A % B) --> zext(A) % zext(B)
1768   {
1769     const SCEV *LHS;
1770     const SCEV *RHS;
1771     if (matchURem(Op, LHS, RHS))
1772       return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1),
1773                          getZeroExtendExpr(RHS, Ty, Depth + 1));
1774   }
1775 
1776   // zext(A / B) --> zext(A) / zext(B).
1777   if (auto *Div = dyn_cast<SCEVUDivExpr>(Op))
1778     return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1),
1779                        getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1));
1780 
1781   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1782     // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1783     if (SA->hasNoUnsignedWrap()) {
1784       // If the addition does not unsign overflow then we can, by definition,
1785       // commute the zero extension with the addition operation.
1786       SmallVector<const SCEV *, 4> Ops;
1787       for (const auto *Op : SA->operands())
1788         Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1789       return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1);
1790     }
1791 
1792     // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...))
1793     // if D + (C - D + x + y + ...) could be proven to not unsigned wrap
1794     // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1795     //
1796     // Often address arithmetics contain expressions like
1797     // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))).
1798     // This transformation is useful while proving that such expressions are
1799     // equal or differ by a small constant amount, see LoadStoreVectorizer pass.
1800     if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1801       const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1802       if (D != 0) {
1803         const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1804         const SCEV *SResidual =
1805             getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth);
1806         const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1807         return getAddExpr(SZExtD, SZExtR,
1808                           (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1809                           Depth + 1);
1810       }
1811     }
1812   }
1813 
1814   if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) {
1815     // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw>
1816     if (SM->hasNoUnsignedWrap()) {
1817       // If the multiply does not unsign overflow then we can, by definition,
1818       // commute the zero extension with the multiply operation.
1819       SmallVector<const SCEV *, 4> Ops;
1820       for (const auto *Op : SM->operands())
1821         Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1822       return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1);
1823     }
1824 
1825     // zext(2^K * (trunc X to iN)) to iM ->
1826     // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw>
1827     //
1828     // Proof:
1829     //
1830     //     zext(2^K * (trunc X to iN)) to iM
1831     //   = zext((trunc X to iN) << K) to iM
1832     //   = zext((trunc X to i{N-K}) << K)<nuw> to iM
1833     //     (because shl removes the top K bits)
1834     //   = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM
1835     //   = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>.
1836     //
1837     if (SM->getNumOperands() == 2)
1838       if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0)))
1839         if (MulLHS->getAPInt().isPowerOf2())
1840           if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) {
1841             int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) -
1842                                MulLHS->getAPInt().logBase2();
1843             Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits);
1844             return getMulExpr(
1845                 getZeroExtendExpr(MulLHS, Ty),
1846                 getZeroExtendExpr(
1847                     getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty),
1848                 SCEV::FlagNUW, Depth + 1);
1849           }
1850   }
1851 
1852   // zext(umin(x, y)) -> umin(zext(x), zext(y))
1853   // zext(umax(x, y)) -> umax(zext(x), zext(y))
1854   if (isa<SCEVUMinExpr>(Op) || isa<SCEVUMaxExpr>(Op)) {
1855     auto *MinMax = cast<SCEVMinMaxExpr>(Op);
1856     SmallVector<const SCEV *, 4> Operands;
1857     for (auto *Operand : MinMax->operands())
1858       Operands.push_back(getZeroExtendExpr(Operand, Ty));
1859     if (isa<SCEVUMinExpr>(MinMax))
1860       return getUMinExpr(Operands);
1861     return getUMaxExpr(Operands);
1862   }
1863 
1864   // zext(umin_seq(x, y)) -> umin_seq(zext(x), zext(y))
1865   if (auto *MinMax = dyn_cast<SCEVSequentialMinMaxExpr>(Op)) {
1866     assert(isa<SCEVSequentialUMinExpr>(MinMax) && "Not supported!");
1867     SmallVector<const SCEV *, 4> Operands;
1868     for (auto *Operand : MinMax->operands())
1869       Operands.push_back(getZeroExtendExpr(Operand, Ty));
1870     return getUMinExpr(Operands, /*Sequential*/ true);
1871   }
1872 
1873   // The cast wasn't folded; create an explicit cast node.
1874   // Recompute the insert position, as it may have been invalidated.
1875   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1876   SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1877                                                    Op, Ty);
1878   UniqueSCEVs.InsertNode(S, IP);
1879   registerUser(S, Op);
1880   return S;
1881 }
1882 
1883 const SCEV *
1884 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1885   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1886          "This is not an extending conversion!");
1887   assert(isSCEVable(Ty) &&
1888          "This is not a conversion to a SCEVable type!");
1889   assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1890   Ty = getEffectiveSCEVType(Ty);
1891 
1892   FoldID ID(scSignExtend, Op, Ty);
1893   auto Iter = FoldCache.find(ID);
1894   if (Iter != FoldCache.end())
1895     return Iter->second;
1896 
1897   const SCEV *S = getSignExtendExprImpl(Op, Ty, Depth);
1898   if (!isa<SCEVSignExtendExpr>(S))
1899     insertFoldCacheEntry(ID, S, FoldCache, FoldCacheUser);
1900   return S;
1901 }
1902 
1903 const SCEV *ScalarEvolution::getSignExtendExprImpl(const SCEV *Op, Type *Ty,
1904                                                    unsigned Depth) {
1905   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1906          "This is not an extending conversion!");
1907   assert(isSCEVable(Ty) && "This is not a conversion to a SCEVable type!");
1908   assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1909   Ty = getEffectiveSCEVType(Ty);
1910 
1911   // Fold if the operand is constant.
1912   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1913     return getConstant(SC->getAPInt().sext(getTypeSizeInBits(Ty)));
1914 
1915   // sext(sext(x)) --> sext(x)
1916   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1917     return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1);
1918 
1919   // sext(zext(x)) --> zext(x)
1920   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1921     return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1922 
1923   // Before doing any expensive analysis, check to see if we've already
1924   // computed a SCEV for this Op and Ty.
1925   FoldingSetNodeID ID;
1926   ID.AddInteger(scSignExtend);
1927   ID.AddPointer(Op);
1928   ID.AddPointer(Ty);
1929   void *IP = nullptr;
1930   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1931   // Limit recursion depth.
1932   if (Depth > MaxCastDepth) {
1933     SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1934                                                      Op, Ty);
1935     UniqueSCEVs.InsertNode(S, IP);
1936     registerUser(S, Op);
1937     return S;
1938   }
1939 
1940   // sext(trunc(x)) --> sext(x) or x or trunc(x)
1941   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1942     // It's possible the bits taken off by the truncate were all sign bits. If
1943     // so, we should be able to simplify this further.
1944     const SCEV *X = ST->getOperand();
1945     ConstantRange CR = getSignedRange(X);
1946     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1947     unsigned NewBits = getTypeSizeInBits(Ty);
1948     if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1949             CR.sextOrTrunc(NewBits)))
1950       return getTruncateOrSignExtend(X, Ty, Depth);
1951   }
1952 
1953   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1954     // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1955     if (SA->hasNoSignedWrap()) {
1956       // If the addition does not sign overflow then we can, by definition,
1957       // commute the sign extension with the addition operation.
1958       SmallVector<const SCEV *, 4> Ops;
1959       for (const auto *Op : SA->operands())
1960         Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1));
1961       return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1);
1962     }
1963 
1964     // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...))
1965     // if D + (C - D + x + y + ...) could be proven to not signed wrap
1966     // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1967     //
1968     // For instance, this will bring two seemingly different expressions:
1969     //     1 + sext(5 + 20 * %x + 24 * %y)  and
1970     //         sext(6 + 20 * %x + 24 * %y)
1971     // to the same form:
1972     //     2 + sext(4 + 20 * %x + 24 * %y)
1973     if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1974       const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1975       if (D != 0) {
1976         const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
1977         const SCEV *SResidual =
1978             getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth);
1979         const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
1980         return getAddExpr(SSExtD, SSExtR,
1981                           (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1982                           Depth + 1);
1983       }
1984     }
1985   }
1986   // If the input value is a chrec scev, and we can prove that the value
1987   // did not overflow the old, smaller, value, we can sign extend all of the
1988   // operands (often constants).  This allows analysis of something like
1989   // this:  for (signed char X = 0; X < 100; ++X) { int Y = X; }
1990   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1991     if (AR->isAffine()) {
1992       const SCEV *Start = AR->getStart();
1993       const SCEV *Step = AR->getStepRecurrence(*this);
1994       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1995       const Loop *L = AR->getLoop();
1996 
1997       // If we have special knowledge that this addrec won't overflow,
1998       // we don't need to do any further analysis.
1999       if (AR->hasNoSignedWrap()) {
2000         Start =
2001             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
2002         Step = getSignExtendExpr(Step, Ty, Depth + 1);
2003         return getAddRecExpr(Start, Step, L, SCEV::FlagNSW);
2004       }
2005 
2006       // Check whether the backedge-taken count is SCEVCouldNotCompute.
2007       // Note that this serves two purposes: It filters out loops that are
2008       // simply not analyzable, and it covers the case where this code is
2009       // being called from within backedge-taken count analysis, such that
2010       // attempting to ask for the backedge-taken count would likely result
2011       // in infinite recursion. In the later case, the analysis code will
2012       // cope with a conservative value, and it will take care to purge
2013       // that value once it has finished.
2014       const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
2015       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
2016         // Manually compute the final value for AR, checking for
2017         // overflow.
2018 
2019         // Check whether the backedge-taken count can be losslessly casted to
2020         // the addrec's type. The count is always unsigned.
2021         const SCEV *CastedMaxBECount =
2022             getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
2023         const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
2024             CastedMaxBECount, MaxBECount->getType(), Depth);
2025         if (MaxBECount == RecastedMaxBECount) {
2026           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
2027           // Check whether Start+Step*MaxBECount has no signed overflow.
2028           const SCEV *SMul = getMulExpr(CastedMaxBECount, Step,
2029                                         SCEV::FlagAnyWrap, Depth + 1);
2030           const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul,
2031                                                           SCEV::FlagAnyWrap,
2032                                                           Depth + 1),
2033                                                WideTy, Depth + 1);
2034           const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
2035           const SCEV *WideMaxBECount =
2036             getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
2037           const SCEV *OperandExtendedAdd =
2038             getAddExpr(WideStart,
2039                        getMulExpr(WideMaxBECount,
2040                                   getSignExtendExpr(Step, WideTy, Depth + 1),
2041                                   SCEV::FlagAnyWrap, Depth + 1),
2042                        SCEV::FlagAnyWrap, Depth + 1);
2043           if (SAdd == OperandExtendedAdd) {
2044             // Cache knowledge of AR NSW, which is propagated to this AddRec.
2045             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2046             // Return the expression with the addrec on the outside.
2047             Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
2048                                                              Depth + 1);
2049             Step = getSignExtendExpr(Step, Ty, Depth + 1);
2050             return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2051           }
2052           // Similar to above, only this time treat the step value as unsigned.
2053           // This covers loops that count up with an unsigned step.
2054           OperandExtendedAdd =
2055             getAddExpr(WideStart,
2056                        getMulExpr(WideMaxBECount,
2057                                   getZeroExtendExpr(Step, WideTy, Depth + 1),
2058                                   SCEV::FlagAnyWrap, Depth + 1),
2059                        SCEV::FlagAnyWrap, Depth + 1);
2060           if (SAdd == OperandExtendedAdd) {
2061             // If AR wraps around then
2062             //
2063             //    abs(Step) * MaxBECount > unsigned-max(AR->getType())
2064             // => SAdd != OperandExtendedAdd
2065             //
2066             // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
2067             // (SAdd == OperandExtendedAdd => AR is NW)
2068 
2069             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
2070 
2071             // Return the expression with the addrec on the outside.
2072             Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
2073                                                              Depth + 1);
2074             Step = getZeroExtendExpr(Step, Ty, Depth + 1);
2075             return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2076           }
2077         }
2078       }
2079 
2080       auto NewFlags = proveNoSignedWrapViaInduction(AR);
2081       setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
2082       if (AR->hasNoSignedWrap()) {
2083         // Same as nsw case above - duplicated here to avoid a compile time
2084         // issue.  It's not clear that the order of checks does matter, but
2085         // it's one of two issue possible causes for a change which was
2086         // reverted.  Be conservative for the moment.
2087         Start =
2088             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
2089         Step = getSignExtendExpr(Step, Ty, Depth + 1);
2090         return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2091       }
2092 
2093       // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw>
2094       // if D + (C - D + Step * n) could be proven to not signed wrap
2095       // where D maximizes the number of trailing zeros of (C - D + Step * n)
2096       if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
2097         const APInt &C = SC->getAPInt();
2098         const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
2099         if (D != 0) {
2100           const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
2101           const SCEV *SResidual =
2102               getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
2103           const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
2104           return getAddExpr(SSExtD, SSExtR,
2105                             (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
2106                             Depth + 1);
2107         }
2108       }
2109 
2110       if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
2111         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2112         Start =
2113             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
2114         Step = getSignExtendExpr(Step, Ty, Depth + 1);
2115         return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2116       }
2117     }
2118 
2119   // If the input value is provably positive and we could not simplify
2120   // away the sext build a zext instead.
2121   if (isKnownNonNegative(Op))
2122     return getZeroExtendExpr(Op, Ty, Depth + 1);
2123 
2124   // sext(smin(x, y)) -> smin(sext(x), sext(y))
2125   // sext(smax(x, y)) -> smax(sext(x), sext(y))
2126   if (isa<SCEVSMinExpr>(Op) || isa<SCEVSMaxExpr>(Op)) {
2127     auto *MinMax = cast<SCEVMinMaxExpr>(Op);
2128     SmallVector<const SCEV *, 4> Operands;
2129     for (auto *Operand : MinMax->operands())
2130       Operands.push_back(getSignExtendExpr(Operand, Ty));
2131     if (isa<SCEVSMinExpr>(MinMax))
2132       return getSMinExpr(Operands);
2133     return getSMaxExpr(Operands);
2134   }
2135 
2136   // The cast wasn't folded; create an explicit cast node.
2137   // Recompute the insert position, as it may have been invalidated.
2138   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2139   SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
2140                                                    Op, Ty);
2141   UniqueSCEVs.InsertNode(S, IP);
2142   registerUser(S, { Op });
2143   return S;
2144 }
2145 
2146 const SCEV *ScalarEvolution::getCastExpr(SCEVTypes Kind, const SCEV *Op,
2147                                          Type *Ty) {
2148   switch (Kind) {
2149   case scTruncate:
2150     return getTruncateExpr(Op, Ty);
2151   case scZeroExtend:
2152     return getZeroExtendExpr(Op, Ty);
2153   case scSignExtend:
2154     return getSignExtendExpr(Op, Ty);
2155   case scPtrToInt:
2156     return getPtrToIntExpr(Op, Ty);
2157   default:
2158     llvm_unreachable("Not a SCEV cast expression!");
2159   }
2160 }
2161 
2162 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
2163 /// unspecified bits out to the given type.
2164 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
2165                                               Type *Ty) {
2166   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
2167          "This is not an extending conversion!");
2168   assert(isSCEVable(Ty) &&
2169          "This is not a conversion to a SCEVable type!");
2170   Ty = getEffectiveSCEVType(Ty);
2171 
2172   // Sign-extend negative constants.
2173   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
2174     if (SC->getAPInt().isNegative())
2175       return getSignExtendExpr(Op, Ty);
2176 
2177   // Peel off a truncate cast.
2178   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
2179     const SCEV *NewOp = T->getOperand();
2180     if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
2181       return getAnyExtendExpr(NewOp, Ty);
2182     return getTruncateOrNoop(NewOp, Ty);
2183   }
2184 
2185   // Next try a zext cast. If the cast is folded, use it.
2186   const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2187   if (!isa<SCEVZeroExtendExpr>(ZExt))
2188     return ZExt;
2189 
2190   // Next try a sext cast. If the cast is folded, use it.
2191   const SCEV *SExt = getSignExtendExpr(Op, Ty);
2192   if (!isa<SCEVSignExtendExpr>(SExt))
2193     return SExt;
2194 
2195   // Force the cast to be folded into the operands of an addrec.
2196   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2197     SmallVector<const SCEV *, 4> Ops;
2198     for (const SCEV *Op : AR->operands())
2199       Ops.push_back(getAnyExtendExpr(Op, Ty));
2200     return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2201   }
2202 
2203   // If the expression is obviously signed, use the sext cast value.
2204   if (isa<SCEVSMaxExpr>(Op))
2205     return SExt;
2206 
2207   // Absent any other information, use the zext cast value.
2208   return ZExt;
2209 }
2210 
2211 /// Process the given Ops list, which is a list of operands to be added under
2212 /// the given scale, update the given map. This is a helper function for
2213 /// getAddRecExpr. As an example of what it does, given a sequence of operands
2214 /// that would form an add expression like this:
2215 ///
2216 ///    m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2217 ///
2218 /// where A and B are constants, update the map with these values:
2219 ///
2220 ///    (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2221 ///
2222 /// and add 13 + A*B*29 to AccumulatedConstant.
2223 /// This will allow getAddRecExpr to produce this:
2224 ///
2225 ///    13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2226 ///
2227 /// This form often exposes folding opportunities that are hidden in
2228 /// the original operand list.
2229 ///
2230 /// Return true iff it appears that any interesting folding opportunities
2231 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
2232 /// the common case where no interesting opportunities are present, and
2233 /// is also used as a check to avoid infinite recursion.
2234 static bool
2235 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
2236                              SmallVectorImpl<const SCEV *> &NewOps,
2237                              APInt &AccumulatedConstant,
2238                              ArrayRef<const SCEV *> Ops, const APInt &Scale,
2239                              ScalarEvolution &SE) {
2240   bool Interesting = false;
2241 
2242   // Iterate over the add operands. They are sorted, with constants first.
2243   unsigned i = 0;
2244   while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2245     ++i;
2246     // Pull a buried constant out to the outside.
2247     if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2248       Interesting = true;
2249     AccumulatedConstant += Scale * C->getAPInt();
2250   }
2251 
2252   // Next comes everything else. We're especially interested in multiplies
2253   // here, but they're in the middle, so just visit the rest with one loop.
2254   for (; i != Ops.size(); ++i) {
2255     const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
2256     if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2257       APInt NewScale =
2258           Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2259       if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2260         // A multiplication of a constant with another add; recurse.
2261         const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2262         Interesting |=
2263           CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2264                                        Add->operands(), NewScale, SE);
2265       } else {
2266         // A multiplication of a constant with some other value. Update
2267         // the map.
2268         SmallVector<const SCEV *, 4> MulOps(drop_begin(Mul->operands()));
2269         const SCEV *Key = SE.getMulExpr(MulOps);
2270         auto Pair = M.insert({Key, NewScale});
2271         if (Pair.second) {
2272           NewOps.push_back(Pair.first->first);
2273         } else {
2274           Pair.first->second += NewScale;
2275           // The map already had an entry for this value, which may indicate
2276           // a folding opportunity.
2277           Interesting = true;
2278         }
2279       }
2280     } else {
2281       // An ordinary operand. Update the map.
2282       std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
2283           M.insert({Ops[i], Scale});
2284       if (Pair.second) {
2285         NewOps.push_back(Pair.first->first);
2286       } else {
2287         Pair.first->second += Scale;
2288         // The map already had an entry for this value, which may indicate
2289         // a folding opportunity.
2290         Interesting = true;
2291       }
2292     }
2293   }
2294 
2295   return Interesting;
2296 }
2297 
2298 bool ScalarEvolution::willNotOverflow(Instruction::BinaryOps BinOp, bool Signed,
2299                                       const SCEV *LHS, const SCEV *RHS,
2300                                       const Instruction *CtxI) {
2301   const SCEV *(ScalarEvolution::*Operation)(const SCEV *, const SCEV *,
2302                                             SCEV::NoWrapFlags, unsigned);
2303   switch (BinOp) {
2304   default:
2305     llvm_unreachable("Unsupported binary op");
2306   case Instruction::Add:
2307     Operation = &ScalarEvolution::getAddExpr;
2308     break;
2309   case Instruction::Sub:
2310     Operation = &ScalarEvolution::getMinusSCEV;
2311     break;
2312   case Instruction::Mul:
2313     Operation = &ScalarEvolution::getMulExpr;
2314     break;
2315   }
2316 
2317   const SCEV *(ScalarEvolution::*Extension)(const SCEV *, Type *, unsigned) =
2318       Signed ? &ScalarEvolution::getSignExtendExpr
2319              : &ScalarEvolution::getZeroExtendExpr;
2320 
2321   // Check ext(LHS op RHS) == ext(LHS) op ext(RHS)
2322   auto *NarrowTy = cast<IntegerType>(LHS->getType());
2323   auto *WideTy =
2324       IntegerType::get(NarrowTy->getContext(), NarrowTy->getBitWidth() * 2);
2325 
2326   const SCEV *A = (this->*Extension)(
2327       (this->*Operation)(LHS, RHS, SCEV::FlagAnyWrap, 0), WideTy, 0);
2328   const SCEV *LHSB = (this->*Extension)(LHS, WideTy, 0);
2329   const SCEV *RHSB = (this->*Extension)(RHS, WideTy, 0);
2330   const SCEV *B = (this->*Operation)(LHSB, RHSB, SCEV::FlagAnyWrap, 0);
2331   if (A == B)
2332     return true;
2333   // Can we use context to prove the fact we need?
2334   if (!CtxI)
2335     return false;
2336   // TODO: Support mul.
2337   if (BinOp == Instruction::Mul)
2338     return false;
2339   auto *RHSC = dyn_cast<SCEVConstant>(RHS);
2340   // TODO: Lift this limitation.
2341   if (!RHSC)
2342     return false;
2343   APInt C = RHSC->getAPInt();
2344   unsigned NumBits = C.getBitWidth();
2345   bool IsSub = (BinOp == Instruction::Sub);
2346   bool IsNegativeConst = (Signed && C.isNegative());
2347   // Compute the direction and magnitude by which we need to check overflow.
2348   bool OverflowDown = IsSub ^ IsNegativeConst;
2349   APInt Magnitude = C;
2350   if (IsNegativeConst) {
2351     if (C == APInt::getSignedMinValue(NumBits))
2352       // TODO: SINT_MIN on inversion gives the same negative value, we don't
2353       // want to deal with that.
2354       return false;
2355     Magnitude = -C;
2356   }
2357 
2358   ICmpInst::Predicate Pred = Signed ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
2359   if (OverflowDown) {
2360     // To avoid overflow down, we need to make sure that MIN + Magnitude <= LHS.
2361     APInt Min = Signed ? APInt::getSignedMinValue(NumBits)
2362                        : APInt::getMinValue(NumBits);
2363     APInt Limit = Min + Magnitude;
2364     return isKnownPredicateAt(Pred, getConstant(Limit), LHS, CtxI);
2365   } else {
2366     // To avoid overflow up, we need to make sure that LHS <= MAX - Magnitude.
2367     APInt Max = Signed ? APInt::getSignedMaxValue(NumBits)
2368                        : APInt::getMaxValue(NumBits);
2369     APInt Limit = Max - Magnitude;
2370     return isKnownPredicateAt(Pred, LHS, getConstant(Limit), CtxI);
2371   }
2372 }
2373 
2374 std::optional<SCEV::NoWrapFlags>
2375 ScalarEvolution::getStrengthenedNoWrapFlagsFromBinOp(
2376     const OverflowingBinaryOperator *OBO) {
2377   // It cannot be done any better.
2378   if (OBO->hasNoUnsignedWrap() && OBO->hasNoSignedWrap())
2379     return std::nullopt;
2380 
2381   SCEV::NoWrapFlags Flags = SCEV::NoWrapFlags::FlagAnyWrap;
2382 
2383   if (OBO->hasNoUnsignedWrap())
2384     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2385   if (OBO->hasNoSignedWrap())
2386     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2387 
2388   bool Deduced = false;
2389 
2390   if (OBO->getOpcode() != Instruction::Add &&
2391       OBO->getOpcode() != Instruction::Sub &&
2392       OBO->getOpcode() != Instruction::Mul)
2393     return std::nullopt;
2394 
2395   const SCEV *LHS = getSCEV(OBO->getOperand(0));
2396   const SCEV *RHS = getSCEV(OBO->getOperand(1));
2397 
2398   const Instruction *CtxI =
2399       UseContextForNoWrapFlagInference ? dyn_cast<Instruction>(OBO) : nullptr;
2400   if (!OBO->hasNoUnsignedWrap() &&
2401       willNotOverflow((Instruction::BinaryOps)OBO->getOpcode(),
2402                       /* Signed */ false, LHS, RHS, CtxI)) {
2403     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2404     Deduced = true;
2405   }
2406 
2407   if (!OBO->hasNoSignedWrap() &&
2408       willNotOverflow((Instruction::BinaryOps)OBO->getOpcode(),
2409                       /* Signed */ true, LHS, RHS, CtxI)) {
2410     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2411     Deduced = true;
2412   }
2413 
2414   if (Deduced)
2415     return Flags;
2416   return std::nullopt;
2417 }
2418 
2419 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2420 // `OldFlags' as can't-wrap behavior.  Infer a more aggressive set of
2421 // can't-overflow flags for the operation if possible.
2422 static SCEV::NoWrapFlags
2423 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
2424                       const ArrayRef<const SCEV *> Ops,
2425                       SCEV::NoWrapFlags Flags) {
2426   using namespace std::placeholders;
2427 
2428   using OBO = OverflowingBinaryOperator;
2429 
2430   bool CanAnalyze =
2431       Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
2432   (void)CanAnalyze;
2433   assert(CanAnalyze && "don't call from other places!");
2434 
2435   int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2436   SCEV::NoWrapFlags SignOrUnsignWrap =
2437       ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2438 
2439   // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2440   auto IsKnownNonNegative = [&](const SCEV *S) {
2441     return SE->isKnownNonNegative(S);
2442   };
2443 
2444   if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2445     Flags =
2446         ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
2447 
2448   SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2449 
2450   if (SignOrUnsignWrap != SignOrUnsignMask &&
2451       (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 &&
2452       isa<SCEVConstant>(Ops[0])) {
2453 
2454     auto Opcode = [&] {
2455       switch (Type) {
2456       case scAddExpr:
2457         return Instruction::Add;
2458       case scMulExpr:
2459         return Instruction::Mul;
2460       default:
2461         llvm_unreachable("Unexpected SCEV op.");
2462       }
2463     }();
2464 
2465     const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2466 
2467     // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow.
2468     if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2469       auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2470           Opcode, C, OBO::NoSignedWrap);
2471       if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2472         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2473     }
2474 
2475     // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow.
2476     if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2477       auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2478           Opcode, C, OBO::NoUnsignedWrap);
2479       if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2480         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2481     }
2482   }
2483 
2484   // <0,+,nonnegative><nw> is also nuw
2485   // TODO: Add corresponding nsw case
2486   if (Type == scAddRecExpr && ScalarEvolution::hasFlags(Flags, SCEV::FlagNW) &&
2487       !ScalarEvolution::hasFlags(Flags, SCEV::FlagNUW) && Ops.size() == 2 &&
2488       Ops[0]->isZero() && IsKnownNonNegative(Ops[1]))
2489     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2490 
2491   // both (udiv X, Y) * Y and Y * (udiv X, Y) are always NUW
2492   if (Type == scMulExpr && !ScalarEvolution::hasFlags(Flags, SCEV::FlagNUW) &&
2493       Ops.size() == 2) {
2494     if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[0]))
2495       if (UDiv->getOperand(1) == Ops[1])
2496         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2497     if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[1]))
2498       if (UDiv->getOperand(1) == Ops[0])
2499         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2500   }
2501 
2502   return Flags;
2503 }
2504 
2505 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) {
2506   return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader());
2507 }
2508 
2509 /// Get a canonical add expression, or something simpler if possible.
2510 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2511                                         SCEV::NoWrapFlags OrigFlags,
2512                                         unsigned Depth) {
2513   assert(!(OrigFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2514          "only nuw or nsw allowed");
2515   assert(!Ops.empty() && "Cannot get empty add!");
2516   if (Ops.size() == 1) return Ops[0];
2517 #ifndef NDEBUG
2518   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2519   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2520     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2521            "SCEVAddExpr operand types don't match!");
2522   unsigned NumPtrs = count_if(
2523       Ops, [](const SCEV *Op) { return Op->getType()->isPointerTy(); });
2524   assert(NumPtrs <= 1 && "add has at most one pointer operand");
2525 #endif
2526 
2527   // Sort by complexity, this groups all similar expression types together.
2528   GroupByComplexity(Ops, &LI, DT);
2529 
2530   // If there are any constants, fold them together.
2531   unsigned Idx = 0;
2532   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2533     ++Idx;
2534     assert(Idx < Ops.size());
2535     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2536       // We found two constants, fold them together!
2537       Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
2538       if (Ops.size() == 2) return Ops[0];
2539       Ops.erase(Ops.begin()+1);  // Erase the folded element
2540       LHSC = cast<SCEVConstant>(Ops[0]);
2541     }
2542 
2543     // If we are left with a constant zero being added, strip it off.
2544     if (LHSC->getValue()->isZero()) {
2545       Ops.erase(Ops.begin());
2546       --Idx;
2547     }
2548 
2549     if (Ops.size() == 1) return Ops[0];
2550   }
2551 
2552   // Delay expensive flag strengthening until necessary.
2553   auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) {
2554     return StrengthenNoWrapFlags(this, scAddExpr, Ops, OrigFlags);
2555   };
2556 
2557   // Limit recursion calls depth.
2558   if (Depth > MaxArithDepth || hasHugeExpression(Ops))
2559     return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
2560 
2561   if (SCEV *S = findExistingSCEVInCache(scAddExpr, Ops)) {
2562     // Don't strengthen flags if we have no new information.
2563     SCEVAddExpr *Add = static_cast<SCEVAddExpr *>(S);
2564     if (Add->getNoWrapFlags(OrigFlags) != OrigFlags)
2565       Add->setNoWrapFlags(ComputeFlags(Ops));
2566     return S;
2567   }
2568 
2569   // Okay, check to see if the same value occurs in the operand list more than
2570   // once.  If so, merge them together into an multiply expression.  Since we
2571   // sorted the list, these values are required to be adjacent.
2572   Type *Ty = Ops[0]->getType();
2573   bool FoundMatch = false;
2574   for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2575     if (Ops[i] == Ops[i+1]) {      //  X + Y + Y  -->  X + Y*2
2576       // Scan ahead to count how many equal operands there are.
2577       unsigned Count = 2;
2578       while (i+Count != e && Ops[i+Count] == Ops[i])
2579         ++Count;
2580       // Merge the values into a multiply.
2581       const SCEV *Scale = getConstant(Ty, Count);
2582       const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1);
2583       if (Ops.size() == Count)
2584         return Mul;
2585       Ops[i] = Mul;
2586       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2587       --i; e -= Count - 1;
2588       FoundMatch = true;
2589     }
2590   if (FoundMatch)
2591     return getAddExpr(Ops, OrigFlags, Depth + 1);
2592 
2593   // Check for truncates. If all the operands are truncated from the same
2594   // type, see if factoring out the truncate would permit the result to be
2595   // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
2596   // if the contents of the resulting outer trunc fold to something simple.
2597   auto FindTruncSrcType = [&]() -> Type * {
2598     // We're ultimately looking to fold an addrec of truncs and muls of only
2599     // constants and truncs, so if we find any other types of SCEV
2600     // as operands of the addrec then we bail and return nullptr here.
2601     // Otherwise, we return the type of the operand of a trunc that we find.
2602     if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx]))
2603       return T->getOperand()->getType();
2604     if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2605       const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1);
2606       if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp))
2607         return T->getOperand()->getType();
2608     }
2609     return nullptr;
2610   };
2611   if (auto *SrcType = FindTruncSrcType()) {
2612     SmallVector<const SCEV *, 8> LargeOps;
2613     bool Ok = true;
2614     // Check all the operands to see if they can be represented in the
2615     // source type of the truncate.
2616     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2617       if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2618         if (T->getOperand()->getType() != SrcType) {
2619           Ok = false;
2620           break;
2621         }
2622         LargeOps.push_back(T->getOperand());
2623       } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2624         LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2625       } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
2626         SmallVector<const SCEV *, 8> LargeMulOps;
2627         for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2628           if (const SCEVTruncateExpr *T =
2629                 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2630             if (T->getOperand()->getType() != SrcType) {
2631               Ok = false;
2632               break;
2633             }
2634             LargeMulOps.push_back(T->getOperand());
2635           } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2636             LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2637           } else {
2638             Ok = false;
2639             break;
2640           }
2641         }
2642         if (Ok)
2643           LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1));
2644       } else {
2645         Ok = false;
2646         break;
2647       }
2648     }
2649     if (Ok) {
2650       // Evaluate the expression in the larger type.
2651       const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1);
2652       // If it folds to something simple, use it. Otherwise, don't.
2653       if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2654         return getTruncateExpr(Fold, Ty);
2655     }
2656   }
2657 
2658   if (Ops.size() == 2) {
2659     // Check if we have an expression of the form ((X + C1) - C2), where C1 and
2660     // C2 can be folded in a way that allows retaining wrapping flags of (X +
2661     // C1).
2662     const SCEV *A = Ops[0];
2663     const SCEV *B = Ops[1];
2664     auto *AddExpr = dyn_cast<SCEVAddExpr>(B);
2665     auto *C = dyn_cast<SCEVConstant>(A);
2666     if (AddExpr && C && isa<SCEVConstant>(AddExpr->getOperand(0))) {
2667       auto C1 = cast<SCEVConstant>(AddExpr->getOperand(0))->getAPInt();
2668       auto C2 = C->getAPInt();
2669       SCEV::NoWrapFlags PreservedFlags = SCEV::FlagAnyWrap;
2670 
2671       APInt ConstAdd = C1 + C2;
2672       auto AddFlags = AddExpr->getNoWrapFlags();
2673       // Adding a smaller constant is NUW if the original AddExpr was NUW.
2674       if (ScalarEvolution::hasFlags(AddFlags, SCEV::FlagNUW) &&
2675           ConstAdd.ule(C1)) {
2676         PreservedFlags =
2677             ScalarEvolution::setFlags(PreservedFlags, SCEV::FlagNUW);
2678       }
2679 
2680       // Adding a constant with the same sign and small magnitude is NSW, if the
2681       // original AddExpr was NSW.
2682       if (ScalarEvolution::hasFlags(AddFlags, SCEV::FlagNSW) &&
2683           C1.isSignBitSet() == ConstAdd.isSignBitSet() &&
2684           ConstAdd.abs().ule(C1.abs())) {
2685         PreservedFlags =
2686             ScalarEvolution::setFlags(PreservedFlags, SCEV::FlagNSW);
2687       }
2688 
2689       if (PreservedFlags != SCEV::FlagAnyWrap) {
2690         SmallVector<const SCEV *, 4> NewOps(AddExpr->operands());
2691         NewOps[0] = getConstant(ConstAdd);
2692         return getAddExpr(NewOps, PreservedFlags);
2693       }
2694     }
2695   }
2696 
2697   // Canonicalize (-1 * urem X, Y) + X --> (Y * X/Y)
2698   if (Ops.size() == 2) {
2699     const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[0]);
2700     if (Mul && Mul->getNumOperands() == 2 &&
2701         Mul->getOperand(0)->isAllOnesValue()) {
2702       const SCEV *X;
2703       const SCEV *Y;
2704       if (matchURem(Mul->getOperand(1), X, Y) && X == Ops[1]) {
2705         return getMulExpr(Y, getUDivExpr(X, Y));
2706       }
2707     }
2708   }
2709 
2710   // Skip past any other cast SCEVs.
2711   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2712     ++Idx;
2713 
2714   // If there are add operands they would be next.
2715   if (Idx < Ops.size()) {
2716     bool DeletedAdd = false;
2717     // If the original flags and all inlined SCEVAddExprs are NUW, use the
2718     // common NUW flag for expression after inlining. Other flags cannot be
2719     // preserved, because they may depend on the original order of operations.
2720     SCEV::NoWrapFlags CommonFlags = maskFlags(OrigFlags, SCEV::FlagNUW);
2721     while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2722       if (Ops.size() > AddOpsInlineThreshold ||
2723           Add->getNumOperands() > AddOpsInlineThreshold)
2724         break;
2725       // If we have an add, expand the add operands onto the end of the operands
2726       // list.
2727       Ops.erase(Ops.begin()+Idx);
2728       append_range(Ops, Add->operands());
2729       DeletedAdd = true;
2730       CommonFlags = maskFlags(CommonFlags, Add->getNoWrapFlags());
2731     }
2732 
2733     // If we deleted at least one add, we added operands to the end of the list,
2734     // and they are not necessarily sorted.  Recurse to resort and resimplify
2735     // any operands we just acquired.
2736     if (DeletedAdd)
2737       return getAddExpr(Ops, CommonFlags, Depth + 1);
2738   }
2739 
2740   // Skip over the add expression until we get to a multiply.
2741   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2742     ++Idx;
2743 
2744   // Check to see if there are any folding opportunities present with
2745   // operands multiplied by constant values.
2746   if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2747     uint64_t BitWidth = getTypeSizeInBits(Ty);
2748     DenseMap<const SCEV *, APInt> M;
2749     SmallVector<const SCEV *, 8> NewOps;
2750     APInt AccumulatedConstant(BitWidth, 0);
2751     if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2752                                      Ops, APInt(BitWidth, 1), *this)) {
2753       struct APIntCompare {
2754         bool operator()(const APInt &LHS, const APInt &RHS) const {
2755           return LHS.ult(RHS);
2756         }
2757       };
2758 
2759       // Some interesting folding opportunity is present, so its worthwhile to
2760       // re-generate the operands list. Group the operands by constant scale,
2761       // to avoid multiplying by the same constant scale multiple times.
2762       std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
2763       for (const SCEV *NewOp : NewOps)
2764         MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2765       // Re-generate the operands list.
2766       Ops.clear();
2767       if (AccumulatedConstant != 0)
2768         Ops.push_back(getConstant(AccumulatedConstant));
2769       for (auto &MulOp : MulOpLists) {
2770         if (MulOp.first == 1) {
2771           Ops.push_back(getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1));
2772         } else if (MulOp.first != 0) {
2773           Ops.push_back(getMulExpr(
2774               getConstant(MulOp.first),
2775               getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1),
2776               SCEV::FlagAnyWrap, Depth + 1));
2777         }
2778       }
2779       if (Ops.empty())
2780         return getZero(Ty);
2781       if (Ops.size() == 1)
2782         return Ops[0];
2783       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2784     }
2785   }
2786 
2787   // If we are adding something to a multiply expression, make sure the
2788   // something is not already an operand of the multiply.  If so, merge it into
2789   // the multiply.
2790   for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2791     const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2792     for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2793       const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2794       if (isa<SCEVConstant>(MulOpSCEV))
2795         continue;
2796       for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
2797         if (MulOpSCEV == Ops[AddOp]) {
2798           // Fold W + X + (X * Y * Z)  -->  W + (X * ((Y*Z)+1))
2799           const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
2800           if (Mul->getNumOperands() != 2) {
2801             // If the multiply has more than two operands, we must get the
2802             // Y*Z term.
2803             SmallVector<const SCEV *, 4> MulOps(
2804                 Mul->operands().take_front(MulOp));
2805             append_range(MulOps, Mul->operands().drop_front(MulOp + 1));
2806             InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2807           }
2808           SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul};
2809           const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2810           const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV,
2811                                             SCEV::FlagAnyWrap, Depth + 1);
2812           if (Ops.size() == 2) return OuterMul;
2813           if (AddOp < Idx) {
2814             Ops.erase(Ops.begin()+AddOp);
2815             Ops.erase(Ops.begin()+Idx-1);
2816           } else {
2817             Ops.erase(Ops.begin()+Idx);
2818             Ops.erase(Ops.begin()+AddOp-1);
2819           }
2820           Ops.push_back(OuterMul);
2821           return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2822         }
2823 
2824       // Check this multiply against other multiplies being added together.
2825       for (unsigned OtherMulIdx = Idx+1;
2826            OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2827            ++OtherMulIdx) {
2828         const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
2829         // If MulOp occurs in OtherMul, we can fold the two multiplies
2830         // together.
2831         for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2832              OMulOp != e; ++OMulOp)
2833           if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2834             // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
2835             const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
2836             if (Mul->getNumOperands() != 2) {
2837               SmallVector<const SCEV *, 4> MulOps(
2838                   Mul->operands().take_front(MulOp));
2839               append_range(MulOps, Mul->operands().drop_front(MulOp+1));
2840               InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2841             }
2842             const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
2843             if (OtherMul->getNumOperands() != 2) {
2844               SmallVector<const SCEV *, 4> MulOps(
2845                   OtherMul->operands().take_front(OMulOp));
2846               append_range(MulOps, OtherMul->operands().drop_front(OMulOp+1));
2847               InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2848             }
2849             SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2};
2850             const SCEV *InnerMulSum =
2851                 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2852             const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum,
2853                                               SCEV::FlagAnyWrap, Depth + 1);
2854             if (Ops.size() == 2) return OuterMul;
2855             Ops.erase(Ops.begin()+Idx);
2856             Ops.erase(Ops.begin()+OtherMulIdx-1);
2857             Ops.push_back(OuterMul);
2858             return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2859           }
2860       }
2861     }
2862   }
2863 
2864   // If there are any add recurrences in the operands list, see if any other
2865   // added values are loop invariant.  If so, we can fold them into the
2866   // recurrence.
2867   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2868     ++Idx;
2869 
2870   // Scan over all recurrences, trying to fold loop invariants into them.
2871   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2872     // Scan all of the other operands to this add and add them to the vector if
2873     // they are loop invariant w.r.t. the recurrence.
2874     SmallVector<const SCEV *, 8> LIOps;
2875     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2876     const Loop *AddRecLoop = AddRec->getLoop();
2877     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2878       if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2879         LIOps.push_back(Ops[i]);
2880         Ops.erase(Ops.begin()+i);
2881         --i; --e;
2882       }
2883 
2884     // If we found some loop invariants, fold them into the recurrence.
2885     if (!LIOps.empty()) {
2886       // Compute nowrap flags for the addition of the loop-invariant ops and
2887       // the addrec. Temporarily push it as an operand for that purpose. These
2888       // flags are valid in the scope of the addrec only.
2889       LIOps.push_back(AddRec);
2890       SCEV::NoWrapFlags Flags = ComputeFlags(LIOps);
2891       LIOps.pop_back();
2892 
2893       //  NLI + LI + {Start,+,Step}  -->  NLI + {LI+Start,+,Step}
2894       LIOps.push_back(AddRec->getStart());
2895 
2896       SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands());
2897 
2898       // It is not in general safe to propagate flags valid on an add within
2899       // the addrec scope to one outside it.  We must prove that the inner
2900       // scope is guaranteed to execute if the outer one does to be able to
2901       // safely propagate.  We know the program is undefined if poison is
2902       // produced on the inner scoped addrec.  We also know that *for this use*
2903       // the outer scoped add can't overflow (because of the flags we just
2904       // computed for the inner scoped add) without the program being undefined.
2905       // Proving that entry to the outer scope neccesitates entry to the inner
2906       // scope, thus proves the program undefined if the flags would be violated
2907       // in the outer scope.
2908       SCEV::NoWrapFlags AddFlags = Flags;
2909       if (AddFlags != SCEV::FlagAnyWrap) {
2910         auto *DefI = getDefiningScopeBound(LIOps);
2911         auto *ReachI = &*AddRecLoop->getHeader()->begin();
2912         if (!isGuaranteedToTransferExecutionTo(DefI, ReachI))
2913           AddFlags = SCEV::FlagAnyWrap;
2914       }
2915       AddRecOps[0] = getAddExpr(LIOps, AddFlags, Depth + 1);
2916 
2917       // Build the new addrec. Propagate the NUW and NSW flags if both the
2918       // outer add and the inner addrec are guaranteed to have no overflow.
2919       // Always propagate NW.
2920       Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2921       const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2922 
2923       // If all of the other operands were loop invariant, we are done.
2924       if (Ops.size() == 1) return NewRec;
2925 
2926       // Otherwise, add the folded AddRec by the non-invariant parts.
2927       for (unsigned i = 0;; ++i)
2928         if (Ops[i] == AddRec) {
2929           Ops[i] = NewRec;
2930           break;
2931         }
2932       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2933     }
2934 
2935     // Okay, if there weren't any loop invariants to be folded, check to see if
2936     // there are multiple AddRec's with the same loop induction variable being
2937     // added together.  If so, we can fold them.
2938     for (unsigned OtherIdx = Idx+1;
2939          OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2940          ++OtherIdx) {
2941       // We expect the AddRecExpr's to be sorted in reverse dominance order,
2942       // so that the 1st found AddRecExpr is dominated by all others.
2943       assert(DT.dominates(
2944            cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
2945            AddRec->getLoop()->getHeader()) &&
2946         "AddRecExprs are not sorted in reverse dominance order?");
2947       if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2948         // Other + {A,+,B}<L> + {C,+,D}<L>  -->  Other + {A+C,+,B+D}<L>
2949         SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands());
2950         for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2951              ++OtherIdx) {
2952           const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2953           if (OtherAddRec->getLoop() == AddRecLoop) {
2954             for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2955                  i != e; ++i) {
2956               if (i >= AddRecOps.size()) {
2957                 append_range(AddRecOps, OtherAddRec->operands().drop_front(i));
2958                 break;
2959               }
2960               SmallVector<const SCEV *, 2> TwoOps = {
2961                   AddRecOps[i], OtherAddRec->getOperand(i)};
2962               AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2963             }
2964             Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2965           }
2966         }
2967         // Step size has changed, so we cannot guarantee no self-wraparound.
2968         Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2969         return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2970       }
2971     }
2972 
2973     // Otherwise couldn't fold anything into this recurrence.  Move onto the
2974     // next one.
2975   }
2976 
2977   // Okay, it looks like we really DO need an add expr.  Check to see if we
2978   // already have one, otherwise create a new one.
2979   return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
2980 }
2981 
2982 const SCEV *
2983 ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops,
2984                                     SCEV::NoWrapFlags Flags) {
2985   FoldingSetNodeID ID;
2986   ID.AddInteger(scAddExpr);
2987   for (const SCEV *Op : Ops)
2988     ID.AddPointer(Op);
2989   void *IP = nullptr;
2990   SCEVAddExpr *S =
2991       static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2992   if (!S) {
2993     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2994     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2995     S = new (SCEVAllocator)
2996         SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
2997     UniqueSCEVs.InsertNode(S, IP);
2998     registerUser(S, Ops);
2999   }
3000   S->setNoWrapFlags(Flags);
3001   return S;
3002 }
3003 
3004 const SCEV *
3005 ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops,
3006                                        const Loop *L, SCEV::NoWrapFlags Flags) {
3007   FoldingSetNodeID ID;
3008   ID.AddInteger(scAddRecExpr);
3009   for (const SCEV *Op : Ops)
3010     ID.AddPointer(Op);
3011   ID.AddPointer(L);
3012   void *IP = nullptr;
3013   SCEVAddRecExpr *S =
3014       static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3015   if (!S) {
3016     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3017     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3018     S = new (SCEVAllocator)
3019         SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L);
3020     UniqueSCEVs.InsertNode(S, IP);
3021     LoopUsers[L].push_back(S);
3022     registerUser(S, Ops);
3023   }
3024   setNoWrapFlags(S, Flags);
3025   return S;
3026 }
3027 
3028 const SCEV *
3029 ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops,
3030                                     SCEV::NoWrapFlags Flags) {
3031   FoldingSetNodeID ID;
3032   ID.AddInteger(scMulExpr);
3033   for (const SCEV *Op : Ops)
3034     ID.AddPointer(Op);
3035   void *IP = nullptr;
3036   SCEVMulExpr *S =
3037     static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3038   if (!S) {
3039     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3040     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3041     S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
3042                                         O, Ops.size());
3043     UniqueSCEVs.InsertNode(S, IP);
3044     registerUser(S, Ops);
3045   }
3046   S->setNoWrapFlags(Flags);
3047   return S;
3048 }
3049 
3050 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
3051   uint64_t k = i*j;
3052   if (j > 1 && k / j != i) Overflow = true;
3053   return k;
3054 }
3055 
3056 /// Compute the result of "n choose k", the binomial coefficient.  If an
3057 /// intermediate computation overflows, Overflow will be set and the return will
3058 /// be garbage. Overflow is not cleared on absence of overflow.
3059 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
3060   // We use the multiplicative formula:
3061   //     n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
3062   // At each iteration, we take the n-th term of the numeral and divide by the
3063   // (k-n)th term of the denominator.  This division will always produce an
3064   // integral result, and helps reduce the chance of overflow in the
3065   // intermediate computations. However, we can still overflow even when the
3066   // final result would fit.
3067 
3068   if (n == 0 || n == k) return 1;
3069   if (k > n) return 0;
3070 
3071   if (k > n/2)
3072     k = n-k;
3073 
3074   uint64_t r = 1;
3075   for (uint64_t i = 1; i <= k; ++i) {
3076     r = umul_ov(r, n-(i-1), Overflow);
3077     r /= i;
3078   }
3079   return r;
3080 }
3081 
3082 /// Determine if any of the operands in this SCEV are a constant or if
3083 /// any of the add or multiply expressions in this SCEV contain a constant.
3084 static bool containsConstantInAddMulChain(const SCEV *StartExpr) {
3085   struct FindConstantInAddMulChain {
3086     bool FoundConstant = false;
3087 
3088     bool follow(const SCEV *S) {
3089       FoundConstant |= isa<SCEVConstant>(S);
3090       return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
3091     }
3092 
3093     bool isDone() const {
3094       return FoundConstant;
3095     }
3096   };
3097 
3098   FindConstantInAddMulChain F;
3099   SCEVTraversal<FindConstantInAddMulChain> ST(F);
3100   ST.visitAll(StartExpr);
3101   return F.FoundConstant;
3102 }
3103 
3104 /// Get a canonical multiply expression, or something simpler if possible.
3105 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
3106                                         SCEV::NoWrapFlags OrigFlags,
3107                                         unsigned Depth) {
3108   assert(OrigFlags == maskFlags(OrigFlags, SCEV::FlagNUW | SCEV::FlagNSW) &&
3109          "only nuw or nsw allowed");
3110   assert(!Ops.empty() && "Cannot get empty mul!");
3111   if (Ops.size() == 1) return Ops[0];
3112 #ifndef NDEBUG
3113   Type *ETy = Ops[0]->getType();
3114   assert(!ETy->isPointerTy());
3115   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3116     assert(Ops[i]->getType() == ETy &&
3117            "SCEVMulExpr operand types don't match!");
3118 #endif
3119 
3120   // Sort by complexity, this groups all similar expression types together.
3121   GroupByComplexity(Ops, &LI, DT);
3122 
3123   // If there are any constants, fold them together.
3124   unsigned Idx = 0;
3125   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3126     ++Idx;
3127     assert(Idx < Ops.size());
3128     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3129       // We found two constants, fold them together!
3130       Ops[0] = getConstant(LHSC->getAPInt() * RHSC->getAPInt());
3131       if (Ops.size() == 2) return Ops[0];
3132       Ops.erase(Ops.begin()+1);  // Erase the folded element
3133       LHSC = cast<SCEVConstant>(Ops[0]);
3134     }
3135 
3136     // If we have a multiply of zero, it will always be zero.
3137     if (LHSC->getValue()->isZero())
3138       return LHSC;
3139 
3140     // If we are left with a constant one being multiplied, strip it off.
3141     if (LHSC->getValue()->isOne()) {
3142       Ops.erase(Ops.begin());
3143       --Idx;
3144     }
3145 
3146     if (Ops.size() == 1)
3147       return Ops[0];
3148   }
3149 
3150   // Delay expensive flag strengthening until necessary.
3151   auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) {
3152     return StrengthenNoWrapFlags(this, scMulExpr, Ops, OrigFlags);
3153   };
3154 
3155   // Limit recursion calls depth.
3156   if (Depth > MaxArithDepth || hasHugeExpression(Ops))
3157     return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
3158 
3159   if (SCEV *S = findExistingSCEVInCache(scMulExpr, Ops)) {
3160     // Don't strengthen flags if we have no new information.
3161     SCEVMulExpr *Mul = static_cast<SCEVMulExpr *>(S);
3162     if (Mul->getNoWrapFlags(OrigFlags) != OrigFlags)
3163       Mul->setNoWrapFlags(ComputeFlags(Ops));
3164     return S;
3165   }
3166 
3167   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3168     if (Ops.size() == 2) {
3169       // C1*(C2+V) -> C1*C2 + C1*V
3170       if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
3171         // If any of Add's ops are Adds or Muls with a constant, apply this
3172         // transformation as well.
3173         //
3174         // TODO: There are some cases where this transformation is not
3175         // profitable; for example, Add = (C0 + X) * Y + Z.  Maybe the scope of
3176         // this transformation should be narrowed down.
3177         if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add)) {
3178           const SCEV *LHS = getMulExpr(LHSC, Add->getOperand(0),
3179                                        SCEV::FlagAnyWrap, Depth + 1);
3180           const SCEV *RHS = getMulExpr(LHSC, Add->getOperand(1),
3181                                        SCEV::FlagAnyWrap, Depth + 1);
3182           return getAddExpr(LHS, RHS, SCEV::FlagAnyWrap, Depth + 1);
3183         }
3184 
3185       if (Ops[0]->isAllOnesValue()) {
3186         // If we have a mul by -1 of an add, try distributing the -1 among the
3187         // add operands.
3188         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
3189           SmallVector<const SCEV *, 4> NewOps;
3190           bool AnyFolded = false;
3191           for (const SCEV *AddOp : Add->operands()) {
3192             const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap,
3193                                          Depth + 1);
3194             if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
3195             NewOps.push_back(Mul);
3196           }
3197           if (AnyFolded)
3198             return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1);
3199         } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
3200           // Negation preserves a recurrence's no self-wrap property.
3201           SmallVector<const SCEV *, 4> Operands;
3202           for (const SCEV *AddRecOp : AddRec->operands())
3203             Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap,
3204                                           Depth + 1));
3205           // Let M be the minimum representable signed value. AddRec with nsw
3206           // multiplied by -1 can have signed overflow if and only if it takes a
3207           // value of M: M * (-1) would stay M and (M + 1) * (-1) would be the
3208           // maximum signed value. In all other cases signed overflow is
3209           // impossible.
3210           auto FlagsMask = SCEV::FlagNW;
3211           if (hasFlags(AddRec->getNoWrapFlags(), SCEV::FlagNSW)) {
3212             auto MinInt =
3213                 APInt::getSignedMinValue(getTypeSizeInBits(AddRec->getType()));
3214             if (getSignedRangeMin(AddRec) != MinInt)
3215               FlagsMask = setFlags(FlagsMask, SCEV::FlagNSW);
3216           }
3217           return getAddRecExpr(Operands, AddRec->getLoop(),
3218                                AddRec->getNoWrapFlags(FlagsMask));
3219         }
3220       }
3221     }
3222   }
3223 
3224   // Skip over the add expression until we get to a multiply.
3225   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
3226     ++Idx;
3227 
3228   // If there are mul operands inline them all into this expression.
3229   if (Idx < Ops.size()) {
3230     bool DeletedMul = false;
3231     while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
3232       if (Ops.size() > MulOpsInlineThreshold)
3233         break;
3234       // If we have an mul, expand the mul operands onto the end of the
3235       // operands list.
3236       Ops.erase(Ops.begin()+Idx);
3237       append_range(Ops, Mul->operands());
3238       DeletedMul = true;
3239     }
3240 
3241     // If we deleted at least one mul, we added operands to the end of the
3242     // list, and they are not necessarily sorted.  Recurse to resort and
3243     // resimplify any operands we just acquired.
3244     if (DeletedMul)
3245       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3246   }
3247 
3248   // If there are any add recurrences in the operands list, see if any other
3249   // added values are loop invariant.  If so, we can fold them into the
3250   // recurrence.
3251   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
3252     ++Idx;
3253 
3254   // Scan over all recurrences, trying to fold loop invariants into them.
3255   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
3256     // Scan all of the other operands to this mul and add them to the vector
3257     // if they are loop invariant w.r.t. the recurrence.
3258     SmallVector<const SCEV *, 8> LIOps;
3259     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
3260     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3261       if (isAvailableAtLoopEntry(Ops[i], AddRec->getLoop())) {
3262         LIOps.push_back(Ops[i]);
3263         Ops.erase(Ops.begin()+i);
3264         --i; --e;
3265       }
3266 
3267     // If we found some loop invariants, fold them into the recurrence.
3268     if (!LIOps.empty()) {
3269       //  NLI * LI * {Start,+,Step}  -->  NLI * {LI*Start,+,LI*Step}
3270       SmallVector<const SCEV *, 4> NewOps;
3271       NewOps.reserve(AddRec->getNumOperands());
3272       const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1);
3273 
3274       // If both the mul and addrec are nuw, we can preserve nuw.
3275       // If both the mul and addrec are nsw, we can only preserve nsw if either
3276       // a) they are also nuw, or
3277       // b) all multiplications of addrec operands with scale are nsw.
3278       SCEV::NoWrapFlags Flags =
3279           AddRec->getNoWrapFlags(ComputeFlags({Scale, AddRec}));
3280 
3281       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
3282         NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
3283                                     SCEV::FlagAnyWrap, Depth + 1));
3284 
3285         if (hasFlags(Flags, SCEV::FlagNSW) && !hasFlags(Flags, SCEV::FlagNUW)) {
3286           ConstantRange NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
3287               Instruction::Mul, getSignedRange(Scale),
3288               OverflowingBinaryOperator::NoSignedWrap);
3289           if (!NSWRegion.contains(getSignedRange(AddRec->getOperand(i))))
3290             Flags = clearFlags(Flags, SCEV::FlagNSW);
3291         }
3292       }
3293 
3294       const SCEV *NewRec = getAddRecExpr(NewOps, AddRec->getLoop(), Flags);
3295 
3296       // If all of the other operands were loop invariant, we are done.
3297       if (Ops.size() == 1) return NewRec;
3298 
3299       // Otherwise, multiply the folded AddRec by the non-invariant parts.
3300       for (unsigned i = 0;; ++i)
3301         if (Ops[i] == AddRec) {
3302           Ops[i] = NewRec;
3303           break;
3304         }
3305       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3306     }
3307 
3308     // Okay, if there weren't any loop invariants to be folded, check to see
3309     // if there are multiple AddRec's with the same loop induction variable
3310     // being multiplied together.  If so, we can fold them.
3311 
3312     // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
3313     // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
3314     //       choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
3315     //   ]]],+,...up to x=2n}.
3316     // Note that the arguments to choose() are always integers with values
3317     // known at compile time, never SCEV objects.
3318     //
3319     // The implementation avoids pointless extra computations when the two
3320     // addrec's are of different length (mathematically, it's equivalent to
3321     // an infinite stream of zeros on the right).
3322     bool OpsModified = false;
3323     for (unsigned OtherIdx = Idx+1;
3324          OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
3325          ++OtherIdx) {
3326       const SCEVAddRecExpr *OtherAddRec =
3327         dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
3328       if (!OtherAddRec || OtherAddRec->getLoop() != AddRec->getLoop())
3329         continue;
3330 
3331       // Limit max number of arguments to avoid creation of unreasonably big
3332       // SCEVAddRecs with very complex operands.
3333       if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
3334           MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec}))
3335         continue;
3336 
3337       bool Overflow = false;
3338       Type *Ty = AddRec->getType();
3339       bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
3340       SmallVector<const SCEV*, 7> AddRecOps;
3341       for (int x = 0, xe = AddRec->getNumOperands() +
3342              OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
3343         SmallVector <const SCEV *, 7> SumOps;
3344         for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
3345           uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
3346           for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
3347                  ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
3348                z < ze && !Overflow; ++z) {
3349             uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
3350             uint64_t Coeff;
3351             if (LargerThan64Bits)
3352               Coeff = umul_ov(Coeff1, Coeff2, Overflow);
3353             else
3354               Coeff = Coeff1*Coeff2;
3355             const SCEV *CoeffTerm = getConstant(Ty, Coeff);
3356             const SCEV *Term1 = AddRec->getOperand(y-z);
3357             const SCEV *Term2 = OtherAddRec->getOperand(z);
3358             SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2,
3359                                         SCEV::FlagAnyWrap, Depth + 1));
3360           }
3361         }
3362         if (SumOps.empty())
3363           SumOps.push_back(getZero(Ty));
3364         AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1));
3365       }
3366       if (!Overflow) {
3367         const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
3368                                               SCEV::FlagAnyWrap);
3369         if (Ops.size() == 2) return NewAddRec;
3370         Ops[Idx] = NewAddRec;
3371         Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
3372         OpsModified = true;
3373         AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
3374         if (!AddRec)
3375           break;
3376       }
3377     }
3378     if (OpsModified)
3379       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3380 
3381     // Otherwise couldn't fold anything into this recurrence.  Move onto the
3382     // next one.
3383   }
3384 
3385   // Okay, it looks like we really DO need an mul expr.  Check to see if we
3386   // already have one, otherwise create a new one.
3387   return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
3388 }
3389 
3390 /// Represents an unsigned remainder expression based on unsigned division.
3391 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS,
3392                                          const SCEV *RHS) {
3393   assert(getEffectiveSCEVType(LHS->getType()) ==
3394          getEffectiveSCEVType(RHS->getType()) &&
3395          "SCEVURemExpr operand types don't match!");
3396 
3397   // Short-circuit easy cases
3398   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3399     // If constant is one, the result is trivial
3400     if (RHSC->getValue()->isOne())
3401       return getZero(LHS->getType()); // X urem 1 --> 0
3402 
3403     // If constant is a power of two, fold into a zext(trunc(LHS)).
3404     if (RHSC->getAPInt().isPowerOf2()) {
3405       Type *FullTy = LHS->getType();
3406       Type *TruncTy =
3407           IntegerType::get(getContext(), RHSC->getAPInt().logBase2());
3408       return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy);
3409     }
3410   }
3411 
3412   // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
3413   const SCEV *UDiv = getUDivExpr(LHS, RHS);
3414   const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW);
3415   return getMinusSCEV(LHS, Mult, SCEV::FlagNUW);
3416 }
3417 
3418 /// Get a canonical unsigned division expression, or something simpler if
3419 /// possible.
3420 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
3421                                          const SCEV *RHS) {
3422   assert(!LHS->getType()->isPointerTy() &&
3423          "SCEVUDivExpr operand can't be pointer!");
3424   assert(LHS->getType() == RHS->getType() &&
3425          "SCEVUDivExpr operand types don't match!");
3426 
3427   FoldingSetNodeID ID;
3428   ID.AddInteger(scUDivExpr);
3429   ID.AddPointer(LHS);
3430   ID.AddPointer(RHS);
3431   void *IP = nullptr;
3432   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
3433     return S;
3434 
3435   // 0 udiv Y == 0
3436   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS))
3437     if (LHSC->getValue()->isZero())
3438       return LHS;
3439 
3440   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3441     if (RHSC->getValue()->isOne())
3442       return LHS;                               // X udiv 1 --> x
3443     // If the denominator is zero, the result of the udiv is undefined. Don't
3444     // try to analyze it, because the resolution chosen here may differ from
3445     // the resolution chosen in other parts of the compiler.
3446     if (!RHSC->getValue()->isZero()) {
3447       // Determine if the division can be folded into the operands of
3448       // its operands.
3449       // TODO: Generalize this to non-constants by using known-bits information.
3450       Type *Ty = LHS->getType();
3451       unsigned LZ = RHSC->getAPInt().countl_zero();
3452       unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
3453       // For non-power-of-two values, effectively round the value up to the
3454       // nearest power of two.
3455       if (!RHSC->getAPInt().isPowerOf2())
3456         ++MaxShiftAmt;
3457       IntegerType *ExtTy =
3458         IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
3459       if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
3460         if (const SCEVConstant *Step =
3461             dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
3462           // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
3463           const APInt &StepInt = Step->getAPInt();
3464           const APInt &DivInt = RHSC->getAPInt();
3465           if (!StepInt.urem(DivInt) &&
3466               getZeroExtendExpr(AR, ExtTy) ==
3467               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3468                             getZeroExtendExpr(Step, ExtTy),
3469                             AR->getLoop(), SCEV::FlagAnyWrap)) {
3470             SmallVector<const SCEV *, 4> Operands;
3471             for (const SCEV *Op : AR->operands())
3472               Operands.push_back(getUDivExpr(Op, RHS));
3473             return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
3474           }
3475           /// Get a canonical UDivExpr for a recurrence.
3476           /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
3477           // We can currently only fold X%N if X is constant.
3478           const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
3479           if (StartC && !DivInt.urem(StepInt) &&
3480               getZeroExtendExpr(AR, ExtTy) ==
3481               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3482                             getZeroExtendExpr(Step, ExtTy),
3483                             AR->getLoop(), SCEV::FlagAnyWrap)) {
3484             const APInt &StartInt = StartC->getAPInt();
3485             const APInt &StartRem = StartInt.urem(StepInt);
3486             if (StartRem != 0) {
3487               const SCEV *NewLHS =
3488                   getAddRecExpr(getConstant(StartInt - StartRem), Step,
3489                                 AR->getLoop(), SCEV::FlagNW);
3490               if (LHS != NewLHS) {
3491                 LHS = NewLHS;
3492 
3493                 // Reset the ID to include the new LHS, and check if it is
3494                 // already cached.
3495                 ID.clear();
3496                 ID.AddInteger(scUDivExpr);
3497                 ID.AddPointer(LHS);
3498                 ID.AddPointer(RHS);
3499                 IP = nullptr;
3500                 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
3501                   return S;
3502               }
3503             }
3504           }
3505         }
3506       // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
3507       if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
3508         SmallVector<const SCEV *, 4> Operands;
3509         for (const SCEV *Op : M->operands())
3510           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3511         if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
3512           // Find an operand that's safely divisible.
3513           for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3514             const SCEV *Op = M->getOperand(i);
3515             const SCEV *Div = getUDivExpr(Op, RHSC);
3516             if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
3517               Operands = SmallVector<const SCEV *, 4>(M->operands());
3518               Operands[i] = Div;
3519               return getMulExpr(Operands);
3520             }
3521           }
3522       }
3523 
3524       // (A/B)/C --> A/(B*C) if safe and B*C can be folded.
3525       if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) {
3526         if (auto *DivisorConstant =
3527                 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) {
3528           bool Overflow = false;
3529           APInt NewRHS =
3530               DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow);
3531           if (Overflow) {
3532             return getConstant(RHSC->getType(), 0, false);
3533           }
3534           return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS));
3535         }
3536       }
3537 
3538       // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
3539       if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
3540         SmallVector<const SCEV *, 4> Operands;
3541         for (const SCEV *Op : A->operands())
3542           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3543         if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
3544           Operands.clear();
3545           for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
3546             const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
3547             if (isa<SCEVUDivExpr>(Op) ||
3548                 getMulExpr(Op, RHS) != A->getOperand(i))
3549               break;
3550             Operands.push_back(Op);
3551           }
3552           if (Operands.size() == A->getNumOperands())
3553             return getAddExpr(Operands);
3554         }
3555       }
3556 
3557       // Fold if both operands are constant.
3558       if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS))
3559         return getConstant(LHSC->getAPInt().udiv(RHSC->getAPInt()));
3560     }
3561   }
3562 
3563   // The Insertion Point (IP) might be invalid by now (due to UniqueSCEVs
3564   // changes). Make sure we get a new one.
3565   IP = nullptr;
3566   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3567   SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
3568                                              LHS, RHS);
3569   UniqueSCEVs.InsertNode(S, IP);
3570   registerUser(S, {LHS, RHS});
3571   return S;
3572 }
3573 
3574 APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
3575   APInt A = C1->getAPInt().abs();
3576   APInt B = C2->getAPInt().abs();
3577   uint32_t ABW = A.getBitWidth();
3578   uint32_t BBW = B.getBitWidth();
3579 
3580   if (ABW > BBW)
3581     B = B.zext(ABW);
3582   else if (ABW < BBW)
3583     A = A.zext(BBW);
3584 
3585   return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B));
3586 }
3587 
3588 /// Get a canonical unsigned division expression, or something simpler if
3589 /// possible. There is no representation for an exact udiv in SCEV IR, but we
3590 /// can attempt to remove factors from the LHS and RHS.  We can't do this when
3591 /// it's not exact because the udiv may be clearing bits.
3592 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
3593                                               const SCEV *RHS) {
3594   // TODO: we could try to find factors in all sorts of things, but for now we
3595   // just deal with u/exact (multiply, constant). See SCEVDivision towards the
3596   // end of this file for inspiration.
3597 
3598   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
3599   if (!Mul || !Mul->hasNoUnsignedWrap())
3600     return getUDivExpr(LHS, RHS);
3601 
3602   if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
3603     // If the mulexpr multiplies by a constant, then that constant must be the
3604     // first element of the mulexpr.
3605     if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
3606       if (LHSCst == RHSCst) {
3607         SmallVector<const SCEV *, 2> Operands(drop_begin(Mul->operands()));
3608         return getMulExpr(Operands);
3609       }
3610 
3611       // We can't just assume that LHSCst divides RHSCst cleanly, it could be
3612       // that there's a factor provided by one of the other terms. We need to
3613       // check.
3614       APInt Factor = gcd(LHSCst, RHSCst);
3615       if (!Factor.isIntN(1)) {
3616         LHSCst =
3617             cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
3618         RHSCst =
3619             cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
3620         SmallVector<const SCEV *, 2> Operands;
3621         Operands.push_back(LHSCst);
3622         append_range(Operands, Mul->operands().drop_front());
3623         LHS = getMulExpr(Operands);
3624         RHS = RHSCst;
3625         Mul = dyn_cast<SCEVMulExpr>(LHS);
3626         if (!Mul)
3627           return getUDivExactExpr(LHS, RHS);
3628       }
3629     }
3630   }
3631 
3632   for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3633     if (Mul->getOperand(i) == RHS) {
3634       SmallVector<const SCEV *, 2> Operands;
3635       append_range(Operands, Mul->operands().take_front(i));
3636       append_range(Operands, Mul->operands().drop_front(i + 1));
3637       return getMulExpr(Operands);
3638     }
3639   }
3640 
3641   return getUDivExpr(LHS, RHS);
3642 }
3643 
3644 /// Get an add recurrence expression for the specified loop.  Simplify the
3645 /// expression as much as possible.
3646 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
3647                                            const Loop *L,
3648                                            SCEV::NoWrapFlags Flags) {
3649   SmallVector<const SCEV *, 4> Operands;
3650   Operands.push_back(Start);
3651   if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3652     if (StepChrec->getLoop() == L) {
3653       append_range(Operands, StepChrec->operands());
3654       return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
3655     }
3656 
3657   Operands.push_back(Step);
3658   return getAddRecExpr(Operands, L, Flags);
3659 }
3660 
3661 /// Get an add recurrence expression for the specified loop.  Simplify the
3662 /// expression as much as possible.
3663 const SCEV *
3664 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
3665                                const Loop *L, SCEV::NoWrapFlags Flags) {
3666   if (Operands.size() == 1) return Operands[0];
3667 #ifndef NDEBUG
3668   Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
3669   for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
3670     assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
3671            "SCEVAddRecExpr operand types don't match!");
3672     assert(!Operands[i]->getType()->isPointerTy() && "Step must be integer");
3673   }
3674   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3675     assert(isAvailableAtLoopEntry(Operands[i], L) &&
3676            "SCEVAddRecExpr operand is not available at loop entry!");
3677 #endif
3678 
3679   if (Operands.back()->isZero()) {
3680     Operands.pop_back();
3681     return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0}  -->  X
3682   }
3683 
3684   // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and
3685   // use that information to infer NUW and NSW flags. However, computing a
3686   // BE count requires calling getAddRecExpr, so we may not yet have a
3687   // meaningful BE count at this point (and if we don't, we'd be stuck
3688   // with a SCEVCouldNotCompute as the cached BE count).
3689 
3690   Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
3691 
3692   // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3693   if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3694     const Loop *NestedLoop = NestedAR->getLoop();
3695     if (L->contains(NestedLoop)
3696             ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3697             : (!NestedLoop->contains(L) &&
3698                DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3699       SmallVector<const SCEV *, 4> NestedOperands(NestedAR->operands());
3700       Operands[0] = NestedAR->getStart();
3701       // AddRecs require their operands be loop-invariant with respect to their
3702       // loops. Don't perform this transformation if it would break this
3703       // requirement.
3704       bool AllInvariant = all_of(
3705           Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3706 
3707       if (AllInvariant) {
3708         // Create a recurrence for the outer loop with the same step size.
3709         //
3710         // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3711         // inner recurrence has the same property.
3712         SCEV::NoWrapFlags OuterFlags =
3713           maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3714 
3715         NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3716         AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3717           return isLoopInvariant(Op, NestedLoop);
3718         });
3719 
3720         if (AllInvariant) {
3721           // Ok, both add recurrences are valid after the transformation.
3722           //
3723           // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3724           // the outer recurrence has the same property.
3725           SCEV::NoWrapFlags InnerFlags =
3726             maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
3727           return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3728         }
3729       }
3730       // Reset Operands to its original state.
3731       Operands[0] = NestedAR;
3732     }
3733   }
3734 
3735   // Okay, it looks like we really DO need an addrec expr.  Check to see if we
3736   // already have one, otherwise create a new one.
3737   return getOrCreateAddRecExpr(Operands, L, Flags);
3738 }
3739 
3740 const SCEV *
3741 ScalarEvolution::getGEPExpr(GEPOperator *GEP,
3742                             const SmallVectorImpl<const SCEV *> &IndexExprs) {
3743   const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3744   // getSCEV(Base)->getType() has the same address space as Base->getType()
3745   // because SCEV::getType() preserves the address space.
3746   Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType());
3747   const bool AssumeInBoundsFlags = [&]() {
3748     if (!GEP->isInBounds())
3749       return false;
3750 
3751     // We'd like to propagate flags from the IR to the corresponding SCEV nodes,
3752     // but to do that, we have to ensure that said flag is valid in the entire
3753     // defined scope of the SCEV.
3754     auto *GEPI = dyn_cast<Instruction>(GEP);
3755     // TODO: non-instructions have global scope.  We might be able to prove
3756     // some global scope cases
3757     return GEPI && isSCEVExprNeverPoison(GEPI);
3758   }();
3759 
3760   SCEV::NoWrapFlags OffsetWrap =
3761     AssumeInBoundsFlags ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3762 
3763   Type *CurTy = GEP->getType();
3764   bool FirstIter = true;
3765   SmallVector<const SCEV *, 4> Offsets;
3766   for (const SCEV *IndexExpr : IndexExprs) {
3767     // Compute the (potentially symbolic) offset in bytes for this index.
3768     if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3769       // For a struct, add the member offset.
3770       ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3771       unsigned FieldNo = Index->getZExtValue();
3772       const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo);
3773       Offsets.push_back(FieldOffset);
3774 
3775       // Update CurTy to the type of the field at Index.
3776       CurTy = STy->getTypeAtIndex(Index);
3777     } else {
3778       // Update CurTy to its element type.
3779       if (FirstIter) {
3780         assert(isa<PointerType>(CurTy) &&
3781                "The first index of a GEP indexes a pointer");
3782         CurTy = GEP->getSourceElementType();
3783         FirstIter = false;
3784       } else {
3785         CurTy = GetElementPtrInst::getTypeAtIndex(CurTy, (uint64_t)0);
3786       }
3787       // For an array, add the element offset, explicitly scaled.
3788       const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy);
3789       // Getelementptr indices are signed.
3790       IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy);
3791 
3792       // Multiply the index by the element size to compute the element offset.
3793       const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, OffsetWrap);
3794       Offsets.push_back(LocalOffset);
3795     }
3796   }
3797 
3798   // Handle degenerate case of GEP without offsets.
3799   if (Offsets.empty())
3800     return BaseExpr;
3801 
3802   // Add the offsets together, assuming nsw if inbounds.
3803   const SCEV *Offset = getAddExpr(Offsets, OffsetWrap);
3804   // Add the base address and the offset. We cannot use the nsw flag, as the
3805   // base address is unsigned. However, if we know that the offset is
3806   // non-negative, we can use nuw.
3807   SCEV::NoWrapFlags BaseWrap = AssumeInBoundsFlags && isKnownNonNegative(Offset)
3808                                    ? SCEV::FlagNUW : SCEV::FlagAnyWrap;
3809   auto *GEPExpr = getAddExpr(BaseExpr, Offset, BaseWrap);
3810   assert(BaseExpr->getType() == GEPExpr->getType() &&
3811          "GEP should not change type mid-flight.");
3812   return GEPExpr;
3813 }
3814 
3815 SCEV *ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType,
3816                                                ArrayRef<const SCEV *> Ops) {
3817   FoldingSetNodeID ID;
3818   ID.AddInteger(SCEVType);
3819   for (const SCEV *Op : Ops)
3820     ID.AddPointer(Op);
3821   void *IP = nullptr;
3822   return UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
3823 }
3824 
3825 const SCEV *ScalarEvolution::getAbsExpr(const SCEV *Op, bool IsNSW) {
3826   SCEV::NoWrapFlags Flags = IsNSW ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3827   return getSMaxExpr(Op, getNegativeSCEV(Op, Flags));
3828 }
3829 
3830 const SCEV *ScalarEvolution::getMinMaxExpr(SCEVTypes Kind,
3831                                            SmallVectorImpl<const SCEV *> &Ops) {
3832   assert(SCEVMinMaxExpr::isMinMaxType(Kind) && "Not a SCEVMinMaxExpr!");
3833   assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
3834   if (Ops.size() == 1) return Ops[0];
3835 #ifndef NDEBUG
3836   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3837   for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
3838     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3839            "Operand types don't match!");
3840     assert(Ops[0]->getType()->isPointerTy() ==
3841                Ops[i]->getType()->isPointerTy() &&
3842            "min/max should be consistently pointerish");
3843   }
3844 #endif
3845 
3846   bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr;
3847   bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr;
3848 
3849   // Sort by complexity, this groups all similar expression types together.
3850   GroupByComplexity(Ops, &LI, DT);
3851 
3852   // Check if we have created the same expression before.
3853   if (const SCEV *S = findExistingSCEVInCache(Kind, Ops)) {
3854     return S;
3855   }
3856 
3857   // If there are any constants, fold them together.
3858   unsigned Idx = 0;
3859   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3860     ++Idx;
3861     assert(Idx < Ops.size());
3862     auto FoldOp = [&](const APInt &LHS, const APInt &RHS) {
3863       switch (Kind) {
3864       case scSMaxExpr:
3865         return APIntOps::smax(LHS, RHS);
3866       case scSMinExpr:
3867         return APIntOps::smin(LHS, RHS);
3868       case scUMaxExpr:
3869         return APIntOps::umax(LHS, RHS);
3870       case scUMinExpr:
3871         return APIntOps::umin(LHS, RHS);
3872       default:
3873         llvm_unreachable("Unknown SCEV min/max opcode");
3874       }
3875     };
3876 
3877     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3878       // We found two constants, fold them together!
3879       ConstantInt *Fold = ConstantInt::get(
3880           getContext(), FoldOp(LHSC->getAPInt(), RHSC->getAPInt()));
3881       Ops[0] = getConstant(Fold);
3882       Ops.erase(Ops.begin()+1);  // Erase the folded element
3883       if (Ops.size() == 1) return Ops[0];
3884       LHSC = cast<SCEVConstant>(Ops[0]);
3885     }
3886 
3887     bool IsMinV = LHSC->getValue()->isMinValue(IsSigned);
3888     bool IsMaxV = LHSC->getValue()->isMaxValue(IsSigned);
3889 
3890     if (IsMax ? IsMinV : IsMaxV) {
3891       // If we are left with a constant minimum(/maximum)-int, strip it off.
3892       Ops.erase(Ops.begin());
3893       --Idx;
3894     } else if (IsMax ? IsMaxV : IsMinV) {
3895       // If we have a max(/min) with a constant maximum(/minimum)-int,
3896       // it will always be the extremum.
3897       return LHSC;
3898     }
3899 
3900     if (Ops.size() == 1) return Ops[0];
3901   }
3902 
3903   // Find the first operation of the same kind
3904   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind)
3905     ++Idx;
3906 
3907   // Check to see if one of the operands is of the same kind. If so, expand its
3908   // operands onto our operand list, and recurse to simplify.
3909   if (Idx < Ops.size()) {
3910     bool DeletedAny = false;
3911     while (Ops[Idx]->getSCEVType() == Kind) {
3912       const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]);
3913       Ops.erase(Ops.begin()+Idx);
3914       append_range(Ops, SMME->operands());
3915       DeletedAny = true;
3916     }
3917 
3918     if (DeletedAny)
3919       return getMinMaxExpr(Kind, Ops);
3920   }
3921 
3922   // Okay, check to see if the same value occurs in the operand list twice.  If
3923   // so, delete one.  Since we sorted the list, these values are required to
3924   // be adjacent.
3925   llvm::CmpInst::Predicate GEPred =
3926       IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
3927   llvm::CmpInst::Predicate LEPred =
3928       IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
3929   llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred;
3930   llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred;
3931   for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) {
3932     if (Ops[i] == Ops[i + 1] ||
3933         isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) {
3934       //  X op Y op Y  -->  X op Y
3935       //  X op Y       -->  X, if we know X, Y are ordered appropriately
3936       Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2);
3937       --i;
3938       --e;
3939     } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i],
3940                                                Ops[i + 1])) {
3941       //  X op Y       -->  Y, if we know X, Y are ordered appropriately
3942       Ops.erase(Ops.begin() + i, Ops.begin() + i + 1);
3943       --i;
3944       --e;
3945     }
3946   }
3947 
3948   if (Ops.size() == 1) return Ops[0];
3949 
3950   assert(!Ops.empty() && "Reduced smax down to nothing!");
3951 
3952   // Okay, it looks like we really DO need an expr.  Check to see if we
3953   // already have one, otherwise create a new one.
3954   FoldingSetNodeID ID;
3955   ID.AddInteger(Kind);
3956   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3957     ID.AddPointer(Ops[i]);
3958   void *IP = nullptr;
3959   const SCEV *ExistingSCEV = UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
3960   if (ExistingSCEV)
3961     return ExistingSCEV;
3962   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3963   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3964   SCEV *S = new (SCEVAllocator)
3965       SCEVMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
3966 
3967   UniqueSCEVs.InsertNode(S, IP);
3968   registerUser(S, Ops);
3969   return S;
3970 }
3971 
3972 namespace {
3973 
3974 class SCEVSequentialMinMaxDeduplicatingVisitor final
3975     : public SCEVVisitor<SCEVSequentialMinMaxDeduplicatingVisitor,
3976                          std::optional<const SCEV *>> {
3977   using RetVal = std::optional<const SCEV *>;
3978   using Base = SCEVVisitor<SCEVSequentialMinMaxDeduplicatingVisitor, RetVal>;
3979 
3980   ScalarEvolution &SE;
3981   const SCEVTypes RootKind; // Must be a sequential min/max expression.
3982   const SCEVTypes NonSequentialRootKind; // Non-sequential variant of RootKind.
3983   SmallPtrSet<const SCEV *, 16> SeenOps;
3984 
3985   bool canRecurseInto(SCEVTypes Kind) const {
3986     // We can only recurse into the SCEV expression of the same effective type
3987     // as the type of our root SCEV expression.
3988     return RootKind == Kind || NonSequentialRootKind == Kind;
3989   };
3990 
3991   RetVal visitAnyMinMaxExpr(const SCEV *S) {
3992     assert((isa<SCEVMinMaxExpr>(S) || isa<SCEVSequentialMinMaxExpr>(S)) &&
3993            "Only for min/max expressions.");
3994     SCEVTypes Kind = S->getSCEVType();
3995 
3996     if (!canRecurseInto(Kind))
3997       return S;
3998 
3999     auto *NAry = cast<SCEVNAryExpr>(S);
4000     SmallVector<const SCEV *> NewOps;
4001     bool Changed = visit(Kind, NAry->operands(), NewOps);
4002 
4003     if (!Changed)
4004       return S;
4005     if (NewOps.empty())
4006       return std::nullopt;
4007 
4008     return isa<SCEVSequentialMinMaxExpr>(S)
4009                ? SE.getSequentialMinMaxExpr(Kind, NewOps)
4010                : SE.getMinMaxExpr(Kind, NewOps);
4011   }
4012 
4013   RetVal visit(const SCEV *S) {
4014     // Has the whole operand been seen already?
4015     if (!SeenOps.insert(S).second)
4016       return std::nullopt;
4017     return Base::visit(S);
4018   }
4019 
4020 public:
4021   SCEVSequentialMinMaxDeduplicatingVisitor(ScalarEvolution &SE,
4022                                            SCEVTypes RootKind)
4023       : SE(SE), RootKind(RootKind),
4024         NonSequentialRootKind(
4025             SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType(
4026                 RootKind)) {}
4027 
4028   bool /*Changed*/ visit(SCEVTypes Kind, ArrayRef<const SCEV *> OrigOps,
4029                          SmallVectorImpl<const SCEV *> &NewOps) {
4030     bool Changed = false;
4031     SmallVector<const SCEV *> Ops;
4032     Ops.reserve(OrigOps.size());
4033 
4034     for (const SCEV *Op : OrigOps) {
4035       RetVal NewOp = visit(Op);
4036       if (NewOp != Op)
4037         Changed = true;
4038       if (NewOp)
4039         Ops.emplace_back(*NewOp);
4040     }
4041 
4042     if (Changed)
4043       NewOps = std::move(Ops);
4044     return Changed;
4045   }
4046 
4047   RetVal visitConstant(const SCEVConstant *Constant) { return Constant; }
4048 
4049   RetVal visitVScale(const SCEVVScale *VScale) { return VScale; }
4050 
4051   RetVal visitPtrToIntExpr(const SCEVPtrToIntExpr *Expr) { return Expr; }
4052 
4053   RetVal visitTruncateExpr(const SCEVTruncateExpr *Expr) { return Expr; }
4054 
4055   RetVal visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { return Expr; }
4056 
4057   RetVal visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { return Expr; }
4058 
4059   RetVal visitAddExpr(const SCEVAddExpr *Expr) { return Expr; }
4060 
4061   RetVal visitMulExpr(const SCEVMulExpr *Expr) { return Expr; }
4062 
4063   RetVal visitUDivExpr(const SCEVUDivExpr *Expr) { return Expr; }
4064 
4065   RetVal visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; }
4066 
4067   RetVal visitSMaxExpr(const SCEVSMaxExpr *Expr) {
4068     return visitAnyMinMaxExpr(Expr);
4069   }
4070 
4071   RetVal visitUMaxExpr(const SCEVUMaxExpr *Expr) {
4072     return visitAnyMinMaxExpr(Expr);
4073   }
4074 
4075   RetVal visitSMinExpr(const SCEVSMinExpr *Expr) {
4076     return visitAnyMinMaxExpr(Expr);
4077   }
4078 
4079   RetVal visitUMinExpr(const SCEVUMinExpr *Expr) {
4080     return visitAnyMinMaxExpr(Expr);
4081   }
4082 
4083   RetVal visitSequentialUMinExpr(const SCEVSequentialUMinExpr *Expr) {
4084     return visitAnyMinMaxExpr(Expr);
4085   }
4086 
4087   RetVal visitUnknown(const SCEVUnknown *Expr) { return Expr; }
4088 
4089   RetVal visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { return Expr; }
4090 };
4091 
4092 } // namespace
4093 
4094 static bool scevUnconditionallyPropagatesPoisonFromOperands(SCEVTypes Kind) {
4095   switch (Kind) {
4096   case scConstant:
4097   case scVScale:
4098   case scTruncate:
4099   case scZeroExtend:
4100   case scSignExtend:
4101   case scPtrToInt:
4102   case scAddExpr:
4103   case scMulExpr:
4104   case scUDivExpr:
4105   case scAddRecExpr:
4106   case scUMaxExpr:
4107   case scSMaxExpr:
4108   case scUMinExpr:
4109   case scSMinExpr:
4110   case scUnknown:
4111     // If any operand is poison, the whole expression is poison.
4112     return true;
4113   case scSequentialUMinExpr:
4114     // FIXME: if the *first* operand is poison, the whole expression is poison.
4115     return false; // Pessimistically, say that it does not propagate poison.
4116   case scCouldNotCompute:
4117     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
4118   }
4119   llvm_unreachable("Unknown SCEV kind!");
4120 }
4121 
4122 namespace {
4123 // The only way poison may be introduced in a SCEV expression is from a
4124 // poison SCEVUnknown (ConstantExprs are also represented as SCEVUnknown,
4125 // not SCEVConstant). Notably, nowrap flags in SCEV nodes can *not*
4126 // introduce poison -- they encode guaranteed, non-speculated knowledge.
4127 //
4128 // Additionally, all SCEV nodes propagate poison from inputs to outputs,
4129 // with the notable exception of umin_seq, where only poison from the first
4130 // operand is (unconditionally) propagated.
4131 struct SCEVPoisonCollector {
4132   bool LookThroughMaybePoisonBlocking;
4133   SmallPtrSet<const SCEVUnknown *, 4> MaybePoison;
4134   SCEVPoisonCollector(bool LookThroughMaybePoisonBlocking)
4135       : LookThroughMaybePoisonBlocking(LookThroughMaybePoisonBlocking) {}
4136 
4137   bool follow(const SCEV *S) {
4138     if (!LookThroughMaybePoisonBlocking &&
4139         !scevUnconditionallyPropagatesPoisonFromOperands(S->getSCEVType()))
4140       return false;
4141 
4142     if (auto *SU = dyn_cast<SCEVUnknown>(S)) {
4143       if (!isGuaranteedNotToBePoison(SU->getValue()))
4144         MaybePoison.insert(SU);
4145     }
4146     return true;
4147   }
4148   bool isDone() const { return false; }
4149 };
4150 } // namespace
4151 
4152 /// Return true if V is poison given that AssumedPoison is already poison.
4153 static bool impliesPoison(const SCEV *AssumedPoison, const SCEV *S) {
4154   // First collect all SCEVs that might result in AssumedPoison to be poison.
4155   // We need to look through potentially poison-blocking operations here,
4156   // because we want to find all SCEVs that *might* result in poison, not only
4157   // those that are *required* to.
4158   SCEVPoisonCollector PC1(/* LookThroughMaybePoisonBlocking */ true);
4159   visitAll(AssumedPoison, PC1);
4160 
4161   // AssumedPoison is never poison. As the assumption is false, the implication
4162   // is true. Don't bother walking the other SCEV in this case.
4163   if (PC1.MaybePoison.empty())
4164     return true;
4165 
4166   // Collect all SCEVs in S that, if poison, *will* result in S being poison
4167   // as well. We cannot look through potentially poison-blocking operations
4168   // here, as their arguments only *may* make the result poison.
4169   SCEVPoisonCollector PC2(/* LookThroughMaybePoisonBlocking */ false);
4170   visitAll(S, PC2);
4171 
4172   // Make sure that no matter which SCEV in PC1.MaybePoison is actually poison,
4173   // it will also make S poison by being part of PC2.MaybePoison.
4174   return all_of(PC1.MaybePoison, [&](const SCEVUnknown *S) {
4175     return PC2.MaybePoison.contains(S);
4176   });
4177 }
4178 
4179 void ScalarEvolution::getPoisonGeneratingValues(
4180     SmallPtrSetImpl<const Value *> &Result, const SCEV *S) {
4181   SCEVPoisonCollector PC(/* LookThroughMaybePoisonBlocking */ false);
4182   visitAll(S, PC);
4183   for (const SCEVUnknown *SU : PC.MaybePoison)
4184     Result.insert(SU->getValue());
4185 }
4186 
4187 const SCEV *
4188 ScalarEvolution::getSequentialMinMaxExpr(SCEVTypes Kind,
4189                                          SmallVectorImpl<const SCEV *> &Ops) {
4190   assert(SCEVSequentialMinMaxExpr::isSequentialMinMaxType(Kind) &&
4191          "Not a SCEVSequentialMinMaxExpr!");
4192   assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
4193   if (Ops.size() == 1)
4194     return Ops[0];
4195 #ifndef NDEBUG
4196   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
4197   for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
4198     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
4199            "Operand types don't match!");
4200     assert(Ops[0]->getType()->isPointerTy() ==
4201                Ops[i]->getType()->isPointerTy() &&
4202            "min/max should be consistently pointerish");
4203   }
4204 #endif
4205 
4206   // Note that SCEVSequentialMinMaxExpr is *NOT* commutative,
4207   // so we can *NOT* do any kind of sorting of the expressions!
4208 
4209   // Check if we have created the same expression before.
4210   if (const SCEV *S = findExistingSCEVInCache(Kind, Ops))
4211     return S;
4212 
4213   // FIXME: there are *some* simplifications that we can do here.
4214 
4215   // Keep only the first instance of an operand.
4216   {
4217     SCEVSequentialMinMaxDeduplicatingVisitor Deduplicator(*this, Kind);
4218     bool Changed = Deduplicator.visit(Kind, Ops, Ops);
4219     if (Changed)
4220       return getSequentialMinMaxExpr(Kind, Ops);
4221   }
4222 
4223   // Check to see if one of the operands is of the same kind. If so, expand its
4224   // operands onto our operand list, and recurse to simplify.
4225   {
4226     unsigned Idx = 0;
4227     bool DeletedAny = false;
4228     while (Idx < Ops.size()) {
4229       if (Ops[Idx]->getSCEVType() != Kind) {
4230         ++Idx;
4231         continue;
4232       }
4233       const auto *SMME = cast<SCEVSequentialMinMaxExpr>(Ops[Idx]);
4234       Ops.erase(Ops.begin() + Idx);
4235       Ops.insert(Ops.begin() + Idx, SMME->operands().begin(),
4236                  SMME->operands().end());
4237       DeletedAny = true;
4238     }
4239 
4240     if (DeletedAny)
4241       return getSequentialMinMaxExpr(Kind, Ops);
4242   }
4243 
4244   const SCEV *SaturationPoint;
4245   ICmpInst::Predicate Pred;
4246   switch (Kind) {
4247   case scSequentialUMinExpr:
4248     SaturationPoint = getZero(Ops[0]->getType());
4249     Pred = ICmpInst::ICMP_ULE;
4250     break;
4251   default:
4252     llvm_unreachable("Not a sequential min/max type.");
4253   }
4254 
4255   for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
4256     // We can replace %x umin_seq %y with %x umin %y if either:
4257     //  * %y being poison implies %x is also poison.
4258     //  * %x cannot be the saturating value (e.g. zero for umin).
4259     if (::impliesPoison(Ops[i], Ops[i - 1]) ||
4260         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, Ops[i - 1],
4261                                         SaturationPoint)) {
4262       SmallVector<const SCEV *> SeqOps = {Ops[i - 1], Ops[i]};
4263       Ops[i - 1] = getMinMaxExpr(
4264           SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType(Kind),
4265           SeqOps);
4266       Ops.erase(Ops.begin() + i);
4267       return getSequentialMinMaxExpr(Kind, Ops);
4268     }
4269     // Fold %x umin_seq %y to %x if %x ule %y.
4270     // TODO: We might be able to prove the predicate for a later operand.
4271     if (isKnownViaNonRecursiveReasoning(Pred, Ops[i - 1], Ops[i])) {
4272       Ops.erase(Ops.begin() + i);
4273       return getSequentialMinMaxExpr(Kind, Ops);
4274     }
4275   }
4276 
4277   // Okay, it looks like we really DO need an expr.  Check to see if we
4278   // already have one, otherwise create a new one.
4279   FoldingSetNodeID ID;
4280   ID.AddInteger(Kind);
4281   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
4282     ID.AddPointer(Ops[i]);
4283   void *IP = nullptr;
4284   const SCEV *ExistingSCEV = UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
4285   if (ExistingSCEV)
4286     return ExistingSCEV;
4287 
4288   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
4289   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
4290   SCEV *S = new (SCEVAllocator)
4291       SCEVSequentialMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
4292 
4293   UniqueSCEVs.InsertNode(S, IP);
4294   registerUser(S, Ops);
4295   return S;
4296 }
4297 
4298 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) {
4299   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
4300   return getSMaxExpr(Ops);
4301 }
4302 
4303 const SCEV *ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
4304   return getMinMaxExpr(scSMaxExpr, Ops);
4305 }
4306 
4307 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) {
4308   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
4309   return getUMaxExpr(Ops);
4310 }
4311 
4312 const SCEV *ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
4313   return getMinMaxExpr(scUMaxExpr, Ops);
4314 }
4315 
4316 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
4317                                          const SCEV *RHS) {
4318   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
4319   return getSMinExpr(Ops);
4320 }
4321 
4322 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) {
4323   return getMinMaxExpr(scSMinExpr, Ops);
4324 }
4325 
4326 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, const SCEV *RHS,
4327                                          bool Sequential) {
4328   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
4329   return getUMinExpr(Ops, Sequential);
4330 }
4331 
4332 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops,
4333                                          bool Sequential) {
4334   return Sequential ? getSequentialMinMaxExpr(scSequentialUMinExpr, Ops)
4335                     : getMinMaxExpr(scUMinExpr, Ops);
4336 }
4337 
4338 const SCEV *
4339 ScalarEvolution::getSizeOfExpr(Type *IntTy, TypeSize Size) {
4340   const SCEV *Res = getConstant(IntTy, Size.getKnownMinValue());
4341   if (Size.isScalable())
4342     Res = getMulExpr(Res, getVScale(IntTy));
4343   return Res;
4344 }
4345 
4346 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
4347   return getSizeOfExpr(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
4348 }
4349 
4350 const SCEV *ScalarEvolution::getStoreSizeOfExpr(Type *IntTy, Type *StoreTy) {
4351   return getSizeOfExpr(IntTy, getDataLayout().getTypeStoreSize(StoreTy));
4352 }
4353 
4354 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
4355                                              StructType *STy,
4356                                              unsigned FieldNo) {
4357   // We can bypass creating a target-independent constant expression and then
4358   // folding it back into a ConstantInt. This is just a compile-time
4359   // optimization.
4360   const StructLayout *SL = getDataLayout().getStructLayout(STy);
4361   assert(!SL->getSizeInBits().isScalable() &&
4362          "Cannot get offset for structure containing scalable vector types");
4363   return getConstant(IntTy, SL->getElementOffset(FieldNo));
4364 }
4365 
4366 const SCEV *ScalarEvolution::getUnknown(Value *V) {
4367   // Don't attempt to do anything other than create a SCEVUnknown object
4368   // here.  createSCEV only calls getUnknown after checking for all other
4369   // interesting possibilities, and any other code that calls getUnknown
4370   // is doing so in order to hide a value from SCEV canonicalization.
4371 
4372   FoldingSetNodeID ID;
4373   ID.AddInteger(scUnknown);
4374   ID.AddPointer(V);
4375   void *IP = nullptr;
4376   if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
4377     assert(cast<SCEVUnknown>(S)->getValue() == V &&
4378            "Stale SCEVUnknown in uniquing map!");
4379     return S;
4380   }
4381   SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
4382                                             FirstUnknown);
4383   FirstUnknown = cast<SCEVUnknown>(S);
4384   UniqueSCEVs.InsertNode(S, IP);
4385   return S;
4386 }
4387 
4388 //===----------------------------------------------------------------------===//
4389 //            Basic SCEV Analysis and PHI Idiom Recognition Code
4390 //
4391 
4392 /// Test if values of the given type are analyzable within the SCEV
4393 /// framework. This primarily includes integer types, and it can optionally
4394 /// include pointer types if the ScalarEvolution class has access to
4395 /// target-specific information.
4396 bool ScalarEvolution::isSCEVable(Type *Ty) const {
4397   // Integers and pointers are always SCEVable.
4398   return Ty->isIntOrPtrTy();
4399 }
4400 
4401 /// Return the size in bits of the specified type, for which isSCEVable must
4402 /// return true.
4403 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
4404   assert(isSCEVable(Ty) && "Type is not SCEVable!");
4405   if (Ty->isPointerTy())
4406     return getDataLayout().getIndexTypeSizeInBits(Ty);
4407   return getDataLayout().getTypeSizeInBits(Ty);
4408 }
4409 
4410 /// Return a type with the same bitwidth as the given type and which represents
4411 /// how SCEV will treat the given type, for which isSCEVable must return
4412 /// true. For pointer types, this is the pointer index sized integer type.
4413 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
4414   assert(isSCEVable(Ty) && "Type is not SCEVable!");
4415 
4416   if (Ty->isIntegerTy())
4417     return Ty;
4418 
4419   // The only other support type is pointer.
4420   assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
4421   return getDataLayout().getIndexType(Ty);
4422 }
4423 
4424 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const {
4425   return  getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
4426 }
4427 
4428 bool ScalarEvolution::instructionCouldExistWithOperands(const SCEV *A,
4429                                                         const SCEV *B) {
4430   /// For a valid use point to exist, the defining scope of one operand
4431   /// must dominate the other.
4432   bool PreciseA, PreciseB;
4433   auto *ScopeA = getDefiningScopeBound({A}, PreciseA);
4434   auto *ScopeB = getDefiningScopeBound({B}, PreciseB);
4435   if (!PreciseA || !PreciseB)
4436     // Can't tell.
4437     return false;
4438   return (ScopeA == ScopeB) || DT.dominates(ScopeA, ScopeB) ||
4439     DT.dominates(ScopeB, ScopeA);
4440 }
4441 
4442 const SCEV *ScalarEvolution::getCouldNotCompute() {
4443   return CouldNotCompute.get();
4444 }
4445 
4446 bool ScalarEvolution::checkValidity(const SCEV *S) const {
4447   bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
4448     auto *SU = dyn_cast<SCEVUnknown>(S);
4449     return SU && SU->getValue() == nullptr;
4450   });
4451 
4452   return !ContainsNulls;
4453 }
4454 
4455 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
4456   HasRecMapType::iterator I = HasRecMap.find(S);
4457   if (I != HasRecMap.end())
4458     return I->second;
4459 
4460   bool FoundAddRec =
4461       SCEVExprContains(S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); });
4462   HasRecMap.insert({S, FoundAddRec});
4463   return FoundAddRec;
4464 }
4465 
4466 /// Return the ValueOffsetPair set for \p S. \p S can be represented
4467 /// by the value and offset from any ValueOffsetPair in the set.
4468 ArrayRef<Value *> ScalarEvolution::getSCEVValues(const SCEV *S) {
4469   ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
4470   if (SI == ExprValueMap.end())
4471     return std::nullopt;
4472   return SI->second.getArrayRef();
4473 }
4474 
4475 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
4476 /// cannot be used separately. eraseValueFromMap should be used to remove
4477 /// V from ValueExprMap and ExprValueMap at the same time.
4478 void ScalarEvolution::eraseValueFromMap(Value *V) {
4479   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
4480   if (I != ValueExprMap.end()) {
4481     auto EVIt = ExprValueMap.find(I->second);
4482     bool Removed = EVIt->second.remove(V);
4483     (void) Removed;
4484     assert(Removed && "Value not in ExprValueMap?");
4485     ValueExprMap.erase(I);
4486   }
4487 }
4488 
4489 void ScalarEvolution::insertValueToMap(Value *V, const SCEV *S) {
4490   // A recursive query may have already computed the SCEV. It should be
4491   // equivalent, but may not necessarily be exactly the same, e.g. due to lazily
4492   // inferred nowrap flags.
4493   auto It = ValueExprMap.find_as(V);
4494   if (It == ValueExprMap.end()) {
4495     ValueExprMap.insert({SCEVCallbackVH(V, this), S});
4496     ExprValueMap[S].insert(V);
4497   }
4498 }
4499 
4500 /// Return an existing SCEV if it exists, otherwise analyze the expression and
4501 /// create a new one.
4502 const SCEV *ScalarEvolution::getSCEV(Value *V) {
4503   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
4504 
4505   if (const SCEV *S = getExistingSCEV(V))
4506     return S;
4507   return createSCEVIter(V);
4508 }
4509 
4510 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
4511   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
4512 
4513   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
4514   if (I != ValueExprMap.end()) {
4515     const SCEV *S = I->second;
4516     assert(checkValidity(S) &&
4517            "existing SCEV has not been properly invalidated");
4518     return S;
4519   }
4520   return nullptr;
4521 }
4522 
4523 /// Return a SCEV corresponding to -V = -1*V
4524 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
4525                                              SCEV::NoWrapFlags Flags) {
4526   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4527     return getConstant(
4528                cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
4529 
4530   Type *Ty = V->getType();
4531   Ty = getEffectiveSCEVType(Ty);
4532   return getMulExpr(V, getMinusOne(Ty), Flags);
4533 }
4534 
4535 /// If Expr computes ~A, return A else return nullptr
4536 static const SCEV *MatchNotExpr(const SCEV *Expr) {
4537   const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
4538   if (!Add || Add->getNumOperands() != 2 ||
4539       !Add->getOperand(0)->isAllOnesValue())
4540     return nullptr;
4541 
4542   const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
4543   if (!AddRHS || AddRHS->getNumOperands() != 2 ||
4544       !AddRHS->getOperand(0)->isAllOnesValue())
4545     return nullptr;
4546 
4547   return AddRHS->getOperand(1);
4548 }
4549 
4550 /// Return a SCEV corresponding to ~V = -1-V
4551 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
4552   assert(!V->getType()->isPointerTy() && "Can't negate pointer");
4553 
4554   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4555     return getConstant(
4556                 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
4557 
4558   // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y)
4559   if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) {
4560     auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) {
4561       SmallVector<const SCEV *, 2> MatchedOperands;
4562       for (const SCEV *Operand : MME->operands()) {
4563         const SCEV *Matched = MatchNotExpr(Operand);
4564         if (!Matched)
4565           return (const SCEV *)nullptr;
4566         MatchedOperands.push_back(Matched);
4567       }
4568       return getMinMaxExpr(SCEVMinMaxExpr::negate(MME->getSCEVType()),
4569                            MatchedOperands);
4570     };
4571     if (const SCEV *Replaced = MatchMinMaxNegation(MME))
4572       return Replaced;
4573   }
4574 
4575   Type *Ty = V->getType();
4576   Ty = getEffectiveSCEVType(Ty);
4577   return getMinusSCEV(getMinusOne(Ty), V);
4578 }
4579 
4580 const SCEV *ScalarEvolution::removePointerBase(const SCEV *P) {
4581   assert(P->getType()->isPointerTy());
4582 
4583   if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(P)) {
4584     // The base of an AddRec is the first operand.
4585     SmallVector<const SCEV *> Ops{AddRec->operands()};
4586     Ops[0] = removePointerBase(Ops[0]);
4587     // Don't try to transfer nowrap flags for now. We could in some cases
4588     // (for example, if pointer operand of the AddRec is a SCEVUnknown).
4589     return getAddRecExpr(Ops, AddRec->getLoop(), SCEV::FlagAnyWrap);
4590   }
4591   if (auto *Add = dyn_cast<SCEVAddExpr>(P)) {
4592     // The base of an Add is the pointer operand.
4593     SmallVector<const SCEV *> Ops{Add->operands()};
4594     const SCEV **PtrOp = nullptr;
4595     for (const SCEV *&AddOp : Ops) {
4596       if (AddOp->getType()->isPointerTy()) {
4597         assert(!PtrOp && "Cannot have multiple pointer ops");
4598         PtrOp = &AddOp;
4599       }
4600     }
4601     *PtrOp = removePointerBase(*PtrOp);
4602     // Don't try to transfer nowrap flags for now. We could in some cases
4603     // (for example, if the pointer operand of the Add is a SCEVUnknown).
4604     return getAddExpr(Ops);
4605   }
4606   // Any other expression must be a pointer base.
4607   return getZero(P->getType());
4608 }
4609 
4610 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
4611                                           SCEV::NoWrapFlags Flags,
4612                                           unsigned Depth) {
4613   // Fast path: X - X --> 0.
4614   if (LHS == RHS)
4615     return getZero(LHS->getType());
4616 
4617   // If we subtract two pointers with different pointer bases, bail.
4618   // Eventually, we're going to add an assertion to getMulExpr that we
4619   // can't multiply by a pointer.
4620   if (RHS->getType()->isPointerTy()) {
4621     if (!LHS->getType()->isPointerTy() ||
4622         getPointerBase(LHS) != getPointerBase(RHS))
4623       return getCouldNotCompute();
4624     LHS = removePointerBase(LHS);
4625     RHS = removePointerBase(RHS);
4626   }
4627 
4628   // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
4629   // makes it so that we cannot make much use of NUW.
4630   auto AddFlags = SCEV::FlagAnyWrap;
4631   const bool RHSIsNotMinSigned =
4632       !getSignedRangeMin(RHS).isMinSignedValue();
4633   if (hasFlags(Flags, SCEV::FlagNSW)) {
4634     // Let M be the minimum representable signed value. Then (-1)*RHS
4635     // signed-wraps if and only if RHS is M. That can happen even for
4636     // a NSW subtraction because e.g. (-1)*M signed-wraps even though
4637     // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
4638     // (-1)*RHS, we need to prove that RHS != M.
4639     //
4640     // If LHS is non-negative and we know that LHS - RHS does not
4641     // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
4642     // either by proving that RHS > M or that LHS >= 0.
4643     if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
4644       AddFlags = SCEV::FlagNSW;
4645     }
4646   }
4647 
4648   // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
4649   // RHS is NSW and LHS >= 0.
4650   //
4651   // The difficulty here is that the NSW flag may have been proven
4652   // relative to a loop that is to be found in a recurrence in LHS and
4653   // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
4654   // larger scope than intended.
4655   auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
4656 
4657   return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
4658 }
4659 
4660 const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty,
4661                                                      unsigned Depth) {
4662   Type *SrcTy = V->getType();
4663   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4664          "Cannot truncate or zero extend with non-integer arguments!");
4665   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4666     return V;  // No conversion
4667   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4668     return getTruncateExpr(V, Ty, Depth);
4669   return getZeroExtendExpr(V, Ty, Depth);
4670 }
4671 
4672 const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty,
4673                                                      unsigned Depth) {
4674   Type *SrcTy = V->getType();
4675   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4676          "Cannot truncate or zero extend with non-integer arguments!");
4677   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4678     return V;  // No conversion
4679   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4680     return getTruncateExpr(V, Ty, Depth);
4681   return getSignExtendExpr(V, Ty, Depth);
4682 }
4683 
4684 const SCEV *
4685 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
4686   Type *SrcTy = V->getType();
4687   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4688          "Cannot noop or zero extend with non-integer arguments!");
4689   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4690          "getNoopOrZeroExtend cannot truncate!");
4691   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4692     return V;  // No conversion
4693   return getZeroExtendExpr(V, Ty);
4694 }
4695 
4696 const SCEV *
4697 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
4698   Type *SrcTy = V->getType();
4699   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4700          "Cannot noop or sign extend with non-integer arguments!");
4701   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4702          "getNoopOrSignExtend cannot truncate!");
4703   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4704     return V;  // No conversion
4705   return getSignExtendExpr(V, Ty);
4706 }
4707 
4708 const SCEV *
4709 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
4710   Type *SrcTy = V->getType();
4711   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4712          "Cannot noop or any extend with non-integer arguments!");
4713   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4714          "getNoopOrAnyExtend cannot truncate!");
4715   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4716     return V;  // No conversion
4717   return getAnyExtendExpr(V, Ty);
4718 }
4719 
4720 const SCEV *
4721 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
4722   Type *SrcTy = V->getType();
4723   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4724          "Cannot truncate or noop with non-integer arguments!");
4725   assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
4726          "getTruncateOrNoop cannot extend!");
4727   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4728     return V;  // No conversion
4729   return getTruncateExpr(V, Ty);
4730 }
4731 
4732 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
4733                                                         const SCEV *RHS) {
4734   const SCEV *PromotedLHS = LHS;
4735   const SCEV *PromotedRHS = RHS;
4736 
4737   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
4738     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
4739   else
4740     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
4741 
4742   return getUMaxExpr(PromotedLHS, PromotedRHS);
4743 }
4744 
4745 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
4746                                                         const SCEV *RHS,
4747                                                         bool Sequential) {
4748   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
4749   return getUMinFromMismatchedTypes(Ops, Sequential);
4750 }
4751 
4752 const SCEV *
4753 ScalarEvolution::getUMinFromMismatchedTypes(SmallVectorImpl<const SCEV *> &Ops,
4754                                             bool Sequential) {
4755   assert(!Ops.empty() && "At least one operand must be!");
4756   // Trivial case.
4757   if (Ops.size() == 1)
4758     return Ops[0];
4759 
4760   // Find the max type first.
4761   Type *MaxType = nullptr;
4762   for (const auto *S : Ops)
4763     if (MaxType)
4764       MaxType = getWiderType(MaxType, S->getType());
4765     else
4766       MaxType = S->getType();
4767   assert(MaxType && "Failed to find maximum type!");
4768 
4769   // Extend all ops to max type.
4770   SmallVector<const SCEV *, 2> PromotedOps;
4771   for (const auto *S : Ops)
4772     PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType));
4773 
4774   // Generate umin.
4775   return getUMinExpr(PromotedOps, Sequential);
4776 }
4777 
4778 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
4779   // A pointer operand may evaluate to a nonpointer expression, such as null.
4780   if (!V->getType()->isPointerTy())
4781     return V;
4782 
4783   while (true) {
4784     if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
4785       V = AddRec->getStart();
4786     } else if (auto *Add = dyn_cast<SCEVAddExpr>(V)) {
4787       const SCEV *PtrOp = nullptr;
4788       for (const SCEV *AddOp : Add->operands()) {
4789         if (AddOp->getType()->isPointerTy()) {
4790           assert(!PtrOp && "Cannot have multiple pointer ops");
4791           PtrOp = AddOp;
4792         }
4793       }
4794       assert(PtrOp && "Must have pointer op");
4795       V = PtrOp;
4796     } else // Not something we can look further into.
4797       return V;
4798   }
4799 }
4800 
4801 /// Push users of the given Instruction onto the given Worklist.
4802 static void PushDefUseChildren(Instruction *I,
4803                                SmallVectorImpl<Instruction *> &Worklist,
4804                                SmallPtrSetImpl<Instruction *> &Visited) {
4805   // Push the def-use children onto the Worklist stack.
4806   for (User *U : I->users()) {
4807     auto *UserInsn = cast<Instruction>(U);
4808     if (Visited.insert(UserInsn).second)
4809       Worklist.push_back(UserInsn);
4810   }
4811 }
4812 
4813 namespace {
4814 
4815 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start
4816 /// expression in case its Loop is L. If it is not L then
4817 /// if IgnoreOtherLoops is true then use AddRec itself
4818 /// otherwise rewrite cannot be done.
4819 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4820 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
4821 public:
4822   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
4823                              bool IgnoreOtherLoops = true) {
4824     SCEVInitRewriter Rewriter(L, SE);
4825     const SCEV *Result = Rewriter.visit(S);
4826     if (Rewriter.hasSeenLoopVariantSCEVUnknown())
4827       return SE.getCouldNotCompute();
4828     return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops
4829                ? SE.getCouldNotCompute()
4830                : Result;
4831   }
4832 
4833   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4834     if (!SE.isLoopInvariant(Expr, L))
4835       SeenLoopVariantSCEVUnknown = true;
4836     return Expr;
4837   }
4838 
4839   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4840     // Only re-write AddRecExprs for this loop.
4841     if (Expr->getLoop() == L)
4842       return Expr->getStart();
4843     SeenOtherLoops = true;
4844     return Expr;
4845   }
4846 
4847   bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4848 
4849   bool hasSeenOtherLoops() { return SeenOtherLoops; }
4850 
4851 private:
4852   explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
4853       : SCEVRewriteVisitor(SE), L(L) {}
4854 
4855   const Loop *L;
4856   bool SeenLoopVariantSCEVUnknown = false;
4857   bool SeenOtherLoops = false;
4858 };
4859 
4860 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post
4861 /// increment expression in case its Loop is L. If it is not L then
4862 /// use AddRec itself.
4863 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4864 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> {
4865 public:
4866   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) {
4867     SCEVPostIncRewriter Rewriter(L, SE);
4868     const SCEV *Result = Rewriter.visit(S);
4869     return Rewriter.hasSeenLoopVariantSCEVUnknown()
4870         ? SE.getCouldNotCompute()
4871         : Result;
4872   }
4873 
4874   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4875     if (!SE.isLoopInvariant(Expr, L))
4876       SeenLoopVariantSCEVUnknown = true;
4877     return Expr;
4878   }
4879 
4880   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4881     // Only re-write AddRecExprs for this loop.
4882     if (Expr->getLoop() == L)
4883       return Expr->getPostIncExpr(SE);
4884     SeenOtherLoops = true;
4885     return Expr;
4886   }
4887 
4888   bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4889 
4890   bool hasSeenOtherLoops() { return SeenOtherLoops; }
4891 
4892 private:
4893   explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE)
4894       : SCEVRewriteVisitor(SE), L(L) {}
4895 
4896   const Loop *L;
4897   bool SeenLoopVariantSCEVUnknown = false;
4898   bool SeenOtherLoops = false;
4899 };
4900 
4901 /// This class evaluates the compare condition by matching it against the
4902 /// condition of loop latch. If there is a match we assume a true value
4903 /// for the condition while building SCEV nodes.
4904 class SCEVBackedgeConditionFolder
4905     : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> {
4906 public:
4907   static const SCEV *rewrite(const SCEV *S, const Loop *L,
4908                              ScalarEvolution &SE) {
4909     bool IsPosBECond = false;
4910     Value *BECond = nullptr;
4911     if (BasicBlock *Latch = L->getLoopLatch()) {
4912       BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator());
4913       if (BI && BI->isConditional()) {
4914         assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
4915                "Both outgoing branches should not target same header!");
4916         BECond = BI->getCondition();
4917         IsPosBECond = BI->getSuccessor(0) == L->getHeader();
4918       } else {
4919         return S;
4920       }
4921     }
4922     SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE);
4923     return Rewriter.visit(S);
4924   }
4925 
4926   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4927     const SCEV *Result = Expr;
4928     bool InvariantF = SE.isLoopInvariant(Expr, L);
4929 
4930     if (!InvariantF) {
4931       Instruction *I = cast<Instruction>(Expr->getValue());
4932       switch (I->getOpcode()) {
4933       case Instruction::Select: {
4934         SelectInst *SI = cast<SelectInst>(I);
4935         std::optional<const SCEV *> Res =
4936             compareWithBackedgeCondition(SI->getCondition());
4937         if (Res) {
4938           bool IsOne = cast<SCEVConstant>(*Res)->getValue()->isOne();
4939           Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue());
4940         }
4941         break;
4942       }
4943       default: {
4944         std::optional<const SCEV *> Res = compareWithBackedgeCondition(I);
4945         if (Res)
4946           Result = *Res;
4947         break;
4948       }
4949       }
4950     }
4951     return Result;
4952   }
4953 
4954 private:
4955   explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond,
4956                                        bool IsPosBECond, ScalarEvolution &SE)
4957       : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond),
4958         IsPositiveBECond(IsPosBECond) {}
4959 
4960   std::optional<const SCEV *> compareWithBackedgeCondition(Value *IC);
4961 
4962   const Loop *L;
4963   /// Loop back condition.
4964   Value *BackedgeCond = nullptr;
4965   /// Set to true if loop back is on positive branch condition.
4966   bool IsPositiveBECond;
4967 };
4968 
4969 std::optional<const SCEV *>
4970 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) {
4971 
4972   // If value matches the backedge condition for loop latch,
4973   // then return a constant evolution node based on loopback
4974   // branch taken.
4975   if (BackedgeCond == IC)
4976     return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext()))
4977                             : SE.getZero(Type::getInt1Ty(SE.getContext()));
4978   return std::nullopt;
4979 }
4980 
4981 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
4982 public:
4983   static const SCEV *rewrite(const SCEV *S, const Loop *L,
4984                              ScalarEvolution &SE) {
4985     SCEVShiftRewriter Rewriter(L, SE);
4986     const SCEV *Result = Rewriter.visit(S);
4987     return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
4988   }
4989 
4990   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4991     // Only allow AddRecExprs for this loop.
4992     if (!SE.isLoopInvariant(Expr, L))
4993       Valid = false;
4994     return Expr;
4995   }
4996 
4997   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4998     if (Expr->getLoop() == L && Expr->isAffine())
4999       return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
5000     Valid = false;
5001     return Expr;
5002   }
5003 
5004   bool isValid() { return Valid; }
5005 
5006 private:
5007   explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
5008       : SCEVRewriteVisitor(SE), L(L) {}
5009 
5010   const Loop *L;
5011   bool Valid = true;
5012 };
5013 
5014 } // end anonymous namespace
5015 
5016 SCEV::NoWrapFlags
5017 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
5018   if (!AR->isAffine())
5019     return SCEV::FlagAnyWrap;
5020 
5021   using OBO = OverflowingBinaryOperator;
5022 
5023   SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
5024 
5025   if (!AR->hasNoSelfWrap()) {
5026     const SCEV *BECount = getConstantMaxBackedgeTakenCount(AR->getLoop());
5027     if (const SCEVConstant *BECountMax = dyn_cast<SCEVConstant>(BECount)) {
5028       ConstantRange StepCR = getSignedRange(AR->getStepRecurrence(*this));
5029       const APInt &BECountAP = BECountMax->getAPInt();
5030       unsigned NoOverflowBitWidth =
5031         BECountAP.getActiveBits() + StepCR.getMinSignedBits();
5032       if (NoOverflowBitWidth <= getTypeSizeInBits(AR->getType()))
5033         Result = ScalarEvolution::setFlags(Result, SCEV::FlagNW);
5034     }
5035   }
5036 
5037   if (!AR->hasNoSignedWrap()) {
5038     ConstantRange AddRecRange = getSignedRange(AR);
5039     ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
5040 
5041     auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
5042         Instruction::Add, IncRange, OBO::NoSignedWrap);
5043     if (NSWRegion.contains(AddRecRange))
5044       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
5045   }
5046 
5047   if (!AR->hasNoUnsignedWrap()) {
5048     ConstantRange AddRecRange = getUnsignedRange(AR);
5049     ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
5050 
5051     auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
5052         Instruction::Add, IncRange, OBO::NoUnsignedWrap);
5053     if (NUWRegion.contains(AddRecRange))
5054       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
5055   }
5056 
5057   return Result;
5058 }
5059 
5060 SCEV::NoWrapFlags
5061 ScalarEvolution::proveNoSignedWrapViaInduction(const SCEVAddRecExpr *AR) {
5062   SCEV::NoWrapFlags Result = AR->getNoWrapFlags();
5063 
5064   if (AR->hasNoSignedWrap())
5065     return Result;
5066 
5067   if (!AR->isAffine())
5068     return Result;
5069 
5070   // This function can be expensive, only try to prove NSW once per AddRec.
5071   if (!SignedWrapViaInductionTried.insert(AR).second)
5072     return Result;
5073 
5074   const SCEV *Step = AR->getStepRecurrence(*this);
5075   const Loop *L = AR->getLoop();
5076 
5077   // Check whether the backedge-taken count is SCEVCouldNotCompute.
5078   // Note that this serves two purposes: It filters out loops that are
5079   // simply not analyzable, and it covers the case where this code is
5080   // being called from within backedge-taken count analysis, such that
5081   // attempting to ask for the backedge-taken count would likely result
5082   // in infinite recursion. In the later case, the analysis code will
5083   // cope with a conservative value, and it will take care to purge
5084   // that value once it has finished.
5085   const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
5086 
5087   // Normally, in the cases we can prove no-overflow via a
5088   // backedge guarding condition, we can also compute a backedge
5089   // taken count for the loop.  The exceptions are assumptions and
5090   // guards present in the loop -- SCEV is not great at exploiting
5091   // these to compute max backedge taken counts, but can still use
5092   // these to prove lack of overflow.  Use this fact to avoid
5093   // doing extra work that may not pay off.
5094 
5095   if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
5096       AC.assumptions().empty())
5097     return Result;
5098 
5099   // If the backedge is guarded by a comparison with the pre-inc  value the
5100   // addrec is safe. Also, if the entry is guarded by a comparison with the
5101   // start value and the backedge is guarded by a comparison with the post-inc
5102   // value, the addrec is safe.
5103   ICmpInst::Predicate Pred;
5104   const SCEV *OverflowLimit =
5105     getSignedOverflowLimitForStep(Step, &Pred, this);
5106   if (OverflowLimit &&
5107       (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
5108        isKnownOnEveryIteration(Pred, AR, OverflowLimit))) {
5109     Result = setFlags(Result, SCEV::FlagNSW);
5110   }
5111   return Result;
5112 }
5113 SCEV::NoWrapFlags
5114 ScalarEvolution::proveNoUnsignedWrapViaInduction(const SCEVAddRecExpr *AR) {
5115   SCEV::NoWrapFlags Result = AR->getNoWrapFlags();
5116 
5117   if (AR->hasNoUnsignedWrap())
5118     return Result;
5119 
5120   if (!AR->isAffine())
5121     return Result;
5122 
5123   // This function can be expensive, only try to prove NUW once per AddRec.
5124   if (!UnsignedWrapViaInductionTried.insert(AR).second)
5125     return Result;
5126 
5127   const SCEV *Step = AR->getStepRecurrence(*this);
5128   unsigned BitWidth = getTypeSizeInBits(AR->getType());
5129   const Loop *L = AR->getLoop();
5130 
5131   // Check whether the backedge-taken count is SCEVCouldNotCompute.
5132   // Note that this serves two purposes: It filters out loops that are
5133   // simply not analyzable, and it covers the case where this code is
5134   // being called from within backedge-taken count analysis, such that
5135   // attempting to ask for the backedge-taken count would likely result
5136   // in infinite recursion. In the later case, the analysis code will
5137   // cope with a conservative value, and it will take care to purge
5138   // that value once it has finished.
5139   const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
5140 
5141   // Normally, in the cases we can prove no-overflow via a
5142   // backedge guarding condition, we can also compute a backedge
5143   // taken count for the loop.  The exceptions are assumptions and
5144   // guards present in the loop -- SCEV is not great at exploiting
5145   // these to compute max backedge taken counts, but can still use
5146   // these to prove lack of overflow.  Use this fact to avoid
5147   // doing extra work that may not pay off.
5148 
5149   if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
5150       AC.assumptions().empty())
5151     return Result;
5152 
5153   // If the backedge is guarded by a comparison with the pre-inc  value the
5154   // addrec is safe. Also, if the entry is guarded by a comparison with the
5155   // start value and the backedge is guarded by a comparison with the post-inc
5156   // value, the addrec is safe.
5157   if (isKnownPositive(Step)) {
5158     const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
5159                                 getUnsignedRangeMax(Step));
5160     if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
5161         isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) {
5162       Result = setFlags(Result, SCEV::FlagNUW);
5163     }
5164   }
5165 
5166   return Result;
5167 }
5168 
5169 namespace {
5170 
5171 /// Represents an abstract binary operation.  This may exist as a
5172 /// normal instruction or constant expression, or may have been
5173 /// derived from an expression tree.
5174 struct BinaryOp {
5175   unsigned Opcode;
5176   Value *LHS;
5177   Value *RHS;
5178   bool IsNSW = false;
5179   bool IsNUW = false;
5180 
5181   /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
5182   /// constant expression.
5183   Operator *Op = nullptr;
5184 
5185   explicit BinaryOp(Operator *Op)
5186       : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
5187         Op(Op) {
5188     if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
5189       IsNSW = OBO->hasNoSignedWrap();
5190       IsNUW = OBO->hasNoUnsignedWrap();
5191     }
5192   }
5193 
5194   explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
5195                     bool IsNUW = false)
5196       : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {}
5197 };
5198 
5199 } // end anonymous namespace
5200 
5201 /// Try to map \p V into a BinaryOp, and return \c std::nullopt on failure.
5202 static std::optional<BinaryOp> MatchBinaryOp(Value *V, const DataLayout &DL,
5203                                              AssumptionCache &AC,
5204                                              const DominatorTree &DT,
5205                                              const Instruction *CxtI) {
5206   auto *Op = dyn_cast<Operator>(V);
5207   if (!Op)
5208     return std::nullopt;
5209 
5210   // Implementation detail: all the cleverness here should happen without
5211   // creating new SCEV expressions -- our caller knowns tricks to avoid creating
5212   // SCEV expressions when possible, and we should not break that.
5213 
5214   switch (Op->getOpcode()) {
5215   case Instruction::Add:
5216   case Instruction::Sub:
5217   case Instruction::Mul:
5218   case Instruction::UDiv:
5219   case Instruction::URem:
5220   case Instruction::And:
5221   case Instruction::AShr:
5222   case Instruction::Shl:
5223     return BinaryOp(Op);
5224 
5225   case Instruction::Or: {
5226     // Convert or disjoint into add nuw nsw.
5227     if (cast<PossiblyDisjointInst>(Op)->isDisjoint())
5228       return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1),
5229                       /*IsNSW=*/true, /*IsNUW=*/true);
5230     return BinaryOp(Op);
5231   }
5232 
5233   case Instruction::Xor:
5234     if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
5235       // If the RHS of the xor is a signmask, then this is just an add.
5236       // Instcombine turns add of signmask into xor as a strength reduction step.
5237       if (RHSC->getValue().isSignMask())
5238         return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
5239     // Binary `xor` is a bit-wise `add`.
5240     if (V->getType()->isIntegerTy(1))
5241       return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
5242     return BinaryOp(Op);
5243 
5244   case Instruction::LShr:
5245     // Turn logical shift right of a constant into a unsigned divide.
5246     if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
5247       uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
5248 
5249       // If the shift count is not less than the bitwidth, the result of
5250       // the shift is undefined. Don't try to analyze it, because the
5251       // resolution chosen here may differ from the resolution chosen in
5252       // other parts of the compiler.
5253       if (SA->getValue().ult(BitWidth)) {
5254         Constant *X =
5255             ConstantInt::get(SA->getContext(),
5256                              APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
5257         return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
5258       }
5259     }
5260     return BinaryOp(Op);
5261 
5262   case Instruction::ExtractValue: {
5263     auto *EVI = cast<ExtractValueInst>(Op);
5264     if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
5265       break;
5266 
5267     auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand());
5268     if (!WO)
5269       break;
5270 
5271     Instruction::BinaryOps BinOp = WO->getBinaryOp();
5272     bool Signed = WO->isSigned();
5273     // TODO: Should add nuw/nsw flags for mul as well.
5274     if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT))
5275       return BinaryOp(BinOp, WO->getLHS(), WO->getRHS());
5276 
5277     // Now that we know that all uses of the arithmetic-result component of
5278     // CI are guarded by the overflow check, we can go ahead and pretend
5279     // that the arithmetic is non-overflowing.
5280     return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(),
5281                     /* IsNSW = */ Signed, /* IsNUW = */ !Signed);
5282   }
5283 
5284   default:
5285     break;
5286   }
5287 
5288   // Recognise intrinsic loop.decrement.reg, and as this has exactly the same
5289   // semantics as a Sub, return a binary sub expression.
5290   if (auto *II = dyn_cast<IntrinsicInst>(V))
5291     if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg)
5292       return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1));
5293 
5294   return std::nullopt;
5295 }
5296 
5297 /// Helper function to createAddRecFromPHIWithCasts. We have a phi
5298 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
5299 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
5300 /// way. This function checks if \p Op, an operand of this SCEVAddExpr,
5301 /// follows one of the following patterns:
5302 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
5303 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
5304 /// If the SCEV expression of \p Op conforms with one of the expected patterns
5305 /// we return the type of the truncation operation, and indicate whether the
5306 /// truncated type should be treated as signed/unsigned by setting
5307 /// \p Signed to true/false, respectively.
5308 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
5309                                bool &Signed, ScalarEvolution &SE) {
5310   // The case where Op == SymbolicPHI (that is, with no type conversions on
5311   // the way) is handled by the regular add recurrence creating logic and
5312   // would have already been triggered in createAddRecForPHI. Reaching it here
5313   // means that createAddRecFromPHI had failed for this PHI before (e.g.,
5314   // because one of the other operands of the SCEVAddExpr updating this PHI is
5315   // not invariant).
5316   //
5317   // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
5318   // this case predicates that allow us to prove that Op == SymbolicPHI will
5319   // be added.
5320   if (Op == SymbolicPHI)
5321     return nullptr;
5322 
5323   unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
5324   unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
5325   if (SourceBits != NewBits)
5326     return nullptr;
5327 
5328   const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op);
5329   const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op);
5330   if (!SExt && !ZExt)
5331     return nullptr;
5332   const SCEVTruncateExpr *Trunc =
5333       SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand())
5334            : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand());
5335   if (!Trunc)
5336     return nullptr;
5337   const SCEV *X = Trunc->getOperand();
5338   if (X != SymbolicPHI)
5339     return nullptr;
5340   Signed = SExt != nullptr;
5341   return Trunc->getType();
5342 }
5343 
5344 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
5345   if (!PN->getType()->isIntegerTy())
5346     return nullptr;
5347   const Loop *L = LI.getLoopFor(PN->getParent());
5348   if (!L || L->getHeader() != PN->getParent())
5349     return nullptr;
5350   return L;
5351 }
5352 
5353 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
5354 // computation that updates the phi follows the following pattern:
5355 //   (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
5356 // which correspond to a phi->trunc->sext/zext->add->phi update chain.
5357 // If so, try to see if it can be rewritten as an AddRecExpr under some
5358 // Predicates. If successful, return them as a pair. Also cache the results
5359 // of the analysis.
5360 //
5361 // Example usage scenario:
5362 //    Say the Rewriter is called for the following SCEV:
5363 //         8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
5364 //    where:
5365 //         %X = phi i64 (%Start, %BEValue)
5366 //    It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
5367 //    and call this function with %SymbolicPHI = %X.
5368 //
5369 //    The analysis will find that the value coming around the backedge has
5370 //    the following SCEV:
5371 //         BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
5372 //    Upon concluding that this matches the desired pattern, the function
5373 //    will return the pair {NewAddRec, SmallPredsVec} where:
5374 //         NewAddRec = {%Start,+,%Step}
5375 //         SmallPredsVec = {P1, P2, P3} as follows:
5376 //           P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
5377 //           P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
5378 //           P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
5379 //    The returned pair means that SymbolicPHI can be rewritten into NewAddRec
5380 //    under the predicates {P1,P2,P3}.
5381 //    This predicated rewrite will be cached in PredicatedSCEVRewrites:
5382 //         PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
5383 //
5384 // TODO's:
5385 //
5386 // 1) Extend the Induction descriptor to also support inductions that involve
5387 //    casts: When needed (namely, when we are called in the context of the
5388 //    vectorizer induction analysis), a Set of cast instructions will be
5389 //    populated by this method, and provided back to isInductionPHI. This is
5390 //    needed to allow the vectorizer to properly record them to be ignored by
5391 //    the cost model and to avoid vectorizing them (otherwise these casts,
5392 //    which are redundant under the runtime overflow checks, will be
5393 //    vectorized, which can be costly).
5394 //
5395 // 2) Support additional induction/PHISCEV patterns: We also want to support
5396 //    inductions where the sext-trunc / zext-trunc operations (partly) occur
5397 //    after the induction update operation (the induction increment):
5398 //
5399 //      (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
5400 //    which correspond to a phi->add->trunc->sext/zext->phi update chain.
5401 //
5402 //      (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
5403 //    which correspond to a phi->trunc->add->sext/zext->phi update chain.
5404 //
5405 // 3) Outline common code with createAddRecFromPHI to avoid duplication.
5406 std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5407 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
5408   SmallVector<const SCEVPredicate *, 3> Predicates;
5409 
5410   // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
5411   // return an AddRec expression under some predicate.
5412 
5413   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
5414   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
5415   assert(L && "Expecting an integer loop header phi");
5416 
5417   // The loop may have multiple entrances or multiple exits; we can analyze
5418   // this phi as an addrec if it has a unique entry value and a unique
5419   // backedge value.
5420   Value *BEValueV = nullptr, *StartValueV = nullptr;
5421   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5422     Value *V = PN->getIncomingValue(i);
5423     if (L->contains(PN->getIncomingBlock(i))) {
5424       if (!BEValueV) {
5425         BEValueV = V;
5426       } else if (BEValueV != V) {
5427         BEValueV = nullptr;
5428         break;
5429       }
5430     } else if (!StartValueV) {
5431       StartValueV = V;
5432     } else if (StartValueV != V) {
5433       StartValueV = nullptr;
5434       break;
5435     }
5436   }
5437   if (!BEValueV || !StartValueV)
5438     return std::nullopt;
5439 
5440   const SCEV *BEValue = getSCEV(BEValueV);
5441 
5442   // If the value coming around the backedge is an add with the symbolic
5443   // value we just inserted, possibly with casts that we can ignore under
5444   // an appropriate runtime guard, then we found a simple induction variable!
5445   const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
5446   if (!Add)
5447     return std::nullopt;
5448 
5449   // If there is a single occurrence of the symbolic value, possibly
5450   // casted, replace it with a recurrence.
5451   unsigned FoundIndex = Add->getNumOperands();
5452   Type *TruncTy = nullptr;
5453   bool Signed;
5454   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5455     if ((TruncTy =
5456              isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
5457       if (FoundIndex == e) {
5458         FoundIndex = i;
5459         break;
5460       }
5461 
5462   if (FoundIndex == Add->getNumOperands())
5463     return std::nullopt;
5464 
5465   // Create an add with everything but the specified operand.
5466   SmallVector<const SCEV *, 8> Ops;
5467   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5468     if (i != FoundIndex)
5469       Ops.push_back(Add->getOperand(i));
5470   const SCEV *Accum = getAddExpr(Ops);
5471 
5472   // The runtime checks will not be valid if the step amount is
5473   // varying inside the loop.
5474   if (!isLoopInvariant(Accum, L))
5475     return std::nullopt;
5476 
5477   // *** Part2: Create the predicates
5478 
5479   // Analysis was successful: we have a phi-with-cast pattern for which we
5480   // can return an AddRec expression under the following predicates:
5481   //
5482   // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
5483   //     fits within the truncated type (does not overflow) for i = 0 to n-1.
5484   // P2: An Equal predicate that guarantees that
5485   //     Start = (Ext ix (Trunc iy (Start) to ix) to iy)
5486   // P3: An Equal predicate that guarantees that
5487   //     Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
5488   //
5489   // As we next prove, the above predicates guarantee that:
5490   //     Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
5491   //
5492   //
5493   // More formally, we want to prove that:
5494   //     Expr(i+1) = Start + (i+1) * Accum
5495   //               = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5496   //
5497   // Given that:
5498   // 1) Expr(0) = Start
5499   // 2) Expr(1) = Start + Accum
5500   //            = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
5501   // 3) Induction hypothesis (step i):
5502   //    Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
5503   //
5504   // Proof:
5505   //  Expr(i+1) =
5506   //   = Start + (i+1)*Accum
5507   //   = (Start + i*Accum) + Accum
5508   //   = Expr(i) + Accum
5509   //   = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
5510   //                                                             :: from step i
5511   //
5512   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
5513   //
5514   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
5515   //     + (Ext ix (Trunc iy (Accum) to ix) to iy)
5516   //     + Accum                                                     :: from P3
5517   //
5518   //   = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
5519   //     + Accum                            :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
5520   //
5521   //   = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
5522   //   = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5523   //
5524   // By induction, the same applies to all iterations 1<=i<n:
5525   //
5526 
5527   // Create a truncated addrec for which we will add a no overflow check (P1).
5528   const SCEV *StartVal = getSCEV(StartValueV);
5529   const SCEV *PHISCEV =
5530       getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
5531                     getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap);
5532 
5533   // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
5534   // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
5535   // will be constant.
5536   //
5537   //  If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
5538   // add P1.
5539   if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
5540     SCEVWrapPredicate::IncrementWrapFlags AddedFlags =
5541         Signed ? SCEVWrapPredicate::IncrementNSSW
5542                : SCEVWrapPredicate::IncrementNUSW;
5543     const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
5544     Predicates.push_back(AddRecPred);
5545   }
5546 
5547   // Create the Equal Predicates P2,P3:
5548 
5549   // It is possible that the predicates P2 and/or P3 are computable at
5550   // compile time due to StartVal and/or Accum being constants.
5551   // If either one is, then we can check that now and escape if either P2
5552   // or P3 is false.
5553 
5554   // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
5555   // for each of StartVal and Accum
5556   auto getExtendedExpr = [&](const SCEV *Expr,
5557                              bool CreateSignExtend) -> const SCEV * {
5558     assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant");
5559     const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
5560     const SCEV *ExtendedExpr =
5561         CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType())
5562                          : getZeroExtendExpr(TruncatedExpr, Expr->getType());
5563     return ExtendedExpr;
5564   };
5565 
5566   // Given:
5567   //  ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
5568   //               = getExtendedExpr(Expr)
5569   // Determine whether the predicate P: Expr == ExtendedExpr
5570   // is known to be false at compile time
5571   auto PredIsKnownFalse = [&](const SCEV *Expr,
5572                               const SCEV *ExtendedExpr) -> bool {
5573     return Expr != ExtendedExpr &&
5574            isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr);
5575   };
5576 
5577   const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
5578   if (PredIsKnownFalse(StartVal, StartExtended)) {
5579     LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";);
5580     return std::nullopt;
5581   }
5582 
5583   // The Step is always Signed (because the overflow checks are either
5584   // NSSW or NUSW)
5585   const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true);
5586   if (PredIsKnownFalse(Accum, AccumExtended)) {
5587     LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";);
5588     return std::nullopt;
5589   }
5590 
5591   auto AppendPredicate = [&](const SCEV *Expr,
5592                              const SCEV *ExtendedExpr) -> void {
5593     if (Expr != ExtendedExpr &&
5594         !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
5595       const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
5596       LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred);
5597       Predicates.push_back(Pred);
5598     }
5599   };
5600 
5601   AppendPredicate(StartVal, StartExtended);
5602   AppendPredicate(Accum, AccumExtended);
5603 
5604   // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
5605   // which the casts had been folded away. The caller can rewrite SymbolicPHI
5606   // into NewAR if it will also add the runtime overflow checks specified in
5607   // Predicates.
5608   auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap);
5609 
5610   std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
5611       std::make_pair(NewAR, Predicates);
5612   // Remember the result of the analysis for this SCEV at this locayyytion.
5613   PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
5614   return PredRewrite;
5615 }
5616 
5617 std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5618 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) {
5619   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
5620   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
5621   if (!L)
5622     return std::nullopt;
5623 
5624   // Check to see if we already analyzed this PHI.
5625   auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
5626   if (I != PredicatedSCEVRewrites.end()) {
5627     std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
5628         I->second;
5629     // Analysis was done before and failed to create an AddRec:
5630     if (Rewrite.first == SymbolicPHI)
5631       return std::nullopt;
5632     // Analysis was done before and succeeded to create an AddRec under
5633     // a predicate:
5634     assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec");
5635     assert(!(Rewrite.second).empty() && "Expected to find Predicates");
5636     return Rewrite;
5637   }
5638 
5639   std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5640     Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
5641 
5642   // Record in the cache that the analysis failed
5643   if (!Rewrite) {
5644     SmallVector<const SCEVPredicate *, 3> Predicates;
5645     PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
5646     return std::nullopt;
5647   }
5648 
5649   return Rewrite;
5650 }
5651 
5652 // FIXME: This utility is currently required because the Rewriter currently
5653 // does not rewrite this expression:
5654 // {0, +, (sext ix (trunc iy to ix) to iy)}
5655 // into {0, +, %step},
5656 // even when the following Equal predicate exists:
5657 // "%step == (sext ix (trunc iy to ix) to iy)".
5658 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds(
5659     const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const {
5660   if (AR1 == AR2)
5661     return true;
5662 
5663   auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool {
5664     if (Expr1 != Expr2 && !Preds->implies(SE.getEqualPredicate(Expr1, Expr2)) &&
5665         !Preds->implies(SE.getEqualPredicate(Expr2, Expr1)))
5666       return false;
5667     return true;
5668   };
5669 
5670   if (!areExprsEqual(AR1->getStart(), AR2->getStart()) ||
5671       !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE)))
5672     return false;
5673   return true;
5674 }
5675 
5676 /// A helper function for createAddRecFromPHI to handle simple cases.
5677 ///
5678 /// This function tries to find an AddRec expression for the simplest (yet most
5679 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
5680 /// If it fails, createAddRecFromPHI will use a more general, but slow,
5681 /// technique for finding the AddRec expression.
5682 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
5683                                                       Value *BEValueV,
5684                                                       Value *StartValueV) {
5685   const Loop *L = LI.getLoopFor(PN->getParent());
5686   assert(L && L->getHeader() == PN->getParent());
5687   assert(BEValueV && StartValueV);
5688 
5689   auto BO = MatchBinaryOp(BEValueV, getDataLayout(), AC, DT, PN);
5690   if (!BO)
5691     return nullptr;
5692 
5693   if (BO->Opcode != Instruction::Add)
5694     return nullptr;
5695 
5696   const SCEV *Accum = nullptr;
5697   if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
5698     Accum = getSCEV(BO->RHS);
5699   else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
5700     Accum = getSCEV(BO->LHS);
5701 
5702   if (!Accum)
5703     return nullptr;
5704 
5705   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5706   if (BO->IsNUW)
5707     Flags = setFlags(Flags, SCEV::FlagNUW);
5708   if (BO->IsNSW)
5709     Flags = setFlags(Flags, SCEV::FlagNSW);
5710 
5711   const SCEV *StartVal = getSCEV(StartValueV);
5712   const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5713   insertValueToMap(PN, PHISCEV);
5714 
5715   if (auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
5716     setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR),
5717                    (SCEV::NoWrapFlags)(AR->getNoWrapFlags() |
5718                                        proveNoWrapViaConstantRanges(AR)));
5719   }
5720 
5721   // We can add Flags to the post-inc expression only if we
5722   // know that it is *undefined behavior* for BEValueV to
5723   // overflow.
5724   if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) {
5725     assert(isLoopInvariant(Accum, L) &&
5726            "Accum is defined outside L, but is not invariant?");
5727     if (isAddRecNeverPoison(BEInst, L))
5728       (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5729   }
5730 
5731   return PHISCEV;
5732 }
5733 
5734 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
5735   const Loop *L = LI.getLoopFor(PN->getParent());
5736   if (!L || L->getHeader() != PN->getParent())
5737     return nullptr;
5738 
5739   // The loop may have multiple entrances or multiple exits; we can analyze
5740   // this phi as an addrec if it has a unique entry value and a unique
5741   // backedge value.
5742   Value *BEValueV = nullptr, *StartValueV = nullptr;
5743   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5744     Value *V = PN->getIncomingValue(i);
5745     if (L->contains(PN->getIncomingBlock(i))) {
5746       if (!BEValueV) {
5747         BEValueV = V;
5748       } else if (BEValueV != V) {
5749         BEValueV = nullptr;
5750         break;
5751       }
5752     } else if (!StartValueV) {
5753       StartValueV = V;
5754     } else if (StartValueV != V) {
5755       StartValueV = nullptr;
5756       break;
5757     }
5758   }
5759   if (!BEValueV || !StartValueV)
5760     return nullptr;
5761 
5762   assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
5763          "PHI node already processed?");
5764 
5765   // First, try to find AddRec expression without creating a fictituos symbolic
5766   // value for PN.
5767   if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
5768     return S;
5769 
5770   // Handle PHI node value symbolically.
5771   const SCEV *SymbolicName = getUnknown(PN);
5772   insertValueToMap(PN, SymbolicName);
5773 
5774   // Using this symbolic name for the PHI, analyze the value coming around
5775   // the back-edge.
5776   const SCEV *BEValue = getSCEV(BEValueV);
5777 
5778   // NOTE: If BEValue is loop invariant, we know that the PHI node just
5779   // has a special value for the first iteration of the loop.
5780 
5781   // If the value coming around the backedge is an add with the symbolic
5782   // value we just inserted, then we found a simple induction variable!
5783   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
5784     // If there is a single occurrence of the symbolic value, replace it
5785     // with a recurrence.
5786     unsigned FoundIndex = Add->getNumOperands();
5787     for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5788       if (Add->getOperand(i) == SymbolicName)
5789         if (FoundIndex == e) {
5790           FoundIndex = i;
5791           break;
5792         }
5793 
5794     if (FoundIndex != Add->getNumOperands()) {
5795       // Create an add with everything but the specified operand.
5796       SmallVector<const SCEV *, 8> Ops;
5797       for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5798         if (i != FoundIndex)
5799           Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i),
5800                                                              L, *this));
5801       const SCEV *Accum = getAddExpr(Ops);
5802 
5803       // This is not a valid addrec if the step amount is varying each
5804       // loop iteration, but is not itself an addrec in this loop.
5805       if (isLoopInvariant(Accum, L) ||
5806           (isa<SCEVAddRecExpr>(Accum) &&
5807            cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
5808         SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5809 
5810         if (auto BO = MatchBinaryOp(BEValueV, getDataLayout(), AC, DT, PN)) {
5811           if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
5812             if (BO->IsNUW)
5813               Flags = setFlags(Flags, SCEV::FlagNUW);
5814             if (BO->IsNSW)
5815               Flags = setFlags(Flags, SCEV::FlagNSW);
5816           }
5817         } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
5818           // If the increment is an inbounds GEP, then we know the address
5819           // space cannot be wrapped around. We cannot make any guarantee
5820           // about signed or unsigned overflow because pointers are
5821           // unsigned but we may have a negative index from the base
5822           // pointer. We can guarantee that no unsigned wrap occurs if the
5823           // indices form a positive value.
5824           if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
5825             Flags = setFlags(Flags, SCEV::FlagNW);
5826             if (isKnownPositive(Accum))
5827               Flags = setFlags(Flags, SCEV::FlagNUW);
5828           }
5829 
5830           // We cannot transfer nuw and nsw flags from subtraction
5831           // operations -- sub nuw X, Y is not the same as add nuw X, -Y
5832           // for instance.
5833         }
5834 
5835         const SCEV *StartVal = getSCEV(StartValueV);
5836         const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5837 
5838         // Okay, for the entire analysis of this edge we assumed the PHI
5839         // to be symbolic.  We now need to go back and purge all of the
5840         // entries for the scalars that use the symbolic expression.
5841         forgetMemoizedResults(SymbolicName);
5842         insertValueToMap(PN, PHISCEV);
5843 
5844         if (auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
5845           setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR),
5846                          (SCEV::NoWrapFlags)(AR->getNoWrapFlags() |
5847                                              proveNoWrapViaConstantRanges(AR)));
5848         }
5849 
5850         // We can add Flags to the post-inc expression only if we
5851         // know that it is *undefined behavior* for BEValueV to
5852         // overflow.
5853         if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5854           if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5855             (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5856 
5857         return PHISCEV;
5858       }
5859     }
5860   } else {
5861     // Otherwise, this could be a loop like this:
5862     //     i = 0;  for (j = 1; ..; ++j) { ....  i = j; }
5863     // In this case, j = {1,+,1}  and BEValue is j.
5864     // Because the other in-value of i (0) fits the evolution of BEValue
5865     // i really is an addrec evolution.
5866     //
5867     // We can generalize this saying that i is the shifted value of BEValue
5868     // by one iteration:
5869     //   PHI(f(0), f({1,+,1})) --> f({0,+,1})
5870     const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
5871     const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false);
5872     if (Shifted != getCouldNotCompute() &&
5873         Start != getCouldNotCompute()) {
5874       const SCEV *StartVal = getSCEV(StartValueV);
5875       if (Start == StartVal) {
5876         // Okay, for the entire analysis of this edge we assumed the PHI
5877         // to be symbolic.  We now need to go back and purge all of the
5878         // entries for the scalars that use the symbolic expression.
5879         forgetMemoizedResults(SymbolicName);
5880         insertValueToMap(PN, Shifted);
5881         return Shifted;
5882       }
5883     }
5884   }
5885 
5886   // Remove the temporary PHI node SCEV that has been inserted while intending
5887   // to create an AddRecExpr for this PHI node. We can not keep this temporary
5888   // as it will prevent later (possibly simpler) SCEV expressions to be added
5889   // to the ValueExprMap.
5890   eraseValueFromMap(PN);
5891 
5892   return nullptr;
5893 }
5894 
5895 // Try to match a control flow sequence that branches out at BI and merges back
5896 // at Merge into a "C ? LHS : RHS" select pattern.  Return true on a successful
5897 // match.
5898 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
5899                           Value *&C, Value *&LHS, Value *&RHS) {
5900   C = BI->getCondition();
5901 
5902   BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
5903   BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
5904 
5905   if (!LeftEdge.isSingleEdge())
5906     return false;
5907 
5908   assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
5909 
5910   Use &LeftUse = Merge->getOperandUse(0);
5911   Use &RightUse = Merge->getOperandUse(1);
5912 
5913   if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
5914     LHS = LeftUse;
5915     RHS = RightUse;
5916     return true;
5917   }
5918 
5919   if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
5920     LHS = RightUse;
5921     RHS = LeftUse;
5922     return true;
5923   }
5924 
5925   return false;
5926 }
5927 
5928 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
5929   auto IsReachable =
5930       [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
5931   if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
5932     // Try to match
5933     //
5934     //  br %cond, label %left, label %right
5935     // left:
5936     //  br label %merge
5937     // right:
5938     //  br label %merge
5939     // merge:
5940     //  V = phi [ %x, %left ], [ %y, %right ]
5941     //
5942     // as "select %cond, %x, %y"
5943 
5944     BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
5945     assert(IDom && "At least the entry block should dominate PN");
5946 
5947     auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
5948     Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
5949 
5950     if (BI && BI->isConditional() &&
5951         BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
5952         properlyDominates(getSCEV(LHS), PN->getParent()) &&
5953         properlyDominates(getSCEV(RHS), PN->getParent()))
5954       return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
5955   }
5956 
5957   return nullptr;
5958 }
5959 
5960 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
5961   if (const SCEV *S = createAddRecFromPHI(PN))
5962     return S;
5963 
5964   if (Value *V = simplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC}))
5965     return getSCEV(V);
5966 
5967   if (const SCEV *S = createNodeFromSelectLikePHI(PN))
5968     return S;
5969 
5970   // If it's not a loop phi, we can't handle it yet.
5971   return getUnknown(PN);
5972 }
5973 
5974 bool SCEVMinMaxExprContains(const SCEV *Root, const SCEV *OperandToFind,
5975                             SCEVTypes RootKind) {
5976   struct FindClosure {
5977     const SCEV *OperandToFind;
5978     const SCEVTypes RootKind; // Must be a sequential min/max expression.
5979     const SCEVTypes NonSequentialRootKind; // Non-seq variant of RootKind.
5980 
5981     bool Found = false;
5982 
5983     bool canRecurseInto(SCEVTypes Kind) const {
5984       // We can only recurse into the SCEV expression of the same effective type
5985       // as the type of our root SCEV expression, and into zero-extensions.
5986       return RootKind == Kind || NonSequentialRootKind == Kind ||
5987              scZeroExtend == Kind;
5988     };
5989 
5990     FindClosure(const SCEV *OperandToFind, SCEVTypes RootKind)
5991         : OperandToFind(OperandToFind), RootKind(RootKind),
5992           NonSequentialRootKind(
5993               SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType(
5994                   RootKind)) {}
5995 
5996     bool follow(const SCEV *S) {
5997       Found = S == OperandToFind;
5998 
5999       return !isDone() && canRecurseInto(S->getSCEVType());
6000     }
6001 
6002     bool isDone() const { return Found; }
6003   };
6004 
6005   FindClosure FC(OperandToFind, RootKind);
6006   visitAll(Root, FC);
6007   return FC.Found;
6008 }
6009 
6010 std::optional<const SCEV *>
6011 ScalarEvolution::createNodeForSelectOrPHIInstWithICmpInstCond(Type *Ty,
6012                                                               ICmpInst *Cond,
6013                                                               Value *TrueVal,
6014                                                               Value *FalseVal) {
6015   // Try to match some simple smax or umax patterns.
6016   auto *ICI = Cond;
6017 
6018   Value *LHS = ICI->getOperand(0);
6019   Value *RHS = ICI->getOperand(1);
6020 
6021   switch (ICI->getPredicate()) {
6022   case ICmpInst::ICMP_SLT:
6023   case ICmpInst::ICMP_SLE:
6024   case ICmpInst::ICMP_ULT:
6025   case ICmpInst::ICMP_ULE:
6026     std::swap(LHS, RHS);
6027     [[fallthrough]];
6028   case ICmpInst::ICMP_SGT:
6029   case ICmpInst::ICMP_SGE:
6030   case ICmpInst::ICMP_UGT:
6031   case ICmpInst::ICMP_UGE:
6032     // a > b ? a+x : b+x  ->  max(a, b)+x
6033     // a > b ? b+x : a+x  ->  min(a, b)+x
6034     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(Ty)) {
6035       bool Signed = ICI->isSigned();
6036       const SCEV *LA = getSCEV(TrueVal);
6037       const SCEV *RA = getSCEV(FalseVal);
6038       const SCEV *LS = getSCEV(LHS);
6039       const SCEV *RS = getSCEV(RHS);
6040       if (LA->getType()->isPointerTy()) {
6041         // FIXME: Handle cases where LS/RS are pointers not equal to LA/RA.
6042         // Need to make sure we can't produce weird expressions involving
6043         // negated pointers.
6044         if (LA == LS && RA == RS)
6045           return Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS);
6046         if (LA == RS && RA == LS)
6047           return Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS);
6048       }
6049       auto CoerceOperand = [&](const SCEV *Op) -> const SCEV * {
6050         if (Op->getType()->isPointerTy()) {
6051           Op = getLosslessPtrToIntExpr(Op);
6052           if (isa<SCEVCouldNotCompute>(Op))
6053             return Op;
6054         }
6055         if (Signed)
6056           Op = getNoopOrSignExtend(Op, Ty);
6057         else
6058           Op = getNoopOrZeroExtend(Op, Ty);
6059         return Op;
6060       };
6061       LS = CoerceOperand(LS);
6062       RS = CoerceOperand(RS);
6063       if (isa<SCEVCouldNotCompute>(LS) || isa<SCEVCouldNotCompute>(RS))
6064         break;
6065       const SCEV *LDiff = getMinusSCEV(LA, LS);
6066       const SCEV *RDiff = getMinusSCEV(RA, RS);
6067       if (LDiff == RDiff)
6068         return getAddExpr(Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS),
6069                           LDiff);
6070       LDiff = getMinusSCEV(LA, RS);
6071       RDiff = getMinusSCEV(RA, LS);
6072       if (LDiff == RDiff)
6073         return getAddExpr(Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS),
6074                           LDiff);
6075     }
6076     break;
6077   case ICmpInst::ICMP_NE:
6078     // x != 0 ? x+y : C+y  ->  x == 0 ? C+y : x+y
6079     std::swap(TrueVal, FalseVal);
6080     [[fallthrough]];
6081   case ICmpInst::ICMP_EQ:
6082     // x == 0 ? C+y : x+y  ->  umax(x, C)+y   iff C u<= 1
6083     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(Ty) &&
6084         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
6085       const SCEV *X = getNoopOrZeroExtend(getSCEV(LHS), Ty);
6086       const SCEV *TrueValExpr = getSCEV(TrueVal);    // C+y
6087       const SCEV *FalseValExpr = getSCEV(FalseVal);  // x+y
6088       const SCEV *Y = getMinusSCEV(FalseValExpr, X); // y = (x+y)-x
6089       const SCEV *C = getMinusSCEV(TrueValExpr, Y);  // C = (C+y)-y
6090       if (isa<SCEVConstant>(C) && cast<SCEVConstant>(C)->getAPInt().ule(1))
6091         return getAddExpr(getUMaxExpr(X, C), Y);
6092     }
6093     // x == 0 ? 0 : umin    (..., x, ...)  ->  umin_seq(x, umin    (...))
6094     // x == 0 ? 0 : umin_seq(..., x, ...)  ->  umin_seq(x, umin_seq(...))
6095     // x == 0 ? 0 : umin    (..., umin_seq(..., x, ...), ...)
6096     //                    ->  umin_seq(x, umin (..., umin_seq(...), ...))
6097     if (isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero() &&
6098         isa<ConstantInt>(TrueVal) && cast<ConstantInt>(TrueVal)->isZero()) {
6099       const SCEV *X = getSCEV(LHS);
6100       while (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(X))
6101         X = ZExt->getOperand();
6102       if (getTypeSizeInBits(X->getType()) <= getTypeSizeInBits(Ty)) {
6103         const SCEV *FalseValExpr = getSCEV(FalseVal);
6104         if (SCEVMinMaxExprContains(FalseValExpr, X, scSequentialUMinExpr))
6105           return getUMinExpr(getNoopOrZeroExtend(X, Ty), FalseValExpr,
6106                              /*Sequential=*/true);
6107       }
6108     }
6109     break;
6110   default:
6111     break;
6112   }
6113 
6114   return std::nullopt;
6115 }
6116 
6117 static std::optional<const SCEV *>
6118 createNodeForSelectViaUMinSeq(ScalarEvolution *SE, const SCEV *CondExpr,
6119                               const SCEV *TrueExpr, const SCEV *FalseExpr) {
6120   assert(CondExpr->getType()->isIntegerTy(1) &&
6121          TrueExpr->getType() == FalseExpr->getType() &&
6122          TrueExpr->getType()->isIntegerTy(1) &&
6123          "Unexpected operands of a select.");
6124 
6125   // i1 cond ? i1 x : i1 C  -->  C + (i1  cond ? (i1 x - i1 C) : i1 0)
6126   //                        -->  C + (umin_seq  cond, x - C)
6127   //
6128   // i1 cond ? i1 C : i1 x  -->  C + (i1  cond ? i1 0 : (i1 x - i1 C))
6129   //                        -->  C + (i1 ~cond ? (i1 x - i1 C) : i1 0)
6130   //                        -->  C + (umin_seq ~cond, x - C)
6131 
6132   // FIXME: while we can't legally model the case where both of the hands
6133   // are fully variable, we only require that the *difference* is constant.
6134   if (!isa<SCEVConstant>(TrueExpr) && !isa<SCEVConstant>(FalseExpr))
6135     return std::nullopt;
6136 
6137   const SCEV *X, *C;
6138   if (isa<SCEVConstant>(TrueExpr)) {
6139     CondExpr = SE->getNotSCEV(CondExpr);
6140     X = FalseExpr;
6141     C = TrueExpr;
6142   } else {
6143     X = TrueExpr;
6144     C = FalseExpr;
6145   }
6146   return SE->getAddExpr(C, SE->getUMinExpr(CondExpr, SE->getMinusSCEV(X, C),
6147                                            /*Sequential=*/true));
6148 }
6149 
6150 static std::optional<const SCEV *>
6151 createNodeForSelectViaUMinSeq(ScalarEvolution *SE, Value *Cond, Value *TrueVal,
6152                               Value *FalseVal) {
6153   if (!isa<ConstantInt>(TrueVal) && !isa<ConstantInt>(FalseVal))
6154     return std::nullopt;
6155 
6156   const auto *SECond = SE->getSCEV(Cond);
6157   const auto *SETrue = SE->getSCEV(TrueVal);
6158   const auto *SEFalse = SE->getSCEV(FalseVal);
6159   return createNodeForSelectViaUMinSeq(SE, SECond, SETrue, SEFalse);
6160 }
6161 
6162 const SCEV *ScalarEvolution::createNodeForSelectOrPHIViaUMinSeq(
6163     Value *V, Value *Cond, Value *TrueVal, Value *FalseVal) {
6164   assert(Cond->getType()->isIntegerTy(1) && "Select condition is not an i1?");
6165   assert(TrueVal->getType() == FalseVal->getType() &&
6166          V->getType() == TrueVal->getType() &&
6167          "Types of select hands and of the result must match.");
6168 
6169   // For now, only deal with i1-typed `select`s.
6170   if (!V->getType()->isIntegerTy(1))
6171     return getUnknown(V);
6172 
6173   if (std::optional<const SCEV *> S =
6174           createNodeForSelectViaUMinSeq(this, Cond, TrueVal, FalseVal))
6175     return *S;
6176 
6177   return getUnknown(V);
6178 }
6179 
6180 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Value *V, Value *Cond,
6181                                                       Value *TrueVal,
6182                                                       Value *FalseVal) {
6183   // Handle "constant" branch or select. This can occur for instance when a
6184   // loop pass transforms an inner loop and moves on to process the outer loop.
6185   if (auto *CI = dyn_cast<ConstantInt>(Cond))
6186     return getSCEV(CI->isOne() ? TrueVal : FalseVal);
6187 
6188   if (auto *I = dyn_cast<Instruction>(V)) {
6189     if (auto *ICI = dyn_cast<ICmpInst>(Cond)) {
6190       if (std::optional<const SCEV *> S =
6191               createNodeForSelectOrPHIInstWithICmpInstCond(I->getType(), ICI,
6192                                                            TrueVal, FalseVal))
6193         return *S;
6194     }
6195   }
6196 
6197   return createNodeForSelectOrPHIViaUMinSeq(V, Cond, TrueVal, FalseVal);
6198 }
6199 
6200 /// Expand GEP instructions into add and multiply operations. This allows them
6201 /// to be analyzed by regular SCEV code.
6202 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
6203   assert(GEP->getSourceElementType()->isSized() &&
6204          "GEP source element type must be sized");
6205 
6206   SmallVector<const SCEV *, 4> IndexExprs;
6207   for (Value *Index : GEP->indices())
6208     IndexExprs.push_back(getSCEV(Index));
6209   return getGEPExpr(GEP, IndexExprs);
6210 }
6211 
6212 APInt ScalarEvolution::getConstantMultipleImpl(const SCEV *S) {
6213   uint64_t BitWidth = getTypeSizeInBits(S->getType());
6214   auto GetShiftedByZeros = [BitWidth](uint32_t TrailingZeros) {
6215     return TrailingZeros >= BitWidth
6216                ? APInt::getZero(BitWidth)
6217                : APInt::getOneBitSet(BitWidth, TrailingZeros);
6218   };
6219   auto GetGCDMultiple = [this](const SCEVNAryExpr *N) {
6220     // The result is GCD of all operands results.
6221     APInt Res = getConstantMultiple(N->getOperand(0));
6222     for (unsigned I = 1, E = N->getNumOperands(); I < E && Res != 1; ++I)
6223       Res = APIntOps::GreatestCommonDivisor(
6224           Res, getConstantMultiple(N->getOperand(I)));
6225     return Res;
6226   };
6227 
6228   switch (S->getSCEVType()) {
6229   case scConstant:
6230     return cast<SCEVConstant>(S)->getAPInt();
6231   case scPtrToInt:
6232     return getConstantMultiple(cast<SCEVPtrToIntExpr>(S)->getOperand());
6233   case scUDivExpr:
6234   case scVScale:
6235     return APInt(BitWidth, 1);
6236   case scTruncate: {
6237     // Only multiples that are a power of 2 will hold after truncation.
6238     const SCEVTruncateExpr *T = cast<SCEVTruncateExpr>(S);
6239     uint32_t TZ = getMinTrailingZeros(T->getOperand());
6240     return GetShiftedByZeros(TZ);
6241   }
6242   case scZeroExtend: {
6243     const SCEVZeroExtendExpr *Z = cast<SCEVZeroExtendExpr>(S);
6244     return getConstantMultiple(Z->getOperand()).zext(BitWidth);
6245   }
6246   case scSignExtend: {
6247     const SCEVSignExtendExpr *E = cast<SCEVSignExtendExpr>(S);
6248     return getConstantMultiple(E->getOperand()).sext(BitWidth);
6249   }
6250   case scMulExpr: {
6251     const SCEVMulExpr *M = cast<SCEVMulExpr>(S);
6252     if (M->hasNoUnsignedWrap()) {
6253       // The result is the product of all operand results.
6254       APInt Res = getConstantMultiple(M->getOperand(0));
6255       for (const SCEV *Operand : M->operands().drop_front())
6256         Res = Res * getConstantMultiple(Operand);
6257       return Res;
6258     }
6259 
6260     // If there are no wrap guarentees, find the trailing zeros, which is the
6261     // sum of trailing zeros for all its operands.
6262     uint32_t TZ = 0;
6263     for (const SCEV *Operand : M->operands())
6264       TZ += getMinTrailingZeros(Operand);
6265     return GetShiftedByZeros(TZ);
6266   }
6267   case scAddExpr:
6268   case scAddRecExpr: {
6269     const SCEVNAryExpr *N = cast<SCEVNAryExpr>(S);
6270     if (N->hasNoUnsignedWrap())
6271         return GetGCDMultiple(N);
6272     // Find the trailing bits, which is the minimum of its operands.
6273     uint32_t TZ = getMinTrailingZeros(N->getOperand(0));
6274     for (const SCEV *Operand : N->operands().drop_front())
6275       TZ = std::min(TZ, getMinTrailingZeros(Operand));
6276     return GetShiftedByZeros(TZ);
6277   }
6278   case scUMaxExpr:
6279   case scSMaxExpr:
6280   case scUMinExpr:
6281   case scSMinExpr:
6282   case scSequentialUMinExpr:
6283     return GetGCDMultiple(cast<SCEVNAryExpr>(S));
6284   case scUnknown: {
6285     // ask ValueTracking for known bits
6286     const SCEVUnknown *U = cast<SCEVUnknown>(S);
6287     unsigned Known =
6288         computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT)
6289             .countMinTrailingZeros();
6290     return GetShiftedByZeros(Known);
6291   }
6292   case scCouldNotCompute:
6293     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6294   }
6295   llvm_unreachable("Unknown SCEV kind!");
6296 }
6297 
6298 APInt ScalarEvolution::getConstantMultiple(const SCEV *S) {
6299   auto I = ConstantMultipleCache.find(S);
6300   if (I != ConstantMultipleCache.end())
6301     return I->second;
6302 
6303   APInt Result = getConstantMultipleImpl(S);
6304   auto InsertPair = ConstantMultipleCache.insert({S, Result});
6305   assert(InsertPair.second && "Should insert a new key");
6306   return InsertPair.first->second;
6307 }
6308 
6309 APInt ScalarEvolution::getNonZeroConstantMultiple(const SCEV *S) {
6310   APInt Multiple = getConstantMultiple(S);
6311   return Multiple == 0 ? APInt(Multiple.getBitWidth(), 1) : Multiple;
6312 }
6313 
6314 uint32_t ScalarEvolution::getMinTrailingZeros(const SCEV *S) {
6315   return std::min(getConstantMultiple(S).countTrailingZeros(),
6316                   (unsigned)getTypeSizeInBits(S->getType()));
6317 }
6318 
6319 /// Helper method to assign a range to V from metadata present in the IR.
6320 static std::optional<ConstantRange> GetRangeFromMetadata(Value *V) {
6321   if (Instruction *I = dyn_cast<Instruction>(V))
6322     if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
6323       return getConstantRangeFromMetadata(*MD);
6324 
6325   return std::nullopt;
6326 }
6327 
6328 void ScalarEvolution::setNoWrapFlags(SCEVAddRecExpr *AddRec,
6329                                      SCEV::NoWrapFlags Flags) {
6330   if (AddRec->getNoWrapFlags(Flags) != Flags) {
6331     AddRec->setNoWrapFlags(Flags);
6332     UnsignedRanges.erase(AddRec);
6333     SignedRanges.erase(AddRec);
6334     ConstantMultipleCache.erase(AddRec);
6335   }
6336 }
6337 
6338 ConstantRange ScalarEvolution::
6339 getRangeForUnknownRecurrence(const SCEVUnknown *U) {
6340   const DataLayout &DL = getDataLayout();
6341 
6342   unsigned BitWidth = getTypeSizeInBits(U->getType());
6343   const ConstantRange FullSet(BitWidth, /*isFullSet=*/true);
6344 
6345   // Match a simple recurrence of the form: <start, ShiftOp, Step>, and then
6346   // use information about the trip count to improve our available range.  Note
6347   // that the trip count independent cases are already handled by known bits.
6348   // WARNING: The definition of recurrence used here is subtly different than
6349   // the one used by AddRec (and thus most of this file).  Step is allowed to
6350   // be arbitrarily loop varying here, where AddRec allows only loop invariant
6351   // and other addrecs in the same loop (for non-affine addrecs).  The code
6352   // below intentionally handles the case where step is not loop invariant.
6353   auto *P = dyn_cast<PHINode>(U->getValue());
6354   if (!P)
6355     return FullSet;
6356 
6357   // Make sure that no Phi input comes from an unreachable block. Otherwise,
6358   // even the values that are not available in these blocks may come from them,
6359   // and this leads to false-positive recurrence test.
6360   for (auto *Pred : predecessors(P->getParent()))
6361     if (!DT.isReachableFromEntry(Pred))
6362       return FullSet;
6363 
6364   BinaryOperator *BO;
6365   Value *Start, *Step;
6366   if (!matchSimpleRecurrence(P, BO, Start, Step))
6367     return FullSet;
6368 
6369   // If we found a recurrence in reachable code, we must be in a loop. Note
6370   // that BO might be in some subloop of L, and that's completely okay.
6371   auto *L = LI.getLoopFor(P->getParent());
6372   assert(L && L->getHeader() == P->getParent());
6373   if (!L->contains(BO->getParent()))
6374     // NOTE: This bailout should be an assert instead.  However, asserting
6375     // the condition here exposes a case where LoopFusion is querying SCEV
6376     // with malformed loop information during the midst of the transform.
6377     // There doesn't appear to be an obvious fix, so for the moment bailout
6378     // until the caller issue can be fixed.  PR49566 tracks the bug.
6379     return FullSet;
6380 
6381   // TODO: Extend to other opcodes such as mul, and div
6382   switch (BO->getOpcode()) {
6383   default:
6384     return FullSet;
6385   case Instruction::AShr:
6386   case Instruction::LShr:
6387   case Instruction::Shl:
6388     break;
6389   };
6390 
6391   if (BO->getOperand(0) != P)
6392     // TODO: Handle the power function forms some day.
6393     return FullSet;
6394 
6395   unsigned TC = getSmallConstantMaxTripCount(L);
6396   if (!TC || TC >= BitWidth)
6397     return FullSet;
6398 
6399   auto KnownStart = computeKnownBits(Start, DL, 0, &AC, nullptr, &DT);
6400   auto KnownStep = computeKnownBits(Step, DL, 0, &AC, nullptr, &DT);
6401   assert(KnownStart.getBitWidth() == BitWidth &&
6402          KnownStep.getBitWidth() == BitWidth);
6403 
6404   // Compute total shift amount, being careful of overflow and bitwidths.
6405   auto MaxShiftAmt = KnownStep.getMaxValue();
6406   APInt TCAP(BitWidth, TC-1);
6407   bool Overflow = false;
6408   auto TotalShift = MaxShiftAmt.umul_ov(TCAP, Overflow);
6409   if (Overflow)
6410     return FullSet;
6411 
6412   switch (BO->getOpcode()) {
6413   default:
6414     llvm_unreachable("filtered out above");
6415   case Instruction::AShr: {
6416     // For each ashr, three cases:
6417     //   shift = 0 => unchanged value
6418     //   saturation => 0 or -1
6419     //   other => a value closer to zero (of the same sign)
6420     // Thus, the end value is closer to zero than the start.
6421     auto KnownEnd = KnownBits::ashr(KnownStart,
6422                                     KnownBits::makeConstant(TotalShift));
6423     if (KnownStart.isNonNegative())
6424       // Analogous to lshr (simply not yet canonicalized)
6425       return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
6426                                         KnownStart.getMaxValue() + 1);
6427     if (KnownStart.isNegative())
6428       // End >=u Start && End <=s Start
6429       return ConstantRange::getNonEmpty(KnownStart.getMinValue(),
6430                                         KnownEnd.getMaxValue() + 1);
6431     break;
6432   }
6433   case Instruction::LShr: {
6434     // For each lshr, three cases:
6435     //   shift = 0 => unchanged value
6436     //   saturation => 0
6437     //   other => a smaller positive number
6438     // Thus, the low end of the unsigned range is the last value produced.
6439     auto KnownEnd = KnownBits::lshr(KnownStart,
6440                                     KnownBits::makeConstant(TotalShift));
6441     return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
6442                                       KnownStart.getMaxValue() + 1);
6443   }
6444   case Instruction::Shl: {
6445     // Iff no bits are shifted out, value increases on every shift.
6446     auto KnownEnd = KnownBits::shl(KnownStart,
6447                                    KnownBits::makeConstant(TotalShift));
6448     if (TotalShift.ult(KnownStart.countMinLeadingZeros()))
6449       return ConstantRange(KnownStart.getMinValue(),
6450                            KnownEnd.getMaxValue() + 1);
6451     break;
6452   }
6453   };
6454   return FullSet;
6455 }
6456 
6457 const ConstantRange &
6458 ScalarEvolution::getRangeRefIter(const SCEV *S,
6459                                  ScalarEvolution::RangeSignHint SignHint) {
6460   DenseMap<const SCEV *, ConstantRange> &Cache =
6461       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
6462                                                        : SignedRanges;
6463   SmallVector<const SCEV *> WorkList;
6464   SmallPtrSet<const SCEV *, 8> Seen;
6465 
6466   // Add Expr to the worklist, if Expr is either an N-ary expression or a
6467   // SCEVUnknown PHI node.
6468   auto AddToWorklist = [&WorkList, &Seen, &Cache](const SCEV *Expr) {
6469     if (!Seen.insert(Expr).second)
6470       return;
6471     if (Cache.contains(Expr))
6472       return;
6473     switch (Expr->getSCEVType()) {
6474     case scUnknown:
6475       if (!isa<PHINode>(cast<SCEVUnknown>(Expr)->getValue()))
6476         break;
6477       [[fallthrough]];
6478     case scConstant:
6479     case scVScale:
6480     case scTruncate:
6481     case scZeroExtend:
6482     case scSignExtend:
6483     case scPtrToInt:
6484     case scAddExpr:
6485     case scMulExpr:
6486     case scUDivExpr:
6487     case scAddRecExpr:
6488     case scUMaxExpr:
6489     case scSMaxExpr:
6490     case scUMinExpr:
6491     case scSMinExpr:
6492     case scSequentialUMinExpr:
6493       WorkList.push_back(Expr);
6494       break;
6495     case scCouldNotCompute:
6496       llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6497     }
6498   };
6499   AddToWorklist(S);
6500 
6501   // Build worklist by queuing operands of N-ary expressions and phi nodes.
6502   for (unsigned I = 0; I != WorkList.size(); ++I) {
6503     const SCEV *P = WorkList[I];
6504     auto *UnknownS = dyn_cast<SCEVUnknown>(P);
6505     // If it is not a `SCEVUnknown`, just recurse into operands.
6506     if (!UnknownS) {
6507       for (const SCEV *Op : P->operands())
6508         AddToWorklist(Op);
6509       continue;
6510     }
6511     // `SCEVUnknown`'s require special treatment.
6512     if (const PHINode *P = dyn_cast<PHINode>(UnknownS->getValue())) {
6513       if (!PendingPhiRangesIter.insert(P).second)
6514         continue;
6515       for (auto &Op : reverse(P->operands()))
6516         AddToWorklist(getSCEV(Op));
6517     }
6518   }
6519 
6520   if (!WorkList.empty()) {
6521     // Use getRangeRef to compute ranges for items in the worklist in reverse
6522     // order. This will force ranges for earlier operands to be computed before
6523     // their users in most cases.
6524     for (const SCEV *P : reverse(drop_begin(WorkList))) {
6525       getRangeRef(P, SignHint);
6526 
6527       if (auto *UnknownS = dyn_cast<SCEVUnknown>(P))
6528         if (const PHINode *P = dyn_cast<PHINode>(UnknownS->getValue()))
6529           PendingPhiRangesIter.erase(P);
6530     }
6531   }
6532 
6533   return getRangeRef(S, SignHint, 0);
6534 }
6535 
6536 /// Determine the range for a particular SCEV.  If SignHint is
6537 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
6538 /// with a "cleaner" unsigned (resp. signed) representation.
6539 const ConstantRange &ScalarEvolution::getRangeRef(
6540     const SCEV *S, ScalarEvolution::RangeSignHint SignHint, unsigned Depth) {
6541   DenseMap<const SCEV *, ConstantRange> &Cache =
6542       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
6543                                                        : SignedRanges;
6544   ConstantRange::PreferredRangeType RangeType =
6545       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? ConstantRange::Unsigned
6546                                                        : ConstantRange::Signed;
6547 
6548   // See if we've computed this range already.
6549   DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
6550   if (I != Cache.end())
6551     return I->second;
6552 
6553   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
6554     return setRange(C, SignHint, ConstantRange(C->getAPInt()));
6555 
6556   // Switch to iteratively computing the range for S, if it is part of a deeply
6557   // nested expression.
6558   if (Depth > RangeIterThreshold)
6559     return getRangeRefIter(S, SignHint);
6560 
6561   unsigned BitWidth = getTypeSizeInBits(S->getType());
6562   ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
6563   using OBO = OverflowingBinaryOperator;
6564 
6565   // If the value has known zeros, the maximum value will have those known zeros
6566   // as well.
6567   if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
6568     APInt Multiple = getNonZeroConstantMultiple(S);
6569     APInt Remainder = APInt::getMaxValue(BitWidth).urem(Multiple);
6570     if (!Remainder.isZero())
6571       ConservativeResult =
6572           ConstantRange(APInt::getMinValue(BitWidth),
6573                         APInt::getMaxValue(BitWidth) - Remainder + 1);
6574   }
6575   else {
6576     uint32_t TZ = getMinTrailingZeros(S);
6577     if (TZ != 0) {
6578       ConservativeResult = ConstantRange(
6579           APInt::getSignedMinValue(BitWidth),
6580           APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
6581     }
6582   }
6583 
6584   switch (S->getSCEVType()) {
6585   case scConstant:
6586     llvm_unreachable("Already handled above.");
6587   case scVScale:
6588     return setRange(S, SignHint, getVScaleRange(&F, BitWidth));
6589   case scTruncate: {
6590     const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(S);
6591     ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint, Depth + 1);
6592     return setRange(
6593         Trunc, SignHint,
6594         ConservativeResult.intersectWith(X.truncate(BitWidth), RangeType));
6595   }
6596   case scZeroExtend: {
6597     const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(S);
6598     ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint, Depth + 1);
6599     return setRange(
6600         ZExt, SignHint,
6601         ConservativeResult.intersectWith(X.zeroExtend(BitWidth), RangeType));
6602   }
6603   case scSignExtend: {
6604     const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(S);
6605     ConstantRange X = getRangeRef(SExt->getOperand(), SignHint, Depth + 1);
6606     return setRange(
6607         SExt, SignHint,
6608         ConservativeResult.intersectWith(X.signExtend(BitWidth), RangeType));
6609   }
6610   case scPtrToInt: {
6611     const SCEVPtrToIntExpr *PtrToInt = cast<SCEVPtrToIntExpr>(S);
6612     ConstantRange X = getRangeRef(PtrToInt->getOperand(), SignHint, Depth + 1);
6613     return setRange(PtrToInt, SignHint, X);
6614   }
6615   case scAddExpr: {
6616     const SCEVAddExpr *Add = cast<SCEVAddExpr>(S);
6617     ConstantRange X = getRangeRef(Add->getOperand(0), SignHint, Depth + 1);
6618     unsigned WrapType = OBO::AnyWrap;
6619     if (Add->hasNoSignedWrap())
6620       WrapType |= OBO::NoSignedWrap;
6621     if (Add->hasNoUnsignedWrap())
6622       WrapType |= OBO::NoUnsignedWrap;
6623     for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
6624       X = X.addWithNoWrap(getRangeRef(Add->getOperand(i), SignHint, Depth + 1),
6625                           WrapType, RangeType);
6626     return setRange(Add, SignHint,
6627                     ConservativeResult.intersectWith(X, RangeType));
6628   }
6629   case scMulExpr: {
6630     const SCEVMulExpr *Mul = cast<SCEVMulExpr>(S);
6631     ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint, Depth + 1);
6632     for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
6633       X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint, Depth + 1));
6634     return setRange(Mul, SignHint,
6635                     ConservativeResult.intersectWith(X, RangeType));
6636   }
6637   case scUDivExpr: {
6638     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
6639     ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint, Depth + 1);
6640     ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint, Depth + 1);
6641     return setRange(UDiv, SignHint,
6642                     ConservativeResult.intersectWith(X.udiv(Y), RangeType));
6643   }
6644   case scAddRecExpr: {
6645     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(S);
6646     // If there's no unsigned wrap, the value will never be less than its
6647     // initial value.
6648     if (AddRec->hasNoUnsignedWrap()) {
6649       APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart());
6650       if (!UnsignedMinValue.isZero())
6651         ConservativeResult = ConservativeResult.intersectWith(
6652             ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType);
6653     }
6654 
6655     // If there's no signed wrap, and all the operands except initial value have
6656     // the same sign or zero, the value won't ever be:
6657     // 1: smaller than initial value if operands are non negative,
6658     // 2: bigger than initial value if operands are non positive.
6659     // For both cases, value can not cross signed min/max boundary.
6660     if (AddRec->hasNoSignedWrap()) {
6661       bool AllNonNeg = true;
6662       bool AllNonPos = true;
6663       for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) {
6664         if (!isKnownNonNegative(AddRec->getOperand(i)))
6665           AllNonNeg = false;
6666         if (!isKnownNonPositive(AddRec->getOperand(i)))
6667           AllNonPos = false;
6668       }
6669       if (AllNonNeg)
6670         ConservativeResult = ConservativeResult.intersectWith(
6671             ConstantRange::getNonEmpty(getSignedRangeMin(AddRec->getStart()),
6672                                        APInt::getSignedMinValue(BitWidth)),
6673             RangeType);
6674       else if (AllNonPos)
6675         ConservativeResult = ConservativeResult.intersectWith(
6676             ConstantRange::getNonEmpty(APInt::getSignedMinValue(BitWidth),
6677                                        getSignedRangeMax(AddRec->getStart()) +
6678                                            1),
6679             RangeType);
6680     }
6681 
6682     // TODO: non-affine addrec
6683     if (AddRec->isAffine()) {
6684       const SCEV *MaxBEScev =
6685           getConstantMaxBackedgeTakenCount(AddRec->getLoop());
6686       if (!isa<SCEVCouldNotCompute>(MaxBEScev)) {
6687         APInt MaxBECount = cast<SCEVConstant>(MaxBEScev)->getAPInt();
6688 
6689         // Adjust MaxBECount to the same bitwidth as AddRec. We can truncate if
6690         // MaxBECount's active bits are all <= AddRec's bit width.
6691         if (MaxBECount.getBitWidth() > BitWidth &&
6692             MaxBECount.getActiveBits() <= BitWidth)
6693           MaxBECount = MaxBECount.trunc(BitWidth);
6694         else if (MaxBECount.getBitWidth() < BitWidth)
6695           MaxBECount = MaxBECount.zext(BitWidth);
6696 
6697         if (MaxBECount.getBitWidth() == BitWidth) {
6698           auto RangeFromAffine = getRangeForAffineAR(
6699               AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount);
6700           ConservativeResult =
6701               ConservativeResult.intersectWith(RangeFromAffine, RangeType);
6702 
6703           auto RangeFromFactoring = getRangeViaFactoring(
6704               AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount);
6705           ConservativeResult =
6706               ConservativeResult.intersectWith(RangeFromFactoring, RangeType);
6707         }
6708       }
6709 
6710       // Now try symbolic BE count and more powerful methods.
6711       if (UseExpensiveRangeSharpening) {
6712         const SCEV *SymbolicMaxBECount =
6713             getSymbolicMaxBackedgeTakenCount(AddRec->getLoop());
6714         if (!isa<SCEVCouldNotCompute>(SymbolicMaxBECount) &&
6715             getTypeSizeInBits(MaxBEScev->getType()) <= BitWidth &&
6716             AddRec->hasNoSelfWrap()) {
6717           auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR(
6718               AddRec, SymbolicMaxBECount, BitWidth, SignHint);
6719           ConservativeResult =
6720               ConservativeResult.intersectWith(RangeFromAffineNew, RangeType);
6721         }
6722       }
6723     }
6724 
6725     return setRange(AddRec, SignHint, std::move(ConservativeResult));
6726   }
6727   case scUMaxExpr:
6728   case scSMaxExpr:
6729   case scUMinExpr:
6730   case scSMinExpr:
6731   case scSequentialUMinExpr: {
6732     Intrinsic::ID ID;
6733     switch (S->getSCEVType()) {
6734     case scUMaxExpr:
6735       ID = Intrinsic::umax;
6736       break;
6737     case scSMaxExpr:
6738       ID = Intrinsic::smax;
6739       break;
6740     case scUMinExpr:
6741     case scSequentialUMinExpr:
6742       ID = Intrinsic::umin;
6743       break;
6744     case scSMinExpr:
6745       ID = Intrinsic::smin;
6746       break;
6747     default:
6748       llvm_unreachable("Unknown SCEVMinMaxExpr/SCEVSequentialMinMaxExpr.");
6749     }
6750 
6751     const auto *NAry = cast<SCEVNAryExpr>(S);
6752     ConstantRange X = getRangeRef(NAry->getOperand(0), SignHint, Depth + 1);
6753     for (unsigned i = 1, e = NAry->getNumOperands(); i != e; ++i)
6754       X = X.intrinsic(
6755           ID, {X, getRangeRef(NAry->getOperand(i), SignHint, Depth + 1)});
6756     return setRange(S, SignHint,
6757                     ConservativeResult.intersectWith(X, RangeType));
6758   }
6759   case scUnknown: {
6760     const SCEVUnknown *U = cast<SCEVUnknown>(S);
6761     Value *V = U->getValue();
6762 
6763     // Check if the IR explicitly contains !range metadata.
6764     std::optional<ConstantRange> MDRange = GetRangeFromMetadata(V);
6765     if (MDRange)
6766       ConservativeResult =
6767           ConservativeResult.intersectWith(*MDRange, RangeType);
6768 
6769     // Use facts about recurrences in the underlying IR.  Note that add
6770     // recurrences are AddRecExprs and thus don't hit this path.  This
6771     // primarily handles shift recurrences.
6772     auto CR = getRangeForUnknownRecurrence(U);
6773     ConservativeResult = ConservativeResult.intersectWith(CR);
6774 
6775     // See if ValueTracking can give us a useful range.
6776     const DataLayout &DL = getDataLayout();
6777     KnownBits Known = computeKnownBits(V, DL, 0, &AC, nullptr, &DT);
6778     if (Known.getBitWidth() != BitWidth)
6779       Known = Known.zextOrTrunc(BitWidth);
6780 
6781     // ValueTracking may be able to compute a tighter result for the number of
6782     // sign bits than for the value of those sign bits.
6783     unsigned NS = ComputeNumSignBits(V, DL, 0, &AC, nullptr, &DT);
6784     if (U->getType()->isPointerTy()) {
6785       // If the pointer size is larger than the index size type, this can cause
6786       // NS to be larger than BitWidth. So compensate for this.
6787       unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType());
6788       int ptrIdxDiff = ptrSize - BitWidth;
6789       if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff)
6790         NS -= ptrIdxDiff;
6791     }
6792 
6793     if (NS > 1) {
6794       // If we know any of the sign bits, we know all of the sign bits.
6795       if (!Known.Zero.getHiBits(NS).isZero())
6796         Known.Zero.setHighBits(NS);
6797       if (!Known.One.getHiBits(NS).isZero())
6798         Known.One.setHighBits(NS);
6799     }
6800 
6801     if (Known.getMinValue() != Known.getMaxValue() + 1)
6802       ConservativeResult = ConservativeResult.intersectWith(
6803           ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1),
6804           RangeType);
6805     if (NS > 1)
6806       ConservativeResult = ConservativeResult.intersectWith(
6807           ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
6808                         APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1),
6809           RangeType);
6810 
6811     if (U->getType()->isPointerTy() && SignHint == HINT_RANGE_UNSIGNED) {
6812       // Strengthen the range if the underlying IR value is a
6813       // global/alloca/heap allocation using the size of the object.
6814       ObjectSizeOpts Opts;
6815       Opts.RoundToAlign = false;
6816       Opts.NullIsUnknownSize = true;
6817       uint64_t ObjSize;
6818       if ((isa<GlobalVariable>(V) || isa<AllocaInst>(V) ||
6819            isAllocationFn(V, &TLI)) &&
6820           getObjectSize(V, ObjSize, DL, &TLI, Opts) && ObjSize > 1) {
6821         // The highest address the object can start is ObjSize bytes before the
6822         // end (unsigned max value). If this value is not a multiple of the
6823         // alignment, the last possible start value is the next lowest multiple
6824         // of the alignment. Note: The computations below cannot overflow,
6825         // because if they would there's no possible start address for the
6826         // object.
6827         APInt MaxVal = APInt::getMaxValue(BitWidth) - APInt(BitWidth, ObjSize);
6828         uint64_t Align = U->getValue()->getPointerAlignment(DL).value();
6829         uint64_t Rem = MaxVal.urem(Align);
6830         MaxVal -= APInt(BitWidth, Rem);
6831         APInt MinVal = APInt::getZero(BitWidth);
6832         if (llvm::isKnownNonZero(V, DL))
6833           MinVal = Align;
6834         ConservativeResult = ConservativeResult.intersectWith(
6835             ConstantRange::getNonEmpty(MinVal, MaxVal + 1), RangeType);
6836       }
6837     }
6838 
6839     // A range of Phi is a subset of union of all ranges of its input.
6840     if (PHINode *Phi = dyn_cast<PHINode>(V)) {
6841       // Make sure that we do not run over cycled Phis.
6842       if (PendingPhiRanges.insert(Phi).second) {
6843         ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false);
6844 
6845         for (const auto &Op : Phi->operands()) {
6846           auto OpRange = getRangeRef(getSCEV(Op), SignHint, Depth + 1);
6847           RangeFromOps = RangeFromOps.unionWith(OpRange);
6848           // No point to continue if we already have a full set.
6849           if (RangeFromOps.isFullSet())
6850             break;
6851         }
6852         ConservativeResult =
6853             ConservativeResult.intersectWith(RangeFromOps, RangeType);
6854         bool Erased = PendingPhiRanges.erase(Phi);
6855         assert(Erased && "Failed to erase Phi properly?");
6856         (void)Erased;
6857       }
6858     }
6859 
6860     // vscale can't be equal to zero
6861     if (const auto *II = dyn_cast<IntrinsicInst>(V))
6862       if (II->getIntrinsicID() == Intrinsic::vscale) {
6863         ConstantRange Disallowed = APInt::getZero(BitWidth);
6864         ConservativeResult = ConservativeResult.difference(Disallowed);
6865       }
6866 
6867     return setRange(U, SignHint, std::move(ConservativeResult));
6868   }
6869   case scCouldNotCompute:
6870     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6871   }
6872 
6873   return setRange(S, SignHint, std::move(ConservativeResult));
6874 }
6875 
6876 // Given a StartRange, Step and MaxBECount for an expression compute a range of
6877 // values that the expression can take. Initially, the expression has a value
6878 // from StartRange and then is changed by Step up to MaxBECount times. Signed
6879 // argument defines if we treat Step as signed or unsigned.
6880 static ConstantRange getRangeForAffineARHelper(APInt Step,
6881                                                const ConstantRange &StartRange,
6882                                                const APInt &MaxBECount,
6883                                                bool Signed) {
6884   unsigned BitWidth = Step.getBitWidth();
6885   assert(BitWidth == StartRange.getBitWidth() &&
6886          BitWidth == MaxBECount.getBitWidth() && "mismatched bit widths");
6887   // If either Step or MaxBECount is 0, then the expression won't change, and we
6888   // just need to return the initial range.
6889   if (Step == 0 || MaxBECount == 0)
6890     return StartRange;
6891 
6892   // If we don't know anything about the initial value (i.e. StartRange is
6893   // FullRange), then we don't know anything about the final range either.
6894   // Return FullRange.
6895   if (StartRange.isFullSet())
6896     return ConstantRange::getFull(BitWidth);
6897 
6898   // If Step is signed and negative, then we use its absolute value, but we also
6899   // note that we're moving in the opposite direction.
6900   bool Descending = Signed && Step.isNegative();
6901 
6902   if (Signed)
6903     // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
6904     // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
6905     // This equations hold true due to the well-defined wrap-around behavior of
6906     // APInt.
6907     Step = Step.abs();
6908 
6909   // Check if Offset is more than full span of BitWidth. If it is, the
6910   // expression is guaranteed to overflow.
6911   if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
6912     return ConstantRange::getFull(BitWidth);
6913 
6914   // Offset is by how much the expression can change. Checks above guarantee no
6915   // overflow here.
6916   APInt Offset = Step * MaxBECount;
6917 
6918   // Minimum value of the final range will match the minimal value of StartRange
6919   // if the expression is increasing and will be decreased by Offset otherwise.
6920   // Maximum value of the final range will match the maximal value of StartRange
6921   // if the expression is decreasing and will be increased by Offset otherwise.
6922   APInt StartLower = StartRange.getLower();
6923   APInt StartUpper = StartRange.getUpper() - 1;
6924   APInt MovedBoundary = Descending ? (StartLower - std::move(Offset))
6925                                    : (StartUpper + std::move(Offset));
6926 
6927   // It's possible that the new minimum/maximum value will fall into the initial
6928   // range (due to wrap around). This means that the expression can take any
6929   // value in this bitwidth, and we have to return full range.
6930   if (StartRange.contains(MovedBoundary))
6931     return ConstantRange::getFull(BitWidth);
6932 
6933   APInt NewLower =
6934       Descending ? std::move(MovedBoundary) : std::move(StartLower);
6935   APInt NewUpper =
6936       Descending ? std::move(StartUpper) : std::move(MovedBoundary);
6937   NewUpper += 1;
6938 
6939   // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
6940   return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper));
6941 }
6942 
6943 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
6944                                                    const SCEV *Step,
6945                                                    const APInt &MaxBECount) {
6946   assert(getTypeSizeInBits(Start->getType()) ==
6947              getTypeSizeInBits(Step->getType()) &&
6948          getTypeSizeInBits(Start->getType()) == MaxBECount.getBitWidth() &&
6949          "mismatched bit widths");
6950 
6951   // First, consider step signed.
6952   ConstantRange StartSRange = getSignedRange(Start);
6953   ConstantRange StepSRange = getSignedRange(Step);
6954 
6955   // If Step can be both positive and negative, we need to find ranges for the
6956   // maximum absolute step values in both directions and union them.
6957   ConstantRange SR = getRangeForAffineARHelper(
6958       StepSRange.getSignedMin(), StartSRange, MaxBECount, /* Signed = */ true);
6959   SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(),
6960                                               StartSRange, MaxBECount,
6961                                               /* Signed = */ true));
6962 
6963   // Next, consider step unsigned.
6964   ConstantRange UR = getRangeForAffineARHelper(
6965       getUnsignedRangeMax(Step), getUnsignedRange(Start), MaxBECount,
6966       /* Signed = */ false);
6967 
6968   // Finally, intersect signed and unsigned ranges.
6969   return SR.intersectWith(UR, ConstantRange::Smallest);
6970 }
6971 
6972 ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR(
6973     const SCEVAddRecExpr *AddRec, const SCEV *MaxBECount, unsigned BitWidth,
6974     ScalarEvolution::RangeSignHint SignHint) {
6975   assert(AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n");
6976   assert(AddRec->hasNoSelfWrap() &&
6977          "This only works for non-self-wrapping AddRecs!");
6978   const bool IsSigned = SignHint == HINT_RANGE_SIGNED;
6979   const SCEV *Step = AddRec->getStepRecurrence(*this);
6980   // Only deal with constant step to save compile time.
6981   if (!isa<SCEVConstant>(Step))
6982     return ConstantRange::getFull(BitWidth);
6983   // Let's make sure that we can prove that we do not self-wrap during
6984   // MaxBECount iterations. We need this because MaxBECount is a maximum
6985   // iteration count estimate, and we might infer nw from some exit for which we
6986   // do not know max exit count (or any other side reasoning).
6987   // TODO: Turn into assert at some point.
6988   if (getTypeSizeInBits(MaxBECount->getType()) >
6989       getTypeSizeInBits(AddRec->getType()))
6990     return ConstantRange::getFull(BitWidth);
6991   MaxBECount = getNoopOrZeroExtend(MaxBECount, AddRec->getType());
6992   const SCEV *RangeWidth = getMinusOne(AddRec->getType());
6993   const SCEV *StepAbs = getUMinExpr(Step, getNegativeSCEV(Step));
6994   const SCEV *MaxItersWithoutWrap = getUDivExpr(RangeWidth, StepAbs);
6995   if (!isKnownPredicateViaConstantRanges(ICmpInst::ICMP_ULE, MaxBECount,
6996                                          MaxItersWithoutWrap))
6997     return ConstantRange::getFull(BitWidth);
6998 
6999   ICmpInst::Predicate LEPred =
7000       IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
7001   ICmpInst::Predicate GEPred =
7002       IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
7003   const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
7004 
7005   // We know that there is no self-wrap. Let's take Start and End values and
7006   // look at all intermediate values V1, V2, ..., Vn that IndVar takes during
7007   // the iteration. They either lie inside the range [Min(Start, End),
7008   // Max(Start, End)] or outside it:
7009   //
7010   // Case 1:   RangeMin    ...    Start V1 ... VN End ...           RangeMax;
7011   // Case 2:   RangeMin Vk ... V1 Start    ...    End Vn ... Vk + 1 RangeMax;
7012   //
7013   // No self wrap flag guarantees that the intermediate values cannot be BOTH
7014   // outside and inside the range [Min(Start, End), Max(Start, End)]. Using that
7015   // knowledge, let's try to prove that we are dealing with Case 1. It is so if
7016   // Start <= End and step is positive, or Start >= End and step is negative.
7017   const SCEV *Start = applyLoopGuards(AddRec->getStart(), AddRec->getLoop());
7018   ConstantRange StartRange = getRangeRef(Start, SignHint);
7019   ConstantRange EndRange = getRangeRef(End, SignHint);
7020   ConstantRange RangeBetween = StartRange.unionWith(EndRange);
7021   // If they already cover full iteration space, we will know nothing useful
7022   // even if we prove what we want to prove.
7023   if (RangeBetween.isFullSet())
7024     return RangeBetween;
7025   // Only deal with ranges that do not wrap (i.e. RangeMin < RangeMax).
7026   bool IsWrappedSet = IsSigned ? RangeBetween.isSignWrappedSet()
7027                                : RangeBetween.isWrappedSet();
7028   if (IsWrappedSet)
7029     return ConstantRange::getFull(BitWidth);
7030 
7031   if (isKnownPositive(Step) &&
7032       isKnownPredicateViaConstantRanges(LEPred, Start, End))
7033     return RangeBetween;
7034   if (isKnownNegative(Step) &&
7035            isKnownPredicateViaConstantRanges(GEPred, Start, End))
7036     return RangeBetween;
7037   return ConstantRange::getFull(BitWidth);
7038 }
7039 
7040 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
7041                                                     const SCEV *Step,
7042                                                     const APInt &MaxBECount) {
7043   //    RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
7044   // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
7045 
7046   unsigned BitWidth = MaxBECount.getBitWidth();
7047   assert(getTypeSizeInBits(Start->getType()) == BitWidth &&
7048          getTypeSizeInBits(Step->getType()) == BitWidth &&
7049          "mismatched bit widths");
7050 
7051   struct SelectPattern {
7052     Value *Condition = nullptr;
7053     APInt TrueValue;
7054     APInt FalseValue;
7055 
7056     explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
7057                            const SCEV *S) {
7058       std::optional<unsigned> CastOp;
7059       APInt Offset(BitWidth, 0);
7060 
7061       assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&
7062              "Should be!");
7063 
7064       // Peel off a constant offset:
7065       if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
7066         // In the future we could consider being smarter here and handle
7067         // {Start+Step,+,Step} too.
7068         if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
7069           return;
7070 
7071         Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
7072         S = SA->getOperand(1);
7073       }
7074 
7075       // Peel off a cast operation
7076       if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) {
7077         CastOp = SCast->getSCEVType();
7078         S = SCast->getOperand();
7079       }
7080 
7081       using namespace llvm::PatternMatch;
7082 
7083       auto *SU = dyn_cast<SCEVUnknown>(S);
7084       const APInt *TrueVal, *FalseVal;
7085       if (!SU ||
7086           !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
7087                                           m_APInt(FalseVal)))) {
7088         Condition = nullptr;
7089         return;
7090       }
7091 
7092       TrueValue = *TrueVal;
7093       FalseValue = *FalseVal;
7094 
7095       // Re-apply the cast we peeled off earlier
7096       if (CastOp)
7097         switch (*CastOp) {
7098         default:
7099           llvm_unreachable("Unknown SCEV cast type!");
7100 
7101         case scTruncate:
7102           TrueValue = TrueValue.trunc(BitWidth);
7103           FalseValue = FalseValue.trunc(BitWidth);
7104           break;
7105         case scZeroExtend:
7106           TrueValue = TrueValue.zext(BitWidth);
7107           FalseValue = FalseValue.zext(BitWidth);
7108           break;
7109         case scSignExtend:
7110           TrueValue = TrueValue.sext(BitWidth);
7111           FalseValue = FalseValue.sext(BitWidth);
7112           break;
7113         }
7114 
7115       // Re-apply the constant offset we peeled off earlier
7116       TrueValue += Offset;
7117       FalseValue += Offset;
7118     }
7119 
7120     bool isRecognized() { return Condition != nullptr; }
7121   };
7122 
7123   SelectPattern StartPattern(*this, BitWidth, Start);
7124   if (!StartPattern.isRecognized())
7125     return ConstantRange::getFull(BitWidth);
7126 
7127   SelectPattern StepPattern(*this, BitWidth, Step);
7128   if (!StepPattern.isRecognized())
7129     return ConstantRange::getFull(BitWidth);
7130 
7131   if (StartPattern.Condition != StepPattern.Condition) {
7132     // We don't handle this case today; but we could, by considering four
7133     // possibilities below instead of two. I'm not sure if there are cases where
7134     // that will help over what getRange already does, though.
7135     return ConstantRange::getFull(BitWidth);
7136   }
7137 
7138   // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
7139   // construct arbitrary general SCEV expressions here.  This function is called
7140   // from deep in the call stack, and calling getSCEV (on a sext instruction,
7141   // say) can end up caching a suboptimal value.
7142 
7143   // FIXME: without the explicit `this` receiver below, MSVC errors out with
7144   // C2352 and C2512 (otherwise it isn't needed).
7145 
7146   const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
7147   const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
7148   const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
7149   const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
7150 
7151   ConstantRange TrueRange =
7152       this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount);
7153   ConstantRange FalseRange =
7154       this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount);
7155 
7156   return TrueRange.unionWith(FalseRange);
7157 }
7158 
7159 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
7160   if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
7161   const BinaryOperator *BinOp = cast<BinaryOperator>(V);
7162 
7163   // Return early if there are no flags to propagate to the SCEV.
7164   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
7165   if (BinOp->hasNoUnsignedWrap())
7166     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
7167   if (BinOp->hasNoSignedWrap())
7168     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
7169   if (Flags == SCEV::FlagAnyWrap)
7170     return SCEV::FlagAnyWrap;
7171 
7172   return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
7173 }
7174 
7175 const Instruction *
7176 ScalarEvolution::getNonTrivialDefiningScopeBound(const SCEV *S) {
7177   if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S))
7178     return &*AddRec->getLoop()->getHeader()->begin();
7179   if (auto *U = dyn_cast<SCEVUnknown>(S))
7180     if (auto *I = dyn_cast<Instruction>(U->getValue()))
7181       return I;
7182   return nullptr;
7183 }
7184 
7185 const Instruction *
7186 ScalarEvolution::getDefiningScopeBound(ArrayRef<const SCEV *> Ops,
7187                                        bool &Precise) {
7188   Precise = true;
7189   // Do a bounded search of the def relation of the requested SCEVs.
7190   SmallSet<const SCEV *, 16> Visited;
7191   SmallVector<const SCEV *> Worklist;
7192   auto pushOp = [&](const SCEV *S) {
7193     if (!Visited.insert(S).second)
7194       return;
7195     // Threshold of 30 here is arbitrary.
7196     if (Visited.size() > 30) {
7197       Precise = false;
7198       return;
7199     }
7200     Worklist.push_back(S);
7201   };
7202 
7203   for (const auto *S : Ops)
7204     pushOp(S);
7205 
7206   const Instruction *Bound = nullptr;
7207   while (!Worklist.empty()) {
7208     auto *S = Worklist.pop_back_val();
7209     if (auto *DefI = getNonTrivialDefiningScopeBound(S)) {
7210       if (!Bound || DT.dominates(Bound, DefI))
7211         Bound = DefI;
7212     } else {
7213       for (const auto *Op : S->operands())
7214         pushOp(Op);
7215     }
7216   }
7217   return Bound ? Bound : &*F.getEntryBlock().begin();
7218 }
7219 
7220 const Instruction *
7221 ScalarEvolution::getDefiningScopeBound(ArrayRef<const SCEV *> Ops) {
7222   bool Discard;
7223   return getDefiningScopeBound(Ops, Discard);
7224 }
7225 
7226 bool ScalarEvolution::isGuaranteedToTransferExecutionTo(const Instruction *A,
7227                                                         const Instruction *B) {
7228   if (A->getParent() == B->getParent() &&
7229       isGuaranteedToTransferExecutionToSuccessor(A->getIterator(),
7230                                                  B->getIterator()))
7231     return true;
7232 
7233   auto *BLoop = LI.getLoopFor(B->getParent());
7234   if (BLoop && BLoop->getHeader() == B->getParent() &&
7235       BLoop->getLoopPreheader() == A->getParent() &&
7236       isGuaranteedToTransferExecutionToSuccessor(A->getIterator(),
7237                                                  A->getParent()->end()) &&
7238       isGuaranteedToTransferExecutionToSuccessor(B->getParent()->begin(),
7239                                                  B->getIterator()))
7240     return true;
7241   return false;
7242 }
7243 
7244 
7245 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
7246   // Only proceed if we can prove that I does not yield poison.
7247   if (!programUndefinedIfPoison(I))
7248     return false;
7249 
7250   // At this point we know that if I is executed, then it does not wrap
7251   // according to at least one of NSW or NUW. If I is not executed, then we do
7252   // not know if the calculation that I represents would wrap. Multiple
7253   // instructions can map to the same SCEV. If we apply NSW or NUW from I to
7254   // the SCEV, we must guarantee no wrapping for that SCEV also when it is
7255   // derived from other instructions that map to the same SCEV. We cannot make
7256   // that guarantee for cases where I is not executed. So we need to find a
7257   // upper bound on the defining scope for the SCEV, and prove that I is
7258   // executed every time we enter that scope.  When the bounding scope is a
7259   // loop (the common case), this is equivalent to proving I executes on every
7260   // iteration of that loop.
7261   SmallVector<const SCEV *> SCEVOps;
7262   for (const Use &Op : I->operands()) {
7263     // I could be an extractvalue from a call to an overflow intrinsic.
7264     // TODO: We can do better here in some cases.
7265     if (isSCEVable(Op->getType()))
7266       SCEVOps.push_back(getSCEV(Op));
7267   }
7268   auto *DefI = getDefiningScopeBound(SCEVOps);
7269   return isGuaranteedToTransferExecutionTo(DefI, I);
7270 }
7271 
7272 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
7273   // If we know that \c I can never be poison period, then that's enough.
7274   if (isSCEVExprNeverPoison(I))
7275     return true;
7276 
7277   // If the loop only has one exit, then we know that, if the loop is entered,
7278   // any instruction dominating that exit will be executed. If any such
7279   // instruction would result in UB, the addrec cannot be poison.
7280   //
7281   // This is basically the same reasoning as in isSCEVExprNeverPoison(), but
7282   // also handles uses outside the loop header (they just need to dominate the
7283   // single exit).
7284 
7285   auto *ExitingBB = L->getExitingBlock();
7286   if (!ExitingBB || !loopHasNoAbnormalExits(L))
7287     return false;
7288 
7289   SmallPtrSet<const Value *, 16> KnownPoison;
7290   SmallVector<const Instruction *, 8> Worklist;
7291 
7292   // We start by assuming \c I, the post-inc add recurrence, is poison.  Only
7293   // things that are known to be poison under that assumption go on the
7294   // Worklist.
7295   KnownPoison.insert(I);
7296   Worklist.push_back(I);
7297 
7298   while (!Worklist.empty()) {
7299     const Instruction *Poison = Worklist.pop_back_val();
7300 
7301     for (const Use &U : Poison->uses()) {
7302       const Instruction *PoisonUser = cast<Instruction>(U.getUser());
7303       if (mustTriggerUB(PoisonUser, KnownPoison) &&
7304           DT.dominates(PoisonUser->getParent(), ExitingBB))
7305         return true;
7306 
7307       if (propagatesPoison(U) && L->contains(PoisonUser))
7308         if (KnownPoison.insert(PoisonUser).second)
7309           Worklist.push_back(PoisonUser);
7310     }
7311   }
7312 
7313   return false;
7314 }
7315 
7316 ScalarEvolution::LoopProperties
7317 ScalarEvolution::getLoopProperties(const Loop *L) {
7318   using LoopProperties = ScalarEvolution::LoopProperties;
7319 
7320   auto Itr = LoopPropertiesCache.find(L);
7321   if (Itr == LoopPropertiesCache.end()) {
7322     auto HasSideEffects = [](Instruction *I) {
7323       if (auto *SI = dyn_cast<StoreInst>(I))
7324         return !SI->isSimple();
7325 
7326       return I->mayThrow() || I->mayWriteToMemory();
7327     };
7328 
7329     LoopProperties LP = {/* HasNoAbnormalExits */ true,
7330                          /*HasNoSideEffects*/ true};
7331 
7332     for (auto *BB : L->getBlocks())
7333       for (auto &I : *BB) {
7334         if (!isGuaranteedToTransferExecutionToSuccessor(&I))
7335           LP.HasNoAbnormalExits = false;
7336         if (HasSideEffects(&I))
7337           LP.HasNoSideEffects = false;
7338         if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
7339           break; // We're already as pessimistic as we can get.
7340       }
7341 
7342     auto InsertPair = LoopPropertiesCache.insert({L, LP});
7343     assert(InsertPair.second && "We just checked!");
7344     Itr = InsertPair.first;
7345   }
7346 
7347   return Itr->second;
7348 }
7349 
7350 bool ScalarEvolution::loopIsFiniteByAssumption(const Loop *L) {
7351   // A mustprogress loop without side effects must be finite.
7352   // TODO: The check used here is very conservative.  It's only *specific*
7353   // side effects which are well defined in infinite loops.
7354   return isFinite(L) || (isMustProgress(L) && loopHasNoSideEffects(L));
7355 }
7356 
7357 const SCEV *ScalarEvolution::createSCEVIter(Value *V) {
7358   // Worklist item with a Value and a bool indicating whether all operands have
7359   // been visited already.
7360   using PointerTy = PointerIntPair<Value *, 1, bool>;
7361   SmallVector<PointerTy> Stack;
7362 
7363   Stack.emplace_back(V, true);
7364   Stack.emplace_back(V, false);
7365   while (!Stack.empty()) {
7366     auto E = Stack.pop_back_val();
7367     Value *CurV = E.getPointer();
7368 
7369     if (getExistingSCEV(CurV))
7370       continue;
7371 
7372     SmallVector<Value *> Ops;
7373     const SCEV *CreatedSCEV = nullptr;
7374     // If all operands have been visited already, create the SCEV.
7375     if (E.getInt()) {
7376       CreatedSCEV = createSCEV(CurV);
7377     } else {
7378       // Otherwise get the operands we need to create SCEV's for before creating
7379       // the SCEV for CurV. If the SCEV for CurV can be constructed trivially,
7380       // just use it.
7381       CreatedSCEV = getOperandsToCreate(CurV, Ops);
7382     }
7383 
7384     if (CreatedSCEV) {
7385       insertValueToMap(CurV, CreatedSCEV);
7386     } else {
7387       // Queue CurV for SCEV creation, followed by its's operands which need to
7388       // be constructed first.
7389       Stack.emplace_back(CurV, true);
7390       for (Value *Op : Ops)
7391         Stack.emplace_back(Op, false);
7392     }
7393   }
7394 
7395   return getExistingSCEV(V);
7396 }
7397 
7398 const SCEV *
7399 ScalarEvolution::getOperandsToCreate(Value *V, SmallVectorImpl<Value *> &Ops) {
7400   if (!isSCEVable(V->getType()))
7401     return getUnknown(V);
7402 
7403   if (Instruction *I = dyn_cast<Instruction>(V)) {
7404     // Don't attempt to analyze instructions in blocks that aren't
7405     // reachable. Such instructions don't matter, and they aren't required
7406     // to obey basic rules for definitions dominating uses which this
7407     // analysis depends on.
7408     if (!DT.isReachableFromEntry(I->getParent()))
7409       return getUnknown(PoisonValue::get(V->getType()));
7410   } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
7411     return getConstant(CI);
7412   else if (isa<GlobalAlias>(V))
7413     return getUnknown(V);
7414   else if (!isa<ConstantExpr>(V))
7415     return getUnknown(V);
7416 
7417   Operator *U = cast<Operator>(V);
7418   if (auto BO =
7419           MatchBinaryOp(U, getDataLayout(), AC, DT, dyn_cast<Instruction>(V))) {
7420     bool IsConstArg = isa<ConstantInt>(BO->RHS);
7421     switch (BO->Opcode) {
7422     case Instruction::Add:
7423     case Instruction::Mul: {
7424       // For additions and multiplications, traverse add/mul chains for which we
7425       // can potentially create a single SCEV, to reduce the number of
7426       // get{Add,Mul}Expr calls.
7427       do {
7428         if (BO->Op) {
7429           if (BO->Op != V && getExistingSCEV(BO->Op)) {
7430             Ops.push_back(BO->Op);
7431             break;
7432           }
7433         }
7434         Ops.push_back(BO->RHS);
7435         auto NewBO = MatchBinaryOp(BO->LHS, getDataLayout(), AC, DT,
7436                                    dyn_cast<Instruction>(V));
7437         if (!NewBO ||
7438             (BO->Opcode == Instruction::Add &&
7439              (NewBO->Opcode != Instruction::Add &&
7440               NewBO->Opcode != Instruction::Sub)) ||
7441             (BO->Opcode == Instruction::Mul &&
7442              NewBO->Opcode != Instruction::Mul)) {
7443           Ops.push_back(BO->LHS);
7444           break;
7445         }
7446         // CreateSCEV calls getNoWrapFlagsFromUB, which under certain conditions
7447         // requires a SCEV for the LHS.
7448         if (BO->Op && (BO->IsNSW || BO->IsNUW)) {
7449           auto *I = dyn_cast<Instruction>(BO->Op);
7450           if (I && programUndefinedIfPoison(I)) {
7451             Ops.push_back(BO->LHS);
7452             break;
7453           }
7454         }
7455         BO = NewBO;
7456       } while (true);
7457       return nullptr;
7458     }
7459     case Instruction::Sub:
7460     case Instruction::UDiv:
7461     case Instruction::URem:
7462       break;
7463     case Instruction::AShr:
7464     case Instruction::Shl:
7465     case Instruction::Xor:
7466       if (!IsConstArg)
7467         return nullptr;
7468       break;
7469     case Instruction::And:
7470     case Instruction::Or:
7471       if (!IsConstArg && !BO->LHS->getType()->isIntegerTy(1))
7472         return nullptr;
7473       break;
7474     case Instruction::LShr:
7475       return getUnknown(V);
7476     default:
7477       llvm_unreachable("Unhandled binop");
7478       break;
7479     }
7480 
7481     Ops.push_back(BO->LHS);
7482     Ops.push_back(BO->RHS);
7483     return nullptr;
7484   }
7485 
7486   switch (U->getOpcode()) {
7487   case Instruction::Trunc:
7488   case Instruction::ZExt:
7489   case Instruction::SExt:
7490   case Instruction::PtrToInt:
7491     Ops.push_back(U->getOperand(0));
7492     return nullptr;
7493 
7494   case Instruction::BitCast:
7495     if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) {
7496       Ops.push_back(U->getOperand(0));
7497       return nullptr;
7498     }
7499     return getUnknown(V);
7500 
7501   case Instruction::SDiv:
7502   case Instruction::SRem:
7503     Ops.push_back(U->getOperand(0));
7504     Ops.push_back(U->getOperand(1));
7505     return nullptr;
7506 
7507   case Instruction::GetElementPtr:
7508     assert(cast<GEPOperator>(U)->getSourceElementType()->isSized() &&
7509            "GEP source element type must be sized");
7510     for (Value *Index : U->operands())
7511       Ops.push_back(Index);
7512     return nullptr;
7513 
7514   case Instruction::IntToPtr:
7515     return getUnknown(V);
7516 
7517   case Instruction::PHI:
7518     // Keep constructing SCEVs' for phis recursively for now.
7519     return nullptr;
7520 
7521   case Instruction::Select: {
7522     // Check if U is a select that can be simplified to a SCEVUnknown.
7523     auto CanSimplifyToUnknown = [this, U]() {
7524       if (U->getType()->isIntegerTy(1) || isa<ConstantInt>(U->getOperand(0)))
7525         return false;
7526 
7527       auto *ICI = dyn_cast<ICmpInst>(U->getOperand(0));
7528       if (!ICI)
7529         return false;
7530       Value *LHS = ICI->getOperand(0);
7531       Value *RHS = ICI->getOperand(1);
7532       if (ICI->getPredicate() == CmpInst::ICMP_EQ ||
7533           ICI->getPredicate() == CmpInst::ICMP_NE) {
7534         if (!(isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()))
7535           return true;
7536       } else if (getTypeSizeInBits(LHS->getType()) >
7537                  getTypeSizeInBits(U->getType()))
7538         return true;
7539       return false;
7540     };
7541     if (CanSimplifyToUnknown())
7542       return getUnknown(U);
7543 
7544     for (Value *Inc : U->operands())
7545       Ops.push_back(Inc);
7546     return nullptr;
7547     break;
7548   }
7549   case Instruction::Call:
7550   case Instruction::Invoke:
7551     if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand()) {
7552       Ops.push_back(RV);
7553       return nullptr;
7554     }
7555 
7556     if (auto *II = dyn_cast<IntrinsicInst>(U)) {
7557       switch (II->getIntrinsicID()) {
7558       case Intrinsic::abs:
7559         Ops.push_back(II->getArgOperand(0));
7560         return nullptr;
7561       case Intrinsic::umax:
7562       case Intrinsic::umin:
7563       case Intrinsic::smax:
7564       case Intrinsic::smin:
7565       case Intrinsic::usub_sat:
7566       case Intrinsic::uadd_sat:
7567         Ops.push_back(II->getArgOperand(0));
7568         Ops.push_back(II->getArgOperand(1));
7569         return nullptr;
7570       case Intrinsic::start_loop_iterations:
7571       case Intrinsic::annotation:
7572       case Intrinsic::ptr_annotation:
7573         Ops.push_back(II->getArgOperand(0));
7574         return nullptr;
7575       default:
7576         break;
7577       }
7578     }
7579     break;
7580   }
7581 
7582   return nullptr;
7583 }
7584 
7585 const SCEV *ScalarEvolution::createSCEV(Value *V) {
7586   if (!isSCEVable(V->getType()))
7587     return getUnknown(V);
7588 
7589   if (Instruction *I = dyn_cast<Instruction>(V)) {
7590     // Don't attempt to analyze instructions in blocks that aren't
7591     // reachable. Such instructions don't matter, and they aren't required
7592     // to obey basic rules for definitions dominating uses which this
7593     // analysis depends on.
7594     if (!DT.isReachableFromEntry(I->getParent()))
7595       return getUnknown(PoisonValue::get(V->getType()));
7596   } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
7597     return getConstant(CI);
7598   else if (isa<GlobalAlias>(V))
7599     return getUnknown(V);
7600   else if (!isa<ConstantExpr>(V))
7601     return getUnknown(V);
7602 
7603   const SCEV *LHS;
7604   const SCEV *RHS;
7605 
7606   Operator *U = cast<Operator>(V);
7607   if (auto BO =
7608           MatchBinaryOp(U, getDataLayout(), AC, DT, dyn_cast<Instruction>(V))) {
7609     switch (BO->Opcode) {
7610     case Instruction::Add: {
7611       // The simple thing to do would be to just call getSCEV on both operands
7612       // and call getAddExpr with the result. However if we're looking at a
7613       // bunch of things all added together, this can be quite inefficient,
7614       // because it leads to N-1 getAddExpr calls for N ultimate operands.
7615       // Instead, gather up all the operands and make a single getAddExpr call.
7616       // LLVM IR canonical form means we need only traverse the left operands.
7617       SmallVector<const SCEV *, 4> AddOps;
7618       do {
7619         if (BO->Op) {
7620           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
7621             AddOps.push_back(OpSCEV);
7622             break;
7623           }
7624 
7625           // If a NUW or NSW flag can be applied to the SCEV for this
7626           // addition, then compute the SCEV for this addition by itself
7627           // with a separate call to getAddExpr. We need to do that
7628           // instead of pushing the operands of the addition onto AddOps,
7629           // since the flags are only known to apply to this particular
7630           // addition - they may not apply to other additions that can be
7631           // formed with operands from AddOps.
7632           const SCEV *RHS = getSCEV(BO->RHS);
7633           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
7634           if (Flags != SCEV::FlagAnyWrap) {
7635             const SCEV *LHS = getSCEV(BO->LHS);
7636             if (BO->Opcode == Instruction::Sub)
7637               AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
7638             else
7639               AddOps.push_back(getAddExpr(LHS, RHS, Flags));
7640             break;
7641           }
7642         }
7643 
7644         if (BO->Opcode == Instruction::Sub)
7645           AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
7646         else
7647           AddOps.push_back(getSCEV(BO->RHS));
7648 
7649         auto NewBO = MatchBinaryOp(BO->LHS, getDataLayout(), AC, DT,
7650                                    dyn_cast<Instruction>(V));
7651         if (!NewBO || (NewBO->Opcode != Instruction::Add &&
7652                        NewBO->Opcode != Instruction::Sub)) {
7653           AddOps.push_back(getSCEV(BO->LHS));
7654           break;
7655         }
7656         BO = NewBO;
7657       } while (true);
7658 
7659       return getAddExpr(AddOps);
7660     }
7661 
7662     case Instruction::Mul: {
7663       SmallVector<const SCEV *, 4> MulOps;
7664       do {
7665         if (BO->Op) {
7666           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
7667             MulOps.push_back(OpSCEV);
7668             break;
7669           }
7670 
7671           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
7672           if (Flags != SCEV::FlagAnyWrap) {
7673             LHS = getSCEV(BO->LHS);
7674             RHS = getSCEV(BO->RHS);
7675             MulOps.push_back(getMulExpr(LHS, RHS, Flags));
7676             break;
7677           }
7678         }
7679 
7680         MulOps.push_back(getSCEV(BO->RHS));
7681         auto NewBO = MatchBinaryOp(BO->LHS, getDataLayout(), AC, DT,
7682                                    dyn_cast<Instruction>(V));
7683         if (!NewBO || NewBO->Opcode != Instruction::Mul) {
7684           MulOps.push_back(getSCEV(BO->LHS));
7685           break;
7686         }
7687         BO = NewBO;
7688       } while (true);
7689 
7690       return getMulExpr(MulOps);
7691     }
7692     case Instruction::UDiv:
7693       LHS = getSCEV(BO->LHS);
7694       RHS = getSCEV(BO->RHS);
7695       return getUDivExpr(LHS, RHS);
7696     case Instruction::URem:
7697       LHS = getSCEV(BO->LHS);
7698       RHS = getSCEV(BO->RHS);
7699       return getURemExpr(LHS, RHS);
7700     case Instruction::Sub: {
7701       SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
7702       if (BO->Op)
7703         Flags = getNoWrapFlagsFromUB(BO->Op);
7704       LHS = getSCEV(BO->LHS);
7705       RHS = getSCEV(BO->RHS);
7706       return getMinusSCEV(LHS, RHS, Flags);
7707     }
7708     case Instruction::And:
7709       // For an expression like x&255 that merely masks off the high bits,
7710       // use zext(trunc(x)) as the SCEV expression.
7711       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
7712         if (CI->isZero())
7713           return getSCEV(BO->RHS);
7714         if (CI->isMinusOne())
7715           return getSCEV(BO->LHS);
7716         const APInt &A = CI->getValue();
7717 
7718         // Instcombine's ShrinkDemandedConstant may strip bits out of
7719         // constants, obscuring what would otherwise be a low-bits mask.
7720         // Use computeKnownBits to compute what ShrinkDemandedConstant
7721         // knew about to reconstruct a low-bits mask value.
7722         unsigned LZ = A.countl_zero();
7723         unsigned TZ = A.countr_zero();
7724         unsigned BitWidth = A.getBitWidth();
7725         KnownBits Known(BitWidth);
7726         computeKnownBits(BO->LHS, Known, getDataLayout(),
7727                          0, &AC, nullptr, &DT);
7728 
7729         APInt EffectiveMask =
7730             APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
7731         if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
7732           const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
7733           const SCEV *LHS = getSCEV(BO->LHS);
7734           const SCEV *ShiftedLHS = nullptr;
7735           if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
7736             if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
7737               // For an expression like (x * 8) & 8, simplify the multiply.
7738               unsigned MulZeros = OpC->getAPInt().countr_zero();
7739               unsigned GCD = std::min(MulZeros, TZ);
7740               APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
7741               SmallVector<const SCEV*, 4> MulOps;
7742               MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD)));
7743               append_range(MulOps, LHSMul->operands().drop_front());
7744               auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
7745               ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
7746             }
7747           }
7748           if (!ShiftedLHS)
7749             ShiftedLHS = getUDivExpr(LHS, MulCount);
7750           return getMulExpr(
7751               getZeroExtendExpr(
7752                   getTruncateExpr(ShiftedLHS,
7753                       IntegerType::get(getContext(), BitWidth - LZ - TZ)),
7754                   BO->LHS->getType()),
7755               MulCount);
7756         }
7757       }
7758       // Binary `and` is a bit-wise `umin`.
7759       if (BO->LHS->getType()->isIntegerTy(1)) {
7760         LHS = getSCEV(BO->LHS);
7761         RHS = getSCEV(BO->RHS);
7762         return getUMinExpr(LHS, RHS);
7763       }
7764       break;
7765 
7766     case Instruction::Or:
7767       // Binary `or` is a bit-wise `umax`.
7768       if (BO->LHS->getType()->isIntegerTy(1)) {
7769         LHS = getSCEV(BO->LHS);
7770         RHS = getSCEV(BO->RHS);
7771         return getUMaxExpr(LHS, RHS);
7772       }
7773       break;
7774 
7775     case Instruction::Xor:
7776       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
7777         // If the RHS of xor is -1, then this is a not operation.
7778         if (CI->isMinusOne())
7779           return getNotSCEV(getSCEV(BO->LHS));
7780 
7781         // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
7782         // This is a variant of the check for xor with -1, and it handles
7783         // the case where instcombine has trimmed non-demanded bits out
7784         // of an xor with -1.
7785         if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
7786           if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
7787             if (LBO->getOpcode() == Instruction::And &&
7788                 LCI->getValue() == CI->getValue())
7789               if (const SCEVZeroExtendExpr *Z =
7790                       dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
7791                 Type *UTy = BO->LHS->getType();
7792                 const SCEV *Z0 = Z->getOperand();
7793                 Type *Z0Ty = Z0->getType();
7794                 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
7795 
7796                 // If C is a low-bits mask, the zero extend is serving to
7797                 // mask off the high bits. Complement the operand and
7798                 // re-apply the zext.
7799                 if (CI->getValue().isMask(Z0TySize))
7800                   return getZeroExtendExpr(getNotSCEV(Z0), UTy);
7801 
7802                 // If C is a single bit, it may be in the sign-bit position
7803                 // before the zero-extend. In this case, represent the xor
7804                 // using an add, which is equivalent, and re-apply the zext.
7805                 APInt Trunc = CI->getValue().trunc(Z0TySize);
7806                 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
7807                     Trunc.isSignMask())
7808                   return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
7809                                            UTy);
7810               }
7811       }
7812       break;
7813 
7814     case Instruction::Shl:
7815       // Turn shift left of a constant amount into a multiply.
7816       if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
7817         uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
7818 
7819         // If the shift count is not less than the bitwidth, the result of
7820         // the shift is undefined. Don't try to analyze it, because the
7821         // resolution chosen here may differ from the resolution chosen in
7822         // other parts of the compiler.
7823         if (SA->getValue().uge(BitWidth))
7824           break;
7825 
7826         // We can safely preserve the nuw flag in all cases. It's also safe to
7827         // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation
7828         // requires special handling. It can be preserved as long as we're not
7829         // left shifting by bitwidth - 1.
7830         auto Flags = SCEV::FlagAnyWrap;
7831         if (BO->Op) {
7832           auto MulFlags = getNoWrapFlagsFromUB(BO->Op);
7833           if ((MulFlags & SCEV::FlagNSW) &&
7834               ((MulFlags & SCEV::FlagNUW) || SA->getValue().ult(BitWidth - 1)))
7835             Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNSW);
7836           if (MulFlags & SCEV::FlagNUW)
7837             Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNUW);
7838         }
7839 
7840         ConstantInt *X = ConstantInt::get(
7841             getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
7842         return getMulExpr(getSCEV(BO->LHS), getConstant(X), Flags);
7843       }
7844       break;
7845 
7846     case Instruction::AShr:
7847       // AShr X, C, where C is a constant.
7848       ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
7849       if (!CI)
7850         break;
7851 
7852       Type *OuterTy = BO->LHS->getType();
7853       uint64_t BitWidth = getTypeSizeInBits(OuterTy);
7854       // If the shift count is not less than the bitwidth, the result of
7855       // the shift is undefined. Don't try to analyze it, because the
7856       // resolution chosen here may differ from the resolution chosen in
7857       // other parts of the compiler.
7858       if (CI->getValue().uge(BitWidth))
7859         break;
7860 
7861       if (CI->isZero())
7862         return getSCEV(BO->LHS); // shift by zero --> noop
7863 
7864       uint64_t AShrAmt = CI->getZExtValue();
7865       Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
7866 
7867       Operator *L = dyn_cast<Operator>(BO->LHS);
7868       const SCEV *AddTruncateExpr = nullptr;
7869       ConstantInt *ShlAmtCI = nullptr;
7870       const SCEV *AddConstant = nullptr;
7871 
7872       if (L && L->getOpcode() == Instruction::Add) {
7873         // X = Shl A, n
7874         // Y = Add X, c
7875         // Z = AShr Y, m
7876         // n, c and m are constants.
7877 
7878         Operator *LShift = dyn_cast<Operator>(L->getOperand(0));
7879         ConstantInt *AddOperandCI = dyn_cast<ConstantInt>(L->getOperand(1));
7880         if (LShift && LShift->getOpcode() == Instruction::Shl) {
7881           if (AddOperandCI) {
7882             const SCEV *ShlOp0SCEV = getSCEV(LShift->getOperand(0));
7883             ShlAmtCI = dyn_cast<ConstantInt>(LShift->getOperand(1));
7884             // since we truncate to TruncTy, the AddConstant should be of the
7885             // same type, so create a new Constant with type same as TruncTy.
7886             // Also, the Add constant should be shifted right by AShr amount.
7887             APInt AddOperand = AddOperandCI->getValue().ashr(AShrAmt);
7888             AddConstant = getConstant(AddOperand.trunc(BitWidth - AShrAmt));
7889             // we model the expression as sext(add(trunc(A), c << n)), since the
7890             // sext(trunc) part is already handled below, we create a
7891             // AddExpr(TruncExp) which will be used later.
7892             AddTruncateExpr = getTruncateExpr(ShlOp0SCEV, TruncTy);
7893           }
7894         }
7895       } else if (L && L->getOpcode() == Instruction::Shl) {
7896         // X = Shl A, n
7897         // Y = AShr X, m
7898         // Both n and m are constant.
7899 
7900         const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
7901         ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
7902         AddTruncateExpr = getTruncateExpr(ShlOp0SCEV, TruncTy);
7903       }
7904 
7905       if (AddTruncateExpr && ShlAmtCI) {
7906         // We can merge the two given cases into a single SCEV statement,
7907         // incase n = m, the mul expression will be 2^0, so it gets resolved to
7908         // a simpler case. The following code handles the two cases:
7909         //
7910         // 1) For a two-shift sext-inreg, i.e. n = m,
7911         //    use sext(trunc(x)) as the SCEV expression.
7912         //
7913         // 2) When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
7914         //    expression. We already checked that ShlAmt < BitWidth, so
7915         //    the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
7916         //    ShlAmt - AShrAmt < Amt.
7917         const APInt &ShlAmt = ShlAmtCI->getValue();
7918         if (ShlAmt.ult(BitWidth) && ShlAmt.uge(AShrAmt)) {
7919           APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
7920                                           ShlAmtCI->getZExtValue() - AShrAmt);
7921           const SCEV *CompositeExpr =
7922               getMulExpr(AddTruncateExpr, getConstant(Mul));
7923           if (L->getOpcode() != Instruction::Shl)
7924             CompositeExpr = getAddExpr(CompositeExpr, AddConstant);
7925 
7926           return getSignExtendExpr(CompositeExpr, OuterTy);
7927         }
7928       }
7929       break;
7930     }
7931   }
7932 
7933   switch (U->getOpcode()) {
7934   case Instruction::Trunc:
7935     return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
7936 
7937   case Instruction::ZExt:
7938     return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
7939 
7940   case Instruction::SExt:
7941     if (auto BO = MatchBinaryOp(U->getOperand(0), getDataLayout(), AC, DT,
7942                                 dyn_cast<Instruction>(V))) {
7943       // The NSW flag of a subtract does not always survive the conversion to
7944       // A + (-1)*B.  By pushing sign extension onto its operands we are much
7945       // more likely to preserve NSW and allow later AddRec optimisations.
7946       //
7947       // NOTE: This is effectively duplicating this logic from getSignExtend:
7948       //   sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
7949       // but by that point the NSW information has potentially been lost.
7950       if (BO->Opcode == Instruction::Sub && BO->IsNSW) {
7951         Type *Ty = U->getType();
7952         auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty);
7953         auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty);
7954         return getMinusSCEV(V1, V2, SCEV::FlagNSW);
7955       }
7956     }
7957     return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
7958 
7959   case Instruction::BitCast:
7960     // BitCasts are no-op casts so we just eliminate the cast.
7961     if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
7962       return getSCEV(U->getOperand(0));
7963     break;
7964 
7965   case Instruction::PtrToInt: {
7966     // Pointer to integer cast is straight-forward, so do model it.
7967     const SCEV *Op = getSCEV(U->getOperand(0));
7968     Type *DstIntTy = U->getType();
7969     // But only if effective SCEV (integer) type is wide enough to represent
7970     // all possible pointer values.
7971     const SCEV *IntOp = getPtrToIntExpr(Op, DstIntTy);
7972     if (isa<SCEVCouldNotCompute>(IntOp))
7973       return getUnknown(V);
7974     return IntOp;
7975   }
7976   case Instruction::IntToPtr:
7977     // Just don't deal with inttoptr casts.
7978     return getUnknown(V);
7979 
7980   case Instruction::SDiv:
7981     // If both operands are non-negative, this is just an udiv.
7982     if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
7983         isKnownNonNegative(getSCEV(U->getOperand(1))))
7984       return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
7985     break;
7986 
7987   case Instruction::SRem:
7988     // If both operands are non-negative, this is just an urem.
7989     if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
7990         isKnownNonNegative(getSCEV(U->getOperand(1))))
7991       return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
7992     break;
7993 
7994   case Instruction::GetElementPtr:
7995     return createNodeForGEP(cast<GEPOperator>(U));
7996 
7997   case Instruction::PHI:
7998     return createNodeForPHI(cast<PHINode>(U));
7999 
8000   case Instruction::Select:
8001     return createNodeForSelectOrPHI(U, U->getOperand(0), U->getOperand(1),
8002                                     U->getOperand(2));
8003 
8004   case Instruction::Call:
8005   case Instruction::Invoke:
8006     if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand())
8007       return getSCEV(RV);
8008 
8009     if (auto *II = dyn_cast<IntrinsicInst>(U)) {
8010       switch (II->getIntrinsicID()) {
8011       case Intrinsic::abs:
8012         return getAbsExpr(
8013             getSCEV(II->getArgOperand(0)),
8014             /*IsNSW=*/cast<ConstantInt>(II->getArgOperand(1))->isOne());
8015       case Intrinsic::umax:
8016         LHS = getSCEV(II->getArgOperand(0));
8017         RHS = getSCEV(II->getArgOperand(1));
8018         return getUMaxExpr(LHS, RHS);
8019       case Intrinsic::umin:
8020         LHS = getSCEV(II->getArgOperand(0));
8021         RHS = getSCEV(II->getArgOperand(1));
8022         return getUMinExpr(LHS, RHS);
8023       case Intrinsic::smax:
8024         LHS = getSCEV(II->getArgOperand(0));
8025         RHS = getSCEV(II->getArgOperand(1));
8026         return getSMaxExpr(LHS, RHS);
8027       case Intrinsic::smin:
8028         LHS = getSCEV(II->getArgOperand(0));
8029         RHS = getSCEV(II->getArgOperand(1));
8030         return getSMinExpr(LHS, RHS);
8031       case Intrinsic::usub_sat: {
8032         const SCEV *X = getSCEV(II->getArgOperand(0));
8033         const SCEV *Y = getSCEV(II->getArgOperand(1));
8034         const SCEV *ClampedY = getUMinExpr(X, Y);
8035         return getMinusSCEV(X, ClampedY, SCEV::FlagNUW);
8036       }
8037       case Intrinsic::uadd_sat: {
8038         const SCEV *X = getSCEV(II->getArgOperand(0));
8039         const SCEV *Y = getSCEV(II->getArgOperand(1));
8040         const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y));
8041         return getAddExpr(ClampedX, Y, SCEV::FlagNUW);
8042       }
8043       case Intrinsic::start_loop_iterations:
8044       case Intrinsic::annotation:
8045       case Intrinsic::ptr_annotation:
8046         // A start_loop_iterations or llvm.annotation or llvm.prt.annotation is
8047         // just eqivalent to the first operand for SCEV purposes.
8048         return getSCEV(II->getArgOperand(0));
8049       case Intrinsic::vscale:
8050         return getVScale(II->getType());
8051       default:
8052         break;
8053       }
8054     }
8055     break;
8056   }
8057 
8058   return getUnknown(V);
8059 }
8060 
8061 //===----------------------------------------------------------------------===//
8062 //                   Iteration Count Computation Code
8063 //
8064 
8065 const SCEV *ScalarEvolution::getTripCountFromExitCount(const SCEV *ExitCount) {
8066   if (isa<SCEVCouldNotCompute>(ExitCount))
8067     return getCouldNotCompute();
8068 
8069   auto *ExitCountType = ExitCount->getType();
8070   assert(ExitCountType->isIntegerTy());
8071   auto *EvalTy = Type::getIntNTy(ExitCountType->getContext(),
8072                                  1 + ExitCountType->getScalarSizeInBits());
8073   return getTripCountFromExitCount(ExitCount, EvalTy, nullptr);
8074 }
8075 
8076 const SCEV *ScalarEvolution::getTripCountFromExitCount(const SCEV *ExitCount,
8077                                                        Type *EvalTy,
8078                                                        const Loop *L) {
8079   if (isa<SCEVCouldNotCompute>(ExitCount))
8080     return getCouldNotCompute();
8081 
8082   unsigned ExitCountSize = getTypeSizeInBits(ExitCount->getType());
8083   unsigned EvalSize = EvalTy->getPrimitiveSizeInBits();
8084 
8085   auto CanAddOneWithoutOverflow = [&]() {
8086     ConstantRange ExitCountRange =
8087       getRangeRef(ExitCount, RangeSignHint::HINT_RANGE_UNSIGNED);
8088     if (!ExitCountRange.contains(APInt::getMaxValue(ExitCountSize)))
8089       return true;
8090 
8091     return L && isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, ExitCount,
8092                                          getMinusOne(ExitCount->getType()));
8093   };
8094 
8095   // If we need to zero extend the backedge count, check if we can add one to
8096   // it prior to zero extending without overflow. Provided this is safe, it
8097   // allows better simplification of the +1.
8098   if (EvalSize > ExitCountSize && CanAddOneWithoutOverflow())
8099     return getZeroExtendExpr(
8100         getAddExpr(ExitCount, getOne(ExitCount->getType())), EvalTy);
8101 
8102   // Get the total trip count from the count by adding 1.  This may wrap.
8103   return getAddExpr(getTruncateOrZeroExtend(ExitCount, EvalTy), getOne(EvalTy));
8104 }
8105 
8106 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
8107   if (!ExitCount)
8108     return 0;
8109 
8110   ConstantInt *ExitConst = ExitCount->getValue();
8111 
8112   // Guard against huge trip counts.
8113   if (ExitConst->getValue().getActiveBits() > 32)
8114     return 0;
8115 
8116   // In case of integer overflow, this returns 0, which is correct.
8117   return ((unsigned)ExitConst->getZExtValue()) + 1;
8118 }
8119 
8120 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) {
8121   auto *ExitCount = dyn_cast<SCEVConstant>(getBackedgeTakenCount(L, Exact));
8122   return getConstantTripCount(ExitCount);
8123 }
8124 
8125 unsigned
8126 ScalarEvolution::getSmallConstantTripCount(const Loop *L,
8127                                            const BasicBlock *ExitingBlock) {
8128   assert(ExitingBlock && "Must pass a non-null exiting block!");
8129   assert(L->isLoopExiting(ExitingBlock) &&
8130          "Exiting block must actually branch out of the loop!");
8131   const SCEVConstant *ExitCount =
8132       dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
8133   return getConstantTripCount(ExitCount);
8134 }
8135 
8136 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) {
8137   const auto *MaxExitCount =
8138       dyn_cast<SCEVConstant>(getConstantMaxBackedgeTakenCount(L));
8139   return getConstantTripCount(MaxExitCount);
8140 }
8141 
8142 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) {
8143   SmallVector<BasicBlock *, 8> ExitingBlocks;
8144   L->getExitingBlocks(ExitingBlocks);
8145 
8146   std::optional<unsigned> Res;
8147   for (auto *ExitingBB : ExitingBlocks) {
8148     unsigned Multiple = getSmallConstantTripMultiple(L, ExitingBB);
8149     if (!Res)
8150       Res = Multiple;
8151     Res = (unsigned)std::gcd(*Res, Multiple);
8152   }
8153   return Res.value_or(1);
8154 }
8155 
8156 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
8157                                                        const SCEV *ExitCount) {
8158   if (ExitCount == getCouldNotCompute())
8159     return 1;
8160 
8161   // Get the trip count
8162   const SCEV *TCExpr = getTripCountFromExitCount(applyLoopGuards(ExitCount, L));
8163 
8164   APInt Multiple = getNonZeroConstantMultiple(TCExpr);
8165   // If a trip multiple is huge (>=2^32), the trip count is still divisible by
8166   // the greatest power of 2 divisor less than 2^32.
8167   return Multiple.getActiveBits() > 32
8168              ? 1U << std::min((unsigned)31, Multiple.countTrailingZeros())
8169              : (unsigned)Multiple.zextOrTrunc(32).getZExtValue();
8170 }
8171 
8172 /// Returns the largest constant divisor of the trip count of this loop as a
8173 /// normal unsigned value, if possible. This means that the actual trip count is
8174 /// always a multiple of the returned value (don't forget the trip count could
8175 /// very well be zero as well!).
8176 ///
8177 /// Returns 1 if the trip count is unknown or not guaranteed to be the
8178 /// multiple of a constant (which is also the case if the trip count is simply
8179 /// constant, use getSmallConstantTripCount for that case), Will also return 1
8180 /// if the trip count is very large (>= 2^32).
8181 ///
8182 /// As explained in the comments for getSmallConstantTripCount, this assumes
8183 /// that control exits the loop via ExitingBlock.
8184 unsigned
8185 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
8186                                               const BasicBlock *ExitingBlock) {
8187   assert(ExitingBlock && "Must pass a non-null exiting block!");
8188   assert(L->isLoopExiting(ExitingBlock) &&
8189          "Exiting block must actually branch out of the loop!");
8190   const SCEV *ExitCount = getExitCount(L, ExitingBlock);
8191   return getSmallConstantTripMultiple(L, ExitCount);
8192 }
8193 
8194 const SCEV *ScalarEvolution::getExitCount(const Loop *L,
8195                                           const BasicBlock *ExitingBlock,
8196                                           ExitCountKind Kind) {
8197   switch (Kind) {
8198   case Exact:
8199     return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
8200   case SymbolicMaximum:
8201     return getBackedgeTakenInfo(L).getSymbolicMax(ExitingBlock, this);
8202   case ConstantMaximum:
8203     return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this);
8204   };
8205   llvm_unreachable("Invalid ExitCountKind!");
8206 }
8207 
8208 const SCEV *
8209 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
8210                                                  SmallVector<const SCEVPredicate *, 4> &Preds) {
8211   return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds);
8212 }
8213 
8214 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L,
8215                                                    ExitCountKind Kind) {
8216   switch (Kind) {
8217   case Exact:
8218     return getBackedgeTakenInfo(L).getExact(L, this);
8219   case ConstantMaximum:
8220     return getBackedgeTakenInfo(L).getConstantMax(this);
8221   case SymbolicMaximum:
8222     return getBackedgeTakenInfo(L).getSymbolicMax(L, this);
8223   };
8224   llvm_unreachable("Invalid ExitCountKind!");
8225 }
8226 
8227 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) {
8228   return getBackedgeTakenInfo(L).isConstantMaxOrZero(this);
8229 }
8230 
8231 /// Push PHI nodes in the header of the given loop onto the given Worklist.
8232 static void PushLoopPHIs(const Loop *L,
8233                          SmallVectorImpl<Instruction *> &Worklist,
8234                          SmallPtrSetImpl<Instruction *> &Visited) {
8235   BasicBlock *Header = L->getHeader();
8236 
8237   // Push all Loop-header PHIs onto the Worklist stack.
8238   for (PHINode &PN : Header->phis())
8239     if (Visited.insert(&PN).second)
8240       Worklist.push_back(&PN);
8241 }
8242 
8243 const ScalarEvolution::BackedgeTakenInfo &
8244 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
8245   auto &BTI = getBackedgeTakenInfo(L);
8246   if (BTI.hasFullInfo())
8247     return BTI;
8248 
8249   auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
8250 
8251   if (!Pair.second)
8252     return Pair.first->second;
8253 
8254   BackedgeTakenInfo Result =
8255       computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
8256 
8257   return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
8258 }
8259 
8260 ScalarEvolution::BackedgeTakenInfo &
8261 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
8262   // Initially insert an invalid entry for this loop. If the insertion
8263   // succeeds, proceed to actually compute a backedge-taken count and
8264   // update the value. The temporary CouldNotCompute value tells SCEV
8265   // code elsewhere that it shouldn't attempt to request a new
8266   // backedge-taken count, which could result in infinite recursion.
8267   std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
8268       BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
8269   if (!Pair.second)
8270     return Pair.first->second;
8271 
8272   // computeBackedgeTakenCount may allocate memory for its result. Inserting it
8273   // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
8274   // must be cleared in this scope.
8275   BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
8276 
8277   // Now that we know more about the trip count for this loop, forget any
8278   // existing SCEV values for PHI nodes in this loop since they are only
8279   // conservative estimates made without the benefit of trip count
8280   // information. This invalidation is not necessary for correctness, and is
8281   // only done to produce more precise results.
8282   if (Result.hasAnyInfo()) {
8283     // Invalidate any expression using an addrec in this loop.
8284     SmallVector<const SCEV *, 8> ToForget;
8285     auto LoopUsersIt = LoopUsers.find(L);
8286     if (LoopUsersIt != LoopUsers.end())
8287       append_range(ToForget, LoopUsersIt->second);
8288     forgetMemoizedResults(ToForget);
8289 
8290     // Invalidate constant-evolved loop header phis.
8291     for (PHINode &PN : L->getHeader()->phis())
8292       ConstantEvolutionLoopExitValue.erase(&PN);
8293   }
8294 
8295   // Re-lookup the insert position, since the call to
8296   // computeBackedgeTakenCount above could result in a
8297   // recusive call to getBackedgeTakenInfo (on a different
8298   // loop), which would invalidate the iterator computed
8299   // earlier.
8300   return BackedgeTakenCounts.find(L)->second = std::move(Result);
8301 }
8302 
8303 void ScalarEvolution::forgetAllLoops() {
8304   // This method is intended to forget all info about loops. It should
8305   // invalidate caches as if the following happened:
8306   // - The trip counts of all loops have changed arbitrarily
8307   // - Every llvm::Value has been updated in place to produce a different
8308   // result.
8309   BackedgeTakenCounts.clear();
8310   PredicatedBackedgeTakenCounts.clear();
8311   BECountUsers.clear();
8312   LoopPropertiesCache.clear();
8313   ConstantEvolutionLoopExitValue.clear();
8314   ValueExprMap.clear();
8315   ValuesAtScopes.clear();
8316   ValuesAtScopesUsers.clear();
8317   LoopDispositions.clear();
8318   BlockDispositions.clear();
8319   UnsignedRanges.clear();
8320   SignedRanges.clear();
8321   ExprValueMap.clear();
8322   HasRecMap.clear();
8323   ConstantMultipleCache.clear();
8324   PredicatedSCEVRewrites.clear();
8325   FoldCache.clear();
8326   FoldCacheUser.clear();
8327 }
8328 void ScalarEvolution::visitAndClearUsers(
8329     SmallVectorImpl<Instruction *> &Worklist,
8330     SmallPtrSetImpl<Instruction *> &Visited,
8331     SmallVectorImpl<const SCEV *> &ToForget) {
8332   while (!Worklist.empty()) {
8333     Instruction *I = Worklist.pop_back_val();
8334     if (!isSCEVable(I->getType()))
8335       continue;
8336 
8337     ValueExprMapType::iterator It =
8338         ValueExprMap.find_as(static_cast<Value *>(I));
8339     if (It != ValueExprMap.end()) {
8340       eraseValueFromMap(It->first);
8341       ToForget.push_back(It->second);
8342       if (PHINode *PN = dyn_cast<PHINode>(I))
8343         ConstantEvolutionLoopExitValue.erase(PN);
8344     }
8345 
8346     PushDefUseChildren(I, Worklist, Visited);
8347   }
8348 }
8349 
8350 void ScalarEvolution::forgetLoop(const Loop *L) {
8351   SmallVector<const Loop *, 16> LoopWorklist(1, L);
8352   SmallVector<Instruction *, 32> Worklist;
8353   SmallPtrSet<Instruction *, 16> Visited;
8354   SmallVector<const SCEV *, 16> ToForget;
8355 
8356   // Iterate over all the loops and sub-loops to drop SCEV information.
8357   while (!LoopWorklist.empty()) {
8358     auto *CurrL = LoopWorklist.pop_back_val();
8359 
8360     // Drop any stored trip count value.
8361     forgetBackedgeTakenCounts(CurrL, /* Predicated */ false);
8362     forgetBackedgeTakenCounts(CurrL, /* Predicated */ true);
8363 
8364     // Drop information about predicated SCEV rewrites for this loop.
8365     for (auto I = PredicatedSCEVRewrites.begin();
8366          I != PredicatedSCEVRewrites.end();) {
8367       std::pair<const SCEV *, const Loop *> Entry = I->first;
8368       if (Entry.second == CurrL)
8369         PredicatedSCEVRewrites.erase(I++);
8370       else
8371         ++I;
8372     }
8373 
8374     auto LoopUsersItr = LoopUsers.find(CurrL);
8375     if (LoopUsersItr != LoopUsers.end()) {
8376       ToForget.insert(ToForget.end(), LoopUsersItr->second.begin(),
8377                 LoopUsersItr->second.end());
8378     }
8379 
8380     // Drop information about expressions based on loop-header PHIs.
8381     PushLoopPHIs(CurrL, Worklist, Visited);
8382     visitAndClearUsers(Worklist, Visited, ToForget);
8383 
8384     LoopPropertiesCache.erase(CurrL);
8385     // Forget all contained loops too, to avoid dangling entries in the
8386     // ValuesAtScopes map.
8387     LoopWorklist.append(CurrL->begin(), CurrL->end());
8388   }
8389   forgetMemoizedResults(ToForget);
8390 }
8391 
8392 void ScalarEvolution::forgetTopmostLoop(const Loop *L) {
8393   forgetLoop(L->getOutermostLoop());
8394 }
8395 
8396 void ScalarEvolution::forgetValue(Value *V) {
8397   Instruction *I = dyn_cast<Instruction>(V);
8398   if (!I) return;
8399 
8400   // Drop information about expressions based on loop-header PHIs.
8401   SmallVector<Instruction *, 16> Worklist;
8402   SmallPtrSet<Instruction *, 8> Visited;
8403   SmallVector<const SCEV *, 8> ToForget;
8404   Worklist.push_back(I);
8405   Visited.insert(I);
8406   visitAndClearUsers(Worklist, Visited, ToForget);
8407 
8408   forgetMemoizedResults(ToForget);
8409 }
8410 
8411 void ScalarEvolution::forgetLcssaPhiWithNewPredecessor(Loop *L, PHINode *V) {
8412   if (!isSCEVable(V->getType()))
8413     return;
8414 
8415   // If SCEV looked through a trivial LCSSA phi node, we might have SCEV's
8416   // directly using a SCEVUnknown/SCEVAddRec defined in the loop. After an
8417   // extra predecessor is added, this is no longer valid. Find all Unknowns and
8418   // AddRecs defined in the loop and invalidate any SCEV's making use of them.
8419   if (const SCEV *S = getExistingSCEV(V)) {
8420     struct InvalidationRootCollector {
8421       Loop *L;
8422       SmallVector<const SCEV *, 8> Roots;
8423 
8424       InvalidationRootCollector(Loop *L) : L(L) {}
8425 
8426       bool follow(const SCEV *S) {
8427         if (auto *SU = dyn_cast<SCEVUnknown>(S)) {
8428           if (auto *I = dyn_cast<Instruction>(SU->getValue()))
8429             if (L->contains(I))
8430               Roots.push_back(S);
8431         } else if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
8432           if (L->contains(AddRec->getLoop()))
8433             Roots.push_back(S);
8434         }
8435         return true;
8436       }
8437       bool isDone() const { return false; }
8438     };
8439 
8440     InvalidationRootCollector C(L);
8441     visitAll(S, C);
8442     forgetMemoizedResults(C.Roots);
8443   }
8444 
8445   // Also perform the normal invalidation.
8446   forgetValue(V);
8447 }
8448 
8449 void ScalarEvolution::forgetLoopDispositions() { LoopDispositions.clear(); }
8450 
8451 void ScalarEvolution::forgetBlockAndLoopDispositions(Value *V) {
8452   // Unless a specific value is passed to invalidation, completely clear both
8453   // caches.
8454   if (!V) {
8455     BlockDispositions.clear();
8456     LoopDispositions.clear();
8457     return;
8458   }
8459 
8460   if (!isSCEVable(V->getType()))
8461     return;
8462 
8463   const SCEV *S = getExistingSCEV(V);
8464   if (!S)
8465     return;
8466 
8467   // Invalidate the block and loop dispositions cached for S. Dispositions of
8468   // S's users may change if S's disposition changes (i.e. a user may change to
8469   // loop-invariant, if S changes to loop invariant), so also invalidate
8470   // dispositions of S's users recursively.
8471   SmallVector<const SCEV *, 8> Worklist = {S};
8472   SmallPtrSet<const SCEV *, 8> Seen = {S};
8473   while (!Worklist.empty()) {
8474     const SCEV *Curr = Worklist.pop_back_val();
8475     bool LoopDispoRemoved = LoopDispositions.erase(Curr);
8476     bool BlockDispoRemoved = BlockDispositions.erase(Curr);
8477     if (!LoopDispoRemoved && !BlockDispoRemoved)
8478       continue;
8479     auto Users = SCEVUsers.find(Curr);
8480     if (Users != SCEVUsers.end())
8481       for (const auto *User : Users->second)
8482         if (Seen.insert(User).second)
8483           Worklist.push_back(User);
8484   }
8485 }
8486 
8487 /// Get the exact loop backedge taken count considering all loop exits. A
8488 /// computable result can only be returned for loops with all exiting blocks
8489 /// dominating the latch. howFarToZero assumes that the limit of each loop test
8490 /// is never skipped. This is a valid assumption as long as the loop exits via
8491 /// that test. For precise results, it is the caller's responsibility to specify
8492 /// the relevant loop exiting block using getExact(ExitingBlock, SE).
8493 const SCEV *
8494 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE,
8495                                              SmallVector<const SCEVPredicate *, 4> *Preds) const {
8496   // If any exits were not computable, the loop is not computable.
8497   if (!isComplete() || ExitNotTaken.empty())
8498     return SE->getCouldNotCompute();
8499 
8500   const BasicBlock *Latch = L->getLoopLatch();
8501   // All exiting blocks we have collected must dominate the only backedge.
8502   if (!Latch)
8503     return SE->getCouldNotCompute();
8504 
8505   // All exiting blocks we have gathered dominate loop's latch, so exact trip
8506   // count is simply a minimum out of all these calculated exit counts.
8507   SmallVector<const SCEV *, 2> Ops;
8508   for (const auto &ENT : ExitNotTaken) {
8509     const SCEV *BECount = ENT.ExactNotTaken;
8510     assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!");
8511     assert(SE->DT.dominates(ENT.ExitingBlock, Latch) &&
8512            "We should only have known counts for exiting blocks that dominate "
8513            "latch!");
8514 
8515     Ops.push_back(BECount);
8516 
8517     if (Preds)
8518       for (const auto *P : ENT.Predicates)
8519         Preds->push_back(P);
8520 
8521     assert((Preds || ENT.hasAlwaysTruePredicate()) &&
8522            "Predicate should be always true!");
8523   }
8524 
8525   // If an earlier exit exits on the first iteration (exit count zero), then
8526   // a later poison exit count should not propagate into the result. This are
8527   // exactly the semantics provided by umin_seq.
8528   return SE->getUMinFromMismatchedTypes(Ops, /* Sequential */ true);
8529 }
8530 
8531 /// Get the exact not taken count for this loop exit.
8532 const SCEV *
8533 ScalarEvolution::BackedgeTakenInfo::getExact(const BasicBlock *ExitingBlock,
8534                                              ScalarEvolution *SE) const {
8535   for (const auto &ENT : ExitNotTaken)
8536     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
8537       return ENT.ExactNotTaken;
8538 
8539   return SE->getCouldNotCompute();
8540 }
8541 
8542 const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax(
8543     const BasicBlock *ExitingBlock, ScalarEvolution *SE) const {
8544   for (const auto &ENT : ExitNotTaken)
8545     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
8546       return ENT.ConstantMaxNotTaken;
8547 
8548   return SE->getCouldNotCompute();
8549 }
8550 
8551 const SCEV *ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(
8552     const BasicBlock *ExitingBlock, ScalarEvolution *SE) const {
8553   for (const auto &ENT : ExitNotTaken)
8554     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
8555       return ENT.SymbolicMaxNotTaken;
8556 
8557   return SE->getCouldNotCompute();
8558 }
8559 
8560 /// getConstantMax - Get the constant max backedge taken count for the loop.
8561 const SCEV *
8562 ScalarEvolution::BackedgeTakenInfo::getConstantMax(ScalarEvolution *SE) const {
8563   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
8564     return !ENT.hasAlwaysTruePredicate();
8565   };
8566 
8567   if (!getConstantMax() || any_of(ExitNotTaken, PredicateNotAlwaysTrue))
8568     return SE->getCouldNotCompute();
8569 
8570   assert((isa<SCEVCouldNotCompute>(getConstantMax()) ||
8571           isa<SCEVConstant>(getConstantMax())) &&
8572          "No point in having a non-constant max backedge taken count!");
8573   return getConstantMax();
8574 }
8575 
8576 const SCEV *
8577 ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(const Loop *L,
8578                                                    ScalarEvolution *SE) {
8579   if (!SymbolicMax)
8580     SymbolicMax = SE->computeSymbolicMaxBackedgeTakenCount(L);
8581   return SymbolicMax;
8582 }
8583 
8584 bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero(
8585     ScalarEvolution *SE) const {
8586   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
8587     return !ENT.hasAlwaysTruePredicate();
8588   };
8589   return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
8590 }
8591 
8592 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E)
8593     : ExitLimit(E, E, E, false, std::nullopt) {}
8594 
8595 ScalarEvolution::ExitLimit::ExitLimit(
8596     const SCEV *E, const SCEV *ConstantMaxNotTaken,
8597     const SCEV *SymbolicMaxNotTaken, bool MaxOrZero,
8598     ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList)
8599     : ExactNotTaken(E), ConstantMaxNotTaken(ConstantMaxNotTaken),
8600       SymbolicMaxNotTaken(SymbolicMaxNotTaken), MaxOrZero(MaxOrZero) {
8601   // If we prove the max count is zero, so is the symbolic bound.  This happens
8602   // in practice due to differences in a) how context sensitive we've chosen
8603   // to be and b) how we reason about bounds implied by UB.
8604   if (ConstantMaxNotTaken->isZero()) {
8605     this->ExactNotTaken = E = ConstantMaxNotTaken;
8606     this->SymbolicMaxNotTaken = SymbolicMaxNotTaken = ConstantMaxNotTaken;
8607   }
8608 
8609   assert((isa<SCEVCouldNotCompute>(ExactNotTaken) ||
8610           !isa<SCEVCouldNotCompute>(ConstantMaxNotTaken)) &&
8611          "Exact is not allowed to be less precise than Constant Max");
8612   assert((isa<SCEVCouldNotCompute>(ExactNotTaken) ||
8613           !isa<SCEVCouldNotCompute>(SymbolicMaxNotTaken)) &&
8614          "Exact is not allowed to be less precise than Symbolic Max");
8615   assert((isa<SCEVCouldNotCompute>(SymbolicMaxNotTaken) ||
8616           !isa<SCEVCouldNotCompute>(ConstantMaxNotTaken)) &&
8617          "Symbolic Max is not allowed to be less precise than Constant Max");
8618   assert((isa<SCEVCouldNotCompute>(ConstantMaxNotTaken) ||
8619           isa<SCEVConstant>(ConstantMaxNotTaken)) &&
8620          "No point in having a non-constant max backedge taken count!");
8621   for (const auto *PredSet : PredSetList)
8622     for (const auto *P : *PredSet)
8623       addPredicate(P);
8624   assert((isa<SCEVCouldNotCompute>(E) || !E->getType()->isPointerTy()) &&
8625          "Backedge count should be int");
8626   assert((isa<SCEVCouldNotCompute>(ConstantMaxNotTaken) ||
8627           !ConstantMaxNotTaken->getType()->isPointerTy()) &&
8628          "Max backedge count should be int");
8629 }
8630 
8631 ScalarEvolution::ExitLimit::ExitLimit(
8632     const SCEV *E, const SCEV *ConstantMaxNotTaken,
8633     const SCEV *SymbolicMaxNotTaken, bool MaxOrZero,
8634     const SmallPtrSetImpl<const SCEVPredicate *> &PredSet)
8635     : ExitLimit(E, ConstantMaxNotTaken, SymbolicMaxNotTaken, MaxOrZero,
8636                 { &PredSet }) {}
8637 
8638 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
8639 /// computable exit into a persistent ExitNotTakenInfo array.
8640 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
8641     ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> ExitCounts,
8642     bool IsComplete, const SCEV *ConstantMax, bool MaxOrZero)
8643     : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) {
8644   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
8645 
8646   ExitNotTaken.reserve(ExitCounts.size());
8647   std::transform(ExitCounts.begin(), ExitCounts.end(),
8648                  std::back_inserter(ExitNotTaken),
8649                  [&](const EdgeExitInfo &EEI) {
8650         BasicBlock *ExitBB = EEI.first;
8651         const ExitLimit &EL = EEI.second;
8652         return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken,
8653                                 EL.ConstantMaxNotTaken, EL.SymbolicMaxNotTaken,
8654                                 EL.Predicates);
8655   });
8656   assert((isa<SCEVCouldNotCompute>(ConstantMax) ||
8657           isa<SCEVConstant>(ConstantMax)) &&
8658          "No point in having a non-constant max backedge taken count!");
8659 }
8660 
8661 /// Compute the number of times the backedge of the specified loop will execute.
8662 ScalarEvolution::BackedgeTakenInfo
8663 ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
8664                                            bool AllowPredicates) {
8665   SmallVector<BasicBlock *, 8> ExitingBlocks;
8666   L->getExitingBlocks(ExitingBlocks);
8667 
8668   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
8669 
8670   SmallVector<EdgeExitInfo, 4> ExitCounts;
8671   bool CouldComputeBECount = true;
8672   BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
8673   const SCEV *MustExitMaxBECount = nullptr;
8674   const SCEV *MayExitMaxBECount = nullptr;
8675   bool MustExitMaxOrZero = false;
8676 
8677   // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
8678   // and compute maxBECount.
8679   // Do a union of all the predicates here.
8680   for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
8681     BasicBlock *ExitBB = ExitingBlocks[i];
8682 
8683     // We canonicalize untaken exits to br (constant), ignore them so that
8684     // proving an exit untaken doesn't negatively impact our ability to reason
8685     // about the loop as whole.
8686     if (auto *BI = dyn_cast<BranchInst>(ExitBB->getTerminator()))
8687       if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
8688         bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
8689         if (ExitIfTrue == CI->isZero())
8690           continue;
8691       }
8692 
8693     ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
8694 
8695     assert((AllowPredicates || EL.Predicates.empty()) &&
8696            "Predicated exit limit when predicates are not allowed!");
8697 
8698     // 1. For each exit that can be computed, add an entry to ExitCounts.
8699     // CouldComputeBECount is true only if all exits can be computed.
8700     if (EL.ExactNotTaken != getCouldNotCompute())
8701       ++NumExitCountsComputed;
8702     else
8703       // We couldn't compute an exact value for this exit, so
8704       // we won't be able to compute an exact value for the loop.
8705       CouldComputeBECount = false;
8706     // Remember exit count if either exact or symbolic is known. Because
8707     // Exact always implies symbolic, only check symbolic.
8708     if (EL.SymbolicMaxNotTaken != getCouldNotCompute())
8709       ExitCounts.emplace_back(ExitBB, EL);
8710     else {
8711       assert(EL.ExactNotTaken == getCouldNotCompute() &&
8712              "Exact is known but symbolic isn't?");
8713       ++NumExitCountsNotComputed;
8714     }
8715 
8716     // 2. Derive the loop's MaxBECount from each exit's max number of
8717     // non-exiting iterations. Partition the loop exits into two kinds:
8718     // LoopMustExits and LoopMayExits.
8719     //
8720     // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
8721     // is a LoopMayExit.  If any computable LoopMustExit is found, then
8722     // MaxBECount is the minimum EL.ConstantMaxNotTaken of computable
8723     // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
8724     // EL.ConstantMaxNotTaken, where CouldNotCompute is considered greater than
8725     // any
8726     // computable EL.ConstantMaxNotTaken.
8727     if (EL.ConstantMaxNotTaken != getCouldNotCompute() && Latch &&
8728         DT.dominates(ExitBB, Latch)) {
8729       if (!MustExitMaxBECount) {
8730         MustExitMaxBECount = EL.ConstantMaxNotTaken;
8731         MustExitMaxOrZero = EL.MaxOrZero;
8732       } else {
8733         MustExitMaxBECount = getUMinFromMismatchedTypes(MustExitMaxBECount,
8734                                                         EL.ConstantMaxNotTaken);
8735       }
8736     } else if (MayExitMaxBECount != getCouldNotCompute()) {
8737       if (!MayExitMaxBECount || EL.ConstantMaxNotTaken == getCouldNotCompute())
8738         MayExitMaxBECount = EL.ConstantMaxNotTaken;
8739       else {
8740         MayExitMaxBECount = getUMaxFromMismatchedTypes(MayExitMaxBECount,
8741                                                        EL.ConstantMaxNotTaken);
8742       }
8743     }
8744   }
8745   const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
8746     (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
8747   // The loop backedge will be taken the maximum or zero times if there's
8748   // a single exit that must be taken the maximum or zero times.
8749   bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
8750 
8751   // Remember which SCEVs are used in exit limits for invalidation purposes.
8752   // We only care about non-constant SCEVs here, so we can ignore
8753   // EL.ConstantMaxNotTaken
8754   // and MaxBECount, which must be SCEVConstant.
8755   for (const auto &Pair : ExitCounts) {
8756     if (!isa<SCEVConstant>(Pair.second.ExactNotTaken))
8757       BECountUsers[Pair.second.ExactNotTaken].insert({L, AllowPredicates});
8758     if (!isa<SCEVConstant>(Pair.second.SymbolicMaxNotTaken))
8759       BECountUsers[Pair.second.SymbolicMaxNotTaken].insert(
8760           {L, AllowPredicates});
8761   }
8762   return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
8763                            MaxBECount, MaxOrZero);
8764 }
8765 
8766 ScalarEvolution::ExitLimit
8767 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
8768                                       bool AllowPredicates) {
8769   assert(L->contains(ExitingBlock) && "Exit count for non-loop block?");
8770   // If our exiting block does not dominate the latch, then its connection with
8771   // loop's exit limit may be far from trivial.
8772   const BasicBlock *Latch = L->getLoopLatch();
8773   if (!Latch || !DT.dominates(ExitingBlock, Latch))
8774     return getCouldNotCompute();
8775 
8776   bool IsOnlyExit = (L->getExitingBlock() != nullptr);
8777   Instruction *Term = ExitingBlock->getTerminator();
8778   if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
8779     assert(BI->isConditional() && "If unconditional, it can't be in loop!");
8780     bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
8781     assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) &&
8782            "It should have one successor in loop and one exit block!");
8783     // Proceed to the next level to examine the exit condition expression.
8784     return computeExitLimitFromCond(L, BI->getCondition(), ExitIfTrue,
8785                                     /*ControlsOnlyExit=*/IsOnlyExit,
8786                                     AllowPredicates);
8787   }
8788 
8789   if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) {
8790     // For switch, make sure that there is a single exit from the loop.
8791     BasicBlock *Exit = nullptr;
8792     for (auto *SBB : successors(ExitingBlock))
8793       if (!L->contains(SBB)) {
8794         if (Exit) // Multiple exit successors.
8795           return getCouldNotCompute();
8796         Exit = SBB;
8797       }
8798     assert(Exit && "Exiting block must have at least one exit");
8799     return computeExitLimitFromSingleExitSwitch(
8800         L, SI, Exit,
8801         /*ControlsOnlyExit=*/IsOnlyExit);
8802   }
8803 
8804   return getCouldNotCompute();
8805 }
8806 
8807 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond(
8808     const Loop *L, Value *ExitCond, bool ExitIfTrue, bool ControlsOnlyExit,
8809     bool AllowPredicates) {
8810   ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates);
8811   return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue,
8812                                         ControlsOnlyExit, AllowPredicates);
8813 }
8814 
8815 std::optional<ScalarEvolution::ExitLimit>
8816 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
8817                                       bool ExitIfTrue, bool ControlsOnlyExit,
8818                                       bool AllowPredicates) {
8819   (void)this->L;
8820   (void)this->ExitIfTrue;
8821   (void)this->AllowPredicates;
8822 
8823   assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
8824          this->AllowPredicates == AllowPredicates &&
8825          "Variance in assumed invariant key components!");
8826   auto Itr = TripCountMap.find({ExitCond, ControlsOnlyExit});
8827   if (Itr == TripCountMap.end())
8828     return std::nullopt;
8829   return Itr->second;
8830 }
8831 
8832 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
8833                                              bool ExitIfTrue,
8834                                              bool ControlsOnlyExit,
8835                                              bool AllowPredicates,
8836                                              const ExitLimit &EL) {
8837   assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
8838          this->AllowPredicates == AllowPredicates &&
8839          "Variance in assumed invariant key components!");
8840 
8841   auto InsertResult = TripCountMap.insert({{ExitCond, ControlsOnlyExit}, EL});
8842   assert(InsertResult.second && "Expected successful insertion!");
8843   (void)InsertResult;
8844   (void)ExitIfTrue;
8845 }
8846 
8847 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
8848     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
8849     bool ControlsOnlyExit, bool AllowPredicates) {
8850 
8851   if (auto MaybeEL = Cache.find(L, ExitCond, ExitIfTrue, ControlsOnlyExit,
8852                                 AllowPredicates))
8853     return *MaybeEL;
8854 
8855   ExitLimit EL = computeExitLimitFromCondImpl(
8856       Cache, L, ExitCond, ExitIfTrue, ControlsOnlyExit, AllowPredicates);
8857   Cache.insert(L, ExitCond, ExitIfTrue, ControlsOnlyExit, AllowPredicates, EL);
8858   return EL;
8859 }
8860 
8861 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
8862     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
8863     bool ControlsOnlyExit, bool AllowPredicates) {
8864   // Handle BinOp conditions (And, Or).
8865   if (auto LimitFromBinOp = computeExitLimitFromCondFromBinOp(
8866           Cache, L, ExitCond, ExitIfTrue, ControlsOnlyExit, AllowPredicates))
8867     return *LimitFromBinOp;
8868 
8869   // With an icmp, it may be feasible to compute an exact backedge-taken count.
8870   // Proceed to the next level to examine the icmp.
8871   if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
8872     ExitLimit EL =
8873         computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsOnlyExit);
8874     if (EL.hasFullInfo() || !AllowPredicates)
8875       return EL;
8876 
8877     // Try again, but use SCEV predicates this time.
8878     return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue,
8879                                     ControlsOnlyExit,
8880                                     /*AllowPredicates=*/true);
8881   }
8882 
8883   // Check for a constant condition. These are normally stripped out by
8884   // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
8885   // preserve the CFG and is temporarily leaving constant conditions
8886   // in place.
8887   if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
8888     if (ExitIfTrue == !CI->getZExtValue())
8889       // The backedge is always taken.
8890       return getCouldNotCompute();
8891     // The backedge is never taken.
8892     return getZero(CI->getType());
8893   }
8894 
8895   // If we're exiting based on the overflow flag of an x.with.overflow intrinsic
8896   // with a constant step, we can form an equivalent icmp predicate and figure
8897   // out how many iterations will be taken before we exit.
8898   const WithOverflowInst *WO;
8899   const APInt *C;
8900   if (match(ExitCond, m_ExtractValue<1>(m_WithOverflowInst(WO))) &&
8901       match(WO->getRHS(), m_APInt(C))) {
8902     ConstantRange NWR =
8903       ConstantRange::makeExactNoWrapRegion(WO->getBinaryOp(), *C,
8904                                            WO->getNoWrapKind());
8905     CmpInst::Predicate Pred;
8906     APInt NewRHSC, Offset;
8907     NWR.getEquivalentICmp(Pred, NewRHSC, Offset);
8908     if (!ExitIfTrue)
8909       Pred = ICmpInst::getInversePredicate(Pred);
8910     auto *LHS = getSCEV(WO->getLHS());
8911     if (Offset != 0)
8912       LHS = getAddExpr(LHS, getConstant(Offset));
8913     auto EL = computeExitLimitFromICmp(L, Pred, LHS, getConstant(NewRHSC),
8914                                        ControlsOnlyExit, AllowPredicates);
8915     if (EL.hasAnyInfo())
8916       return EL;
8917   }
8918 
8919   // If it's not an integer or pointer comparison then compute it the hard way.
8920   return computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
8921 }
8922 
8923 std::optional<ScalarEvolution::ExitLimit>
8924 ScalarEvolution::computeExitLimitFromCondFromBinOp(
8925     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
8926     bool ControlsOnlyExit, bool AllowPredicates) {
8927   // Check if the controlling expression for this loop is an And or Or.
8928   Value *Op0, *Op1;
8929   bool IsAnd = false;
8930   if (match(ExitCond, m_LogicalAnd(m_Value(Op0), m_Value(Op1))))
8931     IsAnd = true;
8932   else if (match(ExitCond, m_LogicalOr(m_Value(Op0), m_Value(Op1))))
8933     IsAnd = false;
8934   else
8935     return std::nullopt;
8936 
8937   // EitherMayExit is true in these two cases:
8938   //   br (and Op0 Op1), loop, exit
8939   //   br (or  Op0 Op1), exit, loop
8940   bool EitherMayExit = IsAnd ^ ExitIfTrue;
8941   ExitLimit EL0 = computeExitLimitFromCondCached(
8942       Cache, L, Op0, ExitIfTrue, ControlsOnlyExit && !EitherMayExit,
8943       AllowPredicates);
8944   ExitLimit EL1 = computeExitLimitFromCondCached(
8945       Cache, L, Op1, ExitIfTrue, ControlsOnlyExit && !EitherMayExit,
8946       AllowPredicates);
8947 
8948   // Be robust against unsimplified IR for the form "op i1 X, NeutralElement"
8949   const Constant *NeutralElement = ConstantInt::get(ExitCond->getType(), IsAnd);
8950   if (isa<ConstantInt>(Op1))
8951     return Op1 == NeutralElement ? EL0 : EL1;
8952   if (isa<ConstantInt>(Op0))
8953     return Op0 == NeutralElement ? EL1 : EL0;
8954 
8955   const SCEV *BECount = getCouldNotCompute();
8956   const SCEV *ConstantMaxBECount = getCouldNotCompute();
8957   const SCEV *SymbolicMaxBECount = getCouldNotCompute();
8958   if (EitherMayExit) {
8959     bool UseSequentialUMin = !isa<BinaryOperator>(ExitCond);
8960     // Both conditions must be same for the loop to continue executing.
8961     // Choose the less conservative count.
8962     if (EL0.ExactNotTaken != getCouldNotCompute() &&
8963         EL1.ExactNotTaken != getCouldNotCompute()) {
8964       BECount = getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken,
8965                                            UseSequentialUMin);
8966     }
8967     if (EL0.ConstantMaxNotTaken == getCouldNotCompute())
8968       ConstantMaxBECount = EL1.ConstantMaxNotTaken;
8969     else if (EL1.ConstantMaxNotTaken == getCouldNotCompute())
8970       ConstantMaxBECount = EL0.ConstantMaxNotTaken;
8971     else
8972       ConstantMaxBECount = getUMinFromMismatchedTypes(EL0.ConstantMaxNotTaken,
8973                                                       EL1.ConstantMaxNotTaken);
8974     if (EL0.SymbolicMaxNotTaken == getCouldNotCompute())
8975       SymbolicMaxBECount = EL1.SymbolicMaxNotTaken;
8976     else if (EL1.SymbolicMaxNotTaken == getCouldNotCompute())
8977       SymbolicMaxBECount = EL0.SymbolicMaxNotTaken;
8978     else
8979       SymbolicMaxBECount = getUMinFromMismatchedTypes(
8980           EL0.SymbolicMaxNotTaken, EL1.SymbolicMaxNotTaken, UseSequentialUMin);
8981   } else {
8982     // Both conditions must be same at the same time for the loop to exit.
8983     // For now, be conservative.
8984     if (EL0.ExactNotTaken == EL1.ExactNotTaken)
8985       BECount = EL0.ExactNotTaken;
8986   }
8987 
8988   // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
8989   // to be more aggressive when computing BECount than when computing
8990   // ConstantMaxBECount.  In these cases it is possible for EL0.ExactNotTaken
8991   // and
8992   // EL1.ExactNotTaken to match, but for EL0.ConstantMaxNotTaken and
8993   // EL1.ConstantMaxNotTaken to not.
8994   if (isa<SCEVCouldNotCompute>(ConstantMaxBECount) &&
8995       !isa<SCEVCouldNotCompute>(BECount))
8996     ConstantMaxBECount = getConstant(getUnsignedRangeMax(BECount));
8997   if (isa<SCEVCouldNotCompute>(SymbolicMaxBECount))
8998     SymbolicMaxBECount =
8999         isa<SCEVCouldNotCompute>(BECount) ? ConstantMaxBECount : BECount;
9000   return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount, false,
9001                    { &EL0.Predicates, &EL1.Predicates });
9002 }
9003 
9004 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromICmp(
9005     const Loop *L, ICmpInst *ExitCond, bool ExitIfTrue, bool ControlsOnlyExit,
9006     bool AllowPredicates) {
9007   // If the condition was exit on true, convert the condition to exit on false
9008   ICmpInst::Predicate Pred;
9009   if (!ExitIfTrue)
9010     Pred = ExitCond->getPredicate();
9011   else
9012     Pred = ExitCond->getInversePredicate();
9013   const ICmpInst::Predicate OriginalPred = Pred;
9014 
9015   const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
9016   const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
9017 
9018   ExitLimit EL = computeExitLimitFromICmp(L, Pred, LHS, RHS, ControlsOnlyExit,
9019                                           AllowPredicates);
9020   if (EL.hasAnyInfo())
9021     return EL;
9022 
9023   auto *ExhaustiveCount =
9024       computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
9025 
9026   if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
9027     return ExhaustiveCount;
9028 
9029   return computeShiftCompareExitLimit(ExitCond->getOperand(0),
9030                                       ExitCond->getOperand(1), L, OriginalPred);
9031 }
9032 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromICmp(
9033     const Loop *L, ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
9034     bool ControlsOnlyExit, bool AllowPredicates) {
9035 
9036   // Try to evaluate any dependencies out of the loop.
9037   LHS = getSCEVAtScope(LHS, L);
9038   RHS = getSCEVAtScope(RHS, L);
9039 
9040   // At this point, we would like to compute how many iterations of the
9041   // loop the predicate will return true for these inputs.
9042   if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
9043     // If there is a loop-invariant, force it into the RHS.
9044     std::swap(LHS, RHS);
9045     Pred = ICmpInst::getSwappedPredicate(Pred);
9046   }
9047 
9048   bool ControllingFiniteLoop = ControlsOnlyExit && loopHasNoAbnormalExits(L) &&
9049                                loopIsFiniteByAssumption(L);
9050   // Simplify the operands before analyzing them.
9051   (void)SimplifyICmpOperands(Pred, LHS, RHS, /*Depth=*/0);
9052 
9053   // If we have a comparison of a chrec against a constant, try to use value
9054   // ranges to answer this query.
9055   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
9056     if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
9057       if (AddRec->getLoop() == L) {
9058         // Form the constant range.
9059         ConstantRange CompRange =
9060             ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt());
9061 
9062         const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
9063         if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
9064       }
9065 
9066   // If this loop must exit based on this condition (or execute undefined
9067   // behaviour), and we can prove the test sequence produced must repeat
9068   // the same values on self-wrap of the IV, then we can infer that IV
9069   // doesn't self wrap because if it did, we'd have an infinite (undefined)
9070   // loop.
9071   if (ControllingFiniteLoop && isLoopInvariant(RHS, L)) {
9072     // TODO: We can peel off any functions which are invertible *in L*.  Loop
9073     // invariant terms are effectively constants for our purposes here.
9074     auto *InnerLHS = LHS;
9075     if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS))
9076       InnerLHS = ZExt->getOperand();
9077     if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(InnerLHS)) {
9078       auto *StrideC = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this));
9079       if (!AR->hasNoSelfWrap() && AR->getLoop() == L && AR->isAffine() &&
9080           StrideC && StrideC->getAPInt().isPowerOf2()) {
9081         auto Flags = AR->getNoWrapFlags();
9082         Flags = setFlags(Flags, SCEV::FlagNW);
9083         SmallVector<const SCEV*> Operands{AR->operands()};
9084         Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
9085         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
9086       }
9087     }
9088   }
9089 
9090   switch (Pred) {
9091   case ICmpInst::ICMP_NE: {                     // while (X != Y)
9092     // Convert to: while (X-Y != 0)
9093     if (LHS->getType()->isPointerTy()) {
9094       LHS = getLosslessPtrToIntExpr(LHS);
9095       if (isa<SCEVCouldNotCompute>(LHS))
9096         return LHS;
9097     }
9098     if (RHS->getType()->isPointerTy()) {
9099       RHS = getLosslessPtrToIntExpr(RHS);
9100       if (isa<SCEVCouldNotCompute>(RHS))
9101         return RHS;
9102     }
9103     ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsOnlyExit,
9104                                 AllowPredicates);
9105     if (EL.hasAnyInfo())
9106       return EL;
9107     break;
9108   }
9109   case ICmpInst::ICMP_EQ: {                     // while (X == Y)
9110     // Convert to: while (X-Y == 0)
9111     if (LHS->getType()->isPointerTy()) {
9112       LHS = getLosslessPtrToIntExpr(LHS);
9113       if (isa<SCEVCouldNotCompute>(LHS))
9114         return LHS;
9115     }
9116     if (RHS->getType()->isPointerTy()) {
9117       RHS = getLosslessPtrToIntExpr(RHS);
9118       if (isa<SCEVCouldNotCompute>(RHS))
9119         return RHS;
9120     }
9121     ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
9122     if (EL.hasAnyInfo()) return EL;
9123     break;
9124   }
9125   case ICmpInst::ICMP_SLE:
9126   case ICmpInst::ICMP_ULE:
9127     // Since the loop is finite, an invariant RHS cannot include the boundary
9128     // value, otherwise it would loop forever.
9129     if (!EnableFiniteLoopControl || !ControllingFiniteLoop ||
9130         !isLoopInvariant(RHS, L))
9131       break;
9132     RHS = getAddExpr(getOne(RHS->getType()), RHS);
9133     [[fallthrough]];
9134   case ICmpInst::ICMP_SLT:
9135   case ICmpInst::ICMP_ULT: { // while (X < Y)
9136     bool IsSigned = ICmpInst::isSigned(Pred);
9137     ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsOnlyExit,
9138                                     AllowPredicates);
9139     if (EL.hasAnyInfo())
9140       return EL;
9141     break;
9142   }
9143   case ICmpInst::ICMP_SGE:
9144   case ICmpInst::ICMP_UGE:
9145     // Since the loop is finite, an invariant RHS cannot include the boundary
9146     // value, otherwise it would loop forever.
9147     if (!EnableFiniteLoopControl || !ControllingFiniteLoop ||
9148         !isLoopInvariant(RHS, L))
9149       break;
9150     RHS = getAddExpr(getMinusOne(RHS->getType()), RHS);
9151     [[fallthrough]];
9152   case ICmpInst::ICMP_SGT:
9153   case ICmpInst::ICMP_UGT: { // while (X > Y)
9154     bool IsSigned = ICmpInst::isSigned(Pred);
9155     ExitLimit EL = howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsOnlyExit,
9156                                        AllowPredicates);
9157     if (EL.hasAnyInfo())
9158       return EL;
9159     break;
9160   }
9161   default:
9162     break;
9163   }
9164 
9165   return getCouldNotCompute();
9166 }
9167 
9168 ScalarEvolution::ExitLimit
9169 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
9170                                                       SwitchInst *Switch,
9171                                                       BasicBlock *ExitingBlock,
9172                                                       bool ControlsOnlyExit) {
9173   assert(!L->contains(ExitingBlock) && "Not an exiting block!");
9174 
9175   // Give up if the exit is the default dest of a switch.
9176   if (Switch->getDefaultDest() == ExitingBlock)
9177     return getCouldNotCompute();
9178 
9179   assert(L->contains(Switch->getDefaultDest()) &&
9180          "Default case must not exit the loop!");
9181   const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
9182   const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
9183 
9184   // while (X != Y) --> while (X-Y != 0)
9185   ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsOnlyExit);
9186   if (EL.hasAnyInfo())
9187     return EL;
9188 
9189   return getCouldNotCompute();
9190 }
9191 
9192 static ConstantInt *
9193 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
9194                                 ScalarEvolution &SE) {
9195   const SCEV *InVal = SE.getConstant(C);
9196   const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
9197   assert(isa<SCEVConstant>(Val) &&
9198          "Evaluation of SCEV at constant didn't fold correctly?");
9199   return cast<SCEVConstant>(Val)->getValue();
9200 }
9201 
9202 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
9203     Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
9204   ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
9205   if (!RHS)
9206     return getCouldNotCompute();
9207 
9208   const BasicBlock *Latch = L->getLoopLatch();
9209   if (!Latch)
9210     return getCouldNotCompute();
9211 
9212   const BasicBlock *Predecessor = L->getLoopPredecessor();
9213   if (!Predecessor)
9214     return getCouldNotCompute();
9215 
9216   // Return true if V is of the form "LHS `shift_op` <positive constant>".
9217   // Return LHS in OutLHS and shift_opt in OutOpCode.
9218   auto MatchPositiveShift =
9219       [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
9220 
9221     using namespace PatternMatch;
9222 
9223     ConstantInt *ShiftAmt;
9224     if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9225       OutOpCode = Instruction::LShr;
9226     else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9227       OutOpCode = Instruction::AShr;
9228     else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9229       OutOpCode = Instruction::Shl;
9230     else
9231       return false;
9232 
9233     return ShiftAmt->getValue().isStrictlyPositive();
9234   };
9235 
9236   // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
9237   //
9238   // loop:
9239   //   %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
9240   //   %iv.shifted = lshr i32 %iv, <positive constant>
9241   //
9242   // Return true on a successful match.  Return the corresponding PHI node (%iv
9243   // above) in PNOut and the opcode of the shift operation in OpCodeOut.
9244   auto MatchShiftRecurrence =
9245       [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
9246     std::optional<Instruction::BinaryOps> PostShiftOpCode;
9247 
9248     {
9249       Instruction::BinaryOps OpC;
9250       Value *V;
9251 
9252       // If we encounter a shift instruction, "peel off" the shift operation,
9253       // and remember that we did so.  Later when we inspect %iv's backedge
9254       // value, we will make sure that the backedge value uses the same
9255       // operation.
9256       //
9257       // Note: the peeled shift operation does not have to be the same
9258       // instruction as the one feeding into the PHI's backedge value.  We only
9259       // really care about it being the same *kind* of shift instruction --
9260       // that's all that is required for our later inferences to hold.
9261       if (MatchPositiveShift(LHS, V, OpC)) {
9262         PostShiftOpCode = OpC;
9263         LHS = V;
9264       }
9265     }
9266 
9267     PNOut = dyn_cast<PHINode>(LHS);
9268     if (!PNOut || PNOut->getParent() != L->getHeader())
9269       return false;
9270 
9271     Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
9272     Value *OpLHS;
9273 
9274     return
9275         // The backedge value for the PHI node must be a shift by a positive
9276         // amount
9277         MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
9278 
9279         // of the PHI node itself
9280         OpLHS == PNOut &&
9281 
9282         // and the kind of shift should be match the kind of shift we peeled
9283         // off, if any.
9284         (!PostShiftOpCode || *PostShiftOpCode == OpCodeOut);
9285   };
9286 
9287   PHINode *PN;
9288   Instruction::BinaryOps OpCode;
9289   if (!MatchShiftRecurrence(LHS, PN, OpCode))
9290     return getCouldNotCompute();
9291 
9292   const DataLayout &DL = getDataLayout();
9293 
9294   // The key rationale for this optimization is that for some kinds of shift
9295   // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
9296   // within a finite number of iterations.  If the condition guarding the
9297   // backedge (in the sense that the backedge is taken if the condition is true)
9298   // is false for the value the shift recurrence stabilizes to, then we know
9299   // that the backedge is taken only a finite number of times.
9300 
9301   ConstantInt *StableValue = nullptr;
9302   switch (OpCode) {
9303   default:
9304     llvm_unreachable("Impossible case!");
9305 
9306   case Instruction::AShr: {
9307     // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
9308     // bitwidth(K) iterations.
9309     Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
9310     KnownBits Known = computeKnownBits(FirstValue, DL, 0, &AC,
9311                                        Predecessor->getTerminator(), &DT);
9312     auto *Ty = cast<IntegerType>(RHS->getType());
9313     if (Known.isNonNegative())
9314       StableValue = ConstantInt::get(Ty, 0);
9315     else if (Known.isNegative())
9316       StableValue = ConstantInt::get(Ty, -1, true);
9317     else
9318       return getCouldNotCompute();
9319 
9320     break;
9321   }
9322   case Instruction::LShr:
9323   case Instruction::Shl:
9324     // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
9325     // stabilize to 0 in at most bitwidth(K) iterations.
9326     StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
9327     break;
9328   }
9329 
9330   auto *Result =
9331       ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
9332   assert(Result->getType()->isIntegerTy(1) &&
9333          "Otherwise cannot be an operand to a branch instruction");
9334 
9335   if (Result->isZeroValue()) {
9336     unsigned BitWidth = getTypeSizeInBits(RHS->getType());
9337     const SCEV *UpperBound =
9338         getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
9339     return ExitLimit(getCouldNotCompute(), UpperBound, UpperBound, false);
9340   }
9341 
9342   return getCouldNotCompute();
9343 }
9344 
9345 /// Return true if we can constant fold an instruction of the specified type,
9346 /// assuming that all operands were constants.
9347 static bool CanConstantFold(const Instruction *I) {
9348   if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
9349       isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
9350       isa<LoadInst>(I) || isa<ExtractValueInst>(I))
9351     return true;
9352 
9353   if (const CallInst *CI = dyn_cast<CallInst>(I))
9354     if (const Function *F = CI->getCalledFunction())
9355       return canConstantFoldCallTo(CI, F);
9356   return false;
9357 }
9358 
9359 /// Determine whether this instruction can constant evolve within this loop
9360 /// assuming its operands can all constant evolve.
9361 static bool canConstantEvolve(Instruction *I, const Loop *L) {
9362   // An instruction outside of the loop can't be derived from a loop PHI.
9363   if (!L->contains(I)) return false;
9364 
9365   if (isa<PHINode>(I)) {
9366     // We don't currently keep track of the control flow needed to evaluate
9367     // PHIs, so we cannot handle PHIs inside of loops.
9368     return L->getHeader() == I->getParent();
9369   }
9370 
9371   // If we won't be able to constant fold this expression even if the operands
9372   // are constants, bail early.
9373   return CanConstantFold(I);
9374 }
9375 
9376 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
9377 /// recursing through each instruction operand until reaching a loop header phi.
9378 static PHINode *
9379 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
9380                                DenseMap<Instruction *, PHINode *> &PHIMap,
9381                                unsigned Depth) {
9382   if (Depth > MaxConstantEvolvingDepth)
9383     return nullptr;
9384 
9385   // Otherwise, we can evaluate this instruction if all of its operands are
9386   // constant or derived from a PHI node themselves.
9387   PHINode *PHI = nullptr;
9388   for (Value *Op : UseInst->operands()) {
9389     if (isa<Constant>(Op)) continue;
9390 
9391     Instruction *OpInst = dyn_cast<Instruction>(Op);
9392     if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
9393 
9394     PHINode *P = dyn_cast<PHINode>(OpInst);
9395     if (!P)
9396       // If this operand is already visited, reuse the prior result.
9397       // We may have P != PHI if this is the deepest point at which the
9398       // inconsistent paths meet.
9399       P = PHIMap.lookup(OpInst);
9400     if (!P) {
9401       // Recurse and memoize the results, whether a phi is found or not.
9402       // This recursive call invalidates pointers into PHIMap.
9403       P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1);
9404       PHIMap[OpInst] = P;
9405     }
9406     if (!P)
9407       return nullptr;  // Not evolving from PHI
9408     if (PHI && PHI != P)
9409       return nullptr;  // Evolving from multiple different PHIs.
9410     PHI = P;
9411   }
9412   // This is a expression evolving from a constant PHI!
9413   return PHI;
9414 }
9415 
9416 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
9417 /// in the loop that V is derived from.  We allow arbitrary operations along the
9418 /// way, but the operands of an operation must either be constants or a value
9419 /// derived from a constant PHI.  If this expression does not fit with these
9420 /// constraints, return null.
9421 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
9422   Instruction *I = dyn_cast<Instruction>(V);
9423   if (!I || !canConstantEvolve(I, L)) return nullptr;
9424 
9425   if (PHINode *PN = dyn_cast<PHINode>(I))
9426     return PN;
9427 
9428   // Record non-constant instructions contained by the loop.
9429   DenseMap<Instruction *, PHINode *> PHIMap;
9430   return getConstantEvolvingPHIOperands(I, L, PHIMap, 0);
9431 }
9432 
9433 /// EvaluateExpression - Given an expression that passes the
9434 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
9435 /// in the loop has the value PHIVal.  If we can't fold this expression for some
9436 /// reason, return null.
9437 static Constant *EvaluateExpression(Value *V, const Loop *L,
9438                                     DenseMap<Instruction *, Constant *> &Vals,
9439                                     const DataLayout &DL,
9440                                     const TargetLibraryInfo *TLI) {
9441   // Convenient constant check, but redundant for recursive calls.
9442   if (Constant *C = dyn_cast<Constant>(V)) return C;
9443   Instruction *I = dyn_cast<Instruction>(V);
9444   if (!I) return nullptr;
9445 
9446   if (Constant *C = Vals.lookup(I)) return C;
9447 
9448   // An instruction inside the loop depends on a value outside the loop that we
9449   // weren't given a mapping for, or a value such as a call inside the loop.
9450   if (!canConstantEvolve(I, L)) return nullptr;
9451 
9452   // An unmapped PHI can be due to a branch or another loop inside this loop,
9453   // or due to this not being the initial iteration through a loop where we
9454   // couldn't compute the evolution of this particular PHI last time.
9455   if (isa<PHINode>(I)) return nullptr;
9456 
9457   std::vector<Constant*> Operands(I->getNumOperands());
9458 
9459   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
9460     Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
9461     if (!Operand) {
9462       Operands[i] = dyn_cast<Constant>(I->getOperand(i));
9463       if (!Operands[i]) return nullptr;
9464       continue;
9465     }
9466     Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
9467     Vals[Operand] = C;
9468     if (!C) return nullptr;
9469     Operands[i] = C;
9470   }
9471 
9472   return ConstantFoldInstOperands(I, Operands, DL, TLI);
9473 }
9474 
9475 
9476 // If every incoming value to PN except the one for BB is a specific Constant,
9477 // return that, else return nullptr.
9478 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
9479   Constant *IncomingVal = nullptr;
9480 
9481   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9482     if (PN->getIncomingBlock(i) == BB)
9483       continue;
9484 
9485     auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
9486     if (!CurrentVal)
9487       return nullptr;
9488 
9489     if (IncomingVal != CurrentVal) {
9490       if (IncomingVal)
9491         return nullptr;
9492       IncomingVal = CurrentVal;
9493     }
9494   }
9495 
9496   return IncomingVal;
9497 }
9498 
9499 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
9500 /// in the header of its containing loop, we know the loop executes a
9501 /// constant number of times, and the PHI node is just a recurrence
9502 /// involving constants, fold it.
9503 Constant *
9504 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
9505                                                    const APInt &BEs,
9506                                                    const Loop *L) {
9507   auto I = ConstantEvolutionLoopExitValue.find(PN);
9508   if (I != ConstantEvolutionLoopExitValue.end())
9509     return I->second;
9510 
9511   if (BEs.ugt(MaxBruteForceIterations))
9512     return ConstantEvolutionLoopExitValue[PN] = nullptr;  // Not going to evaluate it.
9513 
9514   Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
9515 
9516   DenseMap<Instruction *, Constant *> CurrentIterVals;
9517   BasicBlock *Header = L->getHeader();
9518   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
9519 
9520   BasicBlock *Latch = L->getLoopLatch();
9521   if (!Latch)
9522     return nullptr;
9523 
9524   for (PHINode &PHI : Header->phis()) {
9525     if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
9526       CurrentIterVals[&PHI] = StartCST;
9527   }
9528   if (!CurrentIterVals.count(PN))
9529     return RetVal = nullptr;
9530 
9531   Value *BEValue = PN->getIncomingValueForBlock(Latch);
9532 
9533   // Execute the loop symbolically to determine the exit value.
9534   assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) &&
9535          "BEs is <= MaxBruteForceIterations which is an 'unsigned'!");
9536 
9537   unsigned NumIterations = BEs.getZExtValue(); // must be in range
9538   unsigned IterationNum = 0;
9539   const DataLayout &DL = getDataLayout();
9540   for (; ; ++IterationNum) {
9541     if (IterationNum == NumIterations)
9542       return RetVal = CurrentIterVals[PN];  // Got exit value!
9543 
9544     // Compute the value of the PHIs for the next iteration.
9545     // EvaluateExpression adds non-phi values to the CurrentIterVals map.
9546     DenseMap<Instruction *, Constant *> NextIterVals;
9547     Constant *NextPHI =
9548         EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
9549     if (!NextPHI)
9550       return nullptr;        // Couldn't evaluate!
9551     NextIterVals[PN] = NextPHI;
9552 
9553     bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
9554 
9555     // Also evaluate the other PHI nodes.  However, we don't get to stop if we
9556     // cease to be able to evaluate one of them or if they stop evolving,
9557     // because that doesn't necessarily prevent us from computing PN.
9558     SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
9559     for (const auto &I : CurrentIterVals) {
9560       PHINode *PHI = dyn_cast<PHINode>(I.first);
9561       if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
9562       PHIsToCompute.emplace_back(PHI, I.second);
9563     }
9564     // We use two distinct loops because EvaluateExpression may invalidate any
9565     // iterators into CurrentIterVals.
9566     for (const auto &I : PHIsToCompute) {
9567       PHINode *PHI = I.first;
9568       Constant *&NextPHI = NextIterVals[PHI];
9569       if (!NextPHI) {   // Not already computed.
9570         Value *BEValue = PHI->getIncomingValueForBlock(Latch);
9571         NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
9572       }
9573       if (NextPHI != I.second)
9574         StoppedEvolving = false;
9575     }
9576 
9577     // If all entries in CurrentIterVals == NextIterVals then we can stop
9578     // iterating, the loop can't continue to change.
9579     if (StoppedEvolving)
9580       return RetVal = CurrentIterVals[PN];
9581 
9582     CurrentIterVals.swap(NextIterVals);
9583   }
9584 }
9585 
9586 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
9587                                                           Value *Cond,
9588                                                           bool ExitWhen) {
9589   PHINode *PN = getConstantEvolvingPHI(Cond, L);
9590   if (!PN) return getCouldNotCompute();
9591 
9592   // If the loop is canonicalized, the PHI will have exactly two entries.
9593   // That's the only form we support here.
9594   if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
9595 
9596   DenseMap<Instruction *, Constant *> CurrentIterVals;
9597   BasicBlock *Header = L->getHeader();
9598   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
9599 
9600   BasicBlock *Latch = L->getLoopLatch();
9601   assert(Latch && "Should follow from NumIncomingValues == 2!");
9602 
9603   for (PHINode &PHI : Header->phis()) {
9604     if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
9605       CurrentIterVals[&PHI] = StartCST;
9606   }
9607   if (!CurrentIterVals.count(PN))
9608     return getCouldNotCompute();
9609 
9610   // Okay, we find a PHI node that defines the trip count of this loop.  Execute
9611   // the loop symbolically to determine when the condition gets a value of
9612   // "ExitWhen".
9613   unsigned MaxIterations = MaxBruteForceIterations;   // Limit analysis.
9614   const DataLayout &DL = getDataLayout();
9615   for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
9616     auto *CondVal = dyn_cast_or_null<ConstantInt>(
9617         EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
9618 
9619     // Couldn't symbolically evaluate.
9620     if (!CondVal) return getCouldNotCompute();
9621 
9622     if (CondVal->getValue() == uint64_t(ExitWhen)) {
9623       ++NumBruteForceTripCountsComputed;
9624       return getConstant(Type::getInt32Ty(getContext()), IterationNum);
9625     }
9626 
9627     // Update all the PHI nodes for the next iteration.
9628     DenseMap<Instruction *, Constant *> NextIterVals;
9629 
9630     // Create a list of which PHIs we need to compute. We want to do this before
9631     // calling EvaluateExpression on them because that may invalidate iterators
9632     // into CurrentIterVals.
9633     SmallVector<PHINode *, 8> PHIsToCompute;
9634     for (const auto &I : CurrentIterVals) {
9635       PHINode *PHI = dyn_cast<PHINode>(I.first);
9636       if (!PHI || PHI->getParent() != Header) continue;
9637       PHIsToCompute.push_back(PHI);
9638     }
9639     for (PHINode *PHI : PHIsToCompute) {
9640       Constant *&NextPHI = NextIterVals[PHI];
9641       if (NextPHI) continue;    // Already computed!
9642 
9643       Value *BEValue = PHI->getIncomingValueForBlock(Latch);
9644       NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
9645     }
9646     CurrentIterVals.swap(NextIterVals);
9647   }
9648 
9649   // Too many iterations were needed to evaluate.
9650   return getCouldNotCompute();
9651 }
9652 
9653 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
9654   SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
9655       ValuesAtScopes[V];
9656   // Check to see if we've folded this expression at this loop before.
9657   for (auto &LS : Values)
9658     if (LS.first == L)
9659       return LS.second ? LS.second : V;
9660 
9661   Values.emplace_back(L, nullptr);
9662 
9663   // Otherwise compute it.
9664   const SCEV *C = computeSCEVAtScope(V, L);
9665   for (auto &LS : reverse(ValuesAtScopes[V]))
9666     if (LS.first == L) {
9667       LS.second = C;
9668       if (!isa<SCEVConstant>(C))
9669         ValuesAtScopesUsers[C].push_back({L, V});
9670       break;
9671     }
9672   return C;
9673 }
9674 
9675 /// This builds up a Constant using the ConstantExpr interface.  That way, we
9676 /// will return Constants for objects which aren't represented by a
9677 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
9678 /// Returns NULL if the SCEV isn't representable as a Constant.
9679 static Constant *BuildConstantFromSCEV(const SCEV *V) {
9680   switch (V->getSCEVType()) {
9681   case scCouldNotCompute:
9682   case scAddRecExpr:
9683   case scVScale:
9684     return nullptr;
9685   case scConstant:
9686     return cast<SCEVConstant>(V)->getValue();
9687   case scUnknown:
9688     return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
9689   case scPtrToInt: {
9690     const SCEVPtrToIntExpr *P2I = cast<SCEVPtrToIntExpr>(V);
9691     if (Constant *CastOp = BuildConstantFromSCEV(P2I->getOperand()))
9692       return ConstantExpr::getPtrToInt(CastOp, P2I->getType());
9693 
9694     return nullptr;
9695   }
9696   case scTruncate: {
9697     const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
9698     if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
9699       return ConstantExpr::getTrunc(CastOp, ST->getType());
9700     return nullptr;
9701   }
9702   case scAddExpr: {
9703     const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
9704     Constant *C = nullptr;
9705     for (const SCEV *Op : SA->operands()) {
9706       Constant *OpC = BuildConstantFromSCEV(Op);
9707       if (!OpC)
9708         return nullptr;
9709       if (!C) {
9710         C = OpC;
9711         continue;
9712       }
9713       assert(!C->getType()->isPointerTy() &&
9714              "Can only have one pointer, and it must be last");
9715       if (OpC->getType()->isPointerTy()) {
9716         // The offsets have been converted to bytes.  We can add bytes using
9717         // an i8 GEP.
9718         C = ConstantExpr::getGetElementPtr(Type::getInt8Ty(C->getContext()),
9719                                            OpC, C);
9720       } else {
9721         C = ConstantExpr::getAdd(C, OpC);
9722       }
9723     }
9724     return C;
9725   }
9726   case scMulExpr:
9727   case scSignExtend:
9728   case scZeroExtend:
9729   case scUDivExpr:
9730   case scSMaxExpr:
9731   case scUMaxExpr:
9732   case scSMinExpr:
9733   case scUMinExpr:
9734   case scSequentialUMinExpr:
9735     return nullptr;
9736   }
9737   llvm_unreachable("Unknown SCEV kind!");
9738 }
9739 
9740 const SCEV *
9741 ScalarEvolution::getWithOperands(const SCEV *S,
9742                                  SmallVectorImpl<const SCEV *> &NewOps) {
9743   switch (S->getSCEVType()) {
9744   case scTruncate:
9745   case scZeroExtend:
9746   case scSignExtend:
9747   case scPtrToInt:
9748     return getCastExpr(S->getSCEVType(), NewOps[0], S->getType());
9749   case scAddRecExpr: {
9750     auto *AddRec = cast<SCEVAddRecExpr>(S);
9751     return getAddRecExpr(NewOps, AddRec->getLoop(), AddRec->getNoWrapFlags());
9752   }
9753   case scAddExpr:
9754     return getAddExpr(NewOps, cast<SCEVAddExpr>(S)->getNoWrapFlags());
9755   case scMulExpr:
9756     return getMulExpr(NewOps, cast<SCEVMulExpr>(S)->getNoWrapFlags());
9757   case scUDivExpr:
9758     return getUDivExpr(NewOps[0], NewOps[1]);
9759   case scUMaxExpr:
9760   case scSMaxExpr:
9761   case scUMinExpr:
9762   case scSMinExpr:
9763     return getMinMaxExpr(S->getSCEVType(), NewOps);
9764   case scSequentialUMinExpr:
9765     return getSequentialMinMaxExpr(S->getSCEVType(), NewOps);
9766   case scConstant:
9767   case scVScale:
9768   case scUnknown:
9769     return S;
9770   case scCouldNotCompute:
9771     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
9772   }
9773   llvm_unreachable("Unknown SCEV kind!");
9774 }
9775 
9776 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
9777   switch (V->getSCEVType()) {
9778   case scConstant:
9779   case scVScale:
9780     return V;
9781   case scAddRecExpr: {
9782     // If this is a loop recurrence for a loop that does not contain L, then we
9783     // are dealing with the final value computed by the loop.
9784     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(V);
9785     // First, attempt to evaluate each operand.
9786     // Avoid performing the look-up in the common case where the specified
9787     // expression has no loop-variant portions.
9788     for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
9789       const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
9790       if (OpAtScope == AddRec->getOperand(i))
9791         continue;
9792 
9793       // Okay, at least one of these operands is loop variant but might be
9794       // foldable.  Build a new instance of the folded commutative expression.
9795       SmallVector<const SCEV *, 8> NewOps;
9796       NewOps.reserve(AddRec->getNumOperands());
9797       append_range(NewOps, AddRec->operands().take_front(i));
9798       NewOps.push_back(OpAtScope);
9799       for (++i; i != e; ++i)
9800         NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
9801 
9802       const SCEV *FoldedRec = getAddRecExpr(
9803           NewOps, AddRec->getLoop(), AddRec->getNoWrapFlags(SCEV::FlagNW));
9804       AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
9805       // The addrec may be folded to a nonrecurrence, for example, if the
9806       // induction variable is multiplied by zero after constant folding. Go
9807       // ahead and return the folded value.
9808       if (!AddRec)
9809         return FoldedRec;
9810       break;
9811     }
9812 
9813     // If the scope is outside the addrec's loop, evaluate it by using the
9814     // loop exit value of the addrec.
9815     if (!AddRec->getLoop()->contains(L)) {
9816       // To evaluate this recurrence, we need to know how many times the AddRec
9817       // loop iterates.  Compute this now.
9818       const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
9819       if (BackedgeTakenCount == getCouldNotCompute())
9820         return AddRec;
9821 
9822       // Then, evaluate the AddRec.
9823       return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
9824     }
9825 
9826     return AddRec;
9827   }
9828   case scTruncate:
9829   case scZeroExtend:
9830   case scSignExtend:
9831   case scPtrToInt:
9832   case scAddExpr:
9833   case scMulExpr:
9834   case scUDivExpr:
9835   case scUMaxExpr:
9836   case scSMaxExpr:
9837   case scUMinExpr:
9838   case scSMinExpr:
9839   case scSequentialUMinExpr: {
9840     ArrayRef<const SCEV *> Ops = V->operands();
9841     // Avoid performing the look-up in the common case where the specified
9842     // expression has no loop-variant portions.
9843     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
9844       const SCEV *OpAtScope = getSCEVAtScope(Ops[i], L);
9845       if (OpAtScope != Ops[i]) {
9846         // Okay, at least one of these operands is loop variant but might be
9847         // foldable.  Build a new instance of the folded commutative expression.
9848         SmallVector<const SCEV *, 8> NewOps;
9849         NewOps.reserve(Ops.size());
9850         append_range(NewOps, Ops.take_front(i));
9851         NewOps.push_back(OpAtScope);
9852 
9853         for (++i; i != e; ++i) {
9854           OpAtScope = getSCEVAtScope(Ops[i], L);
9855           NewOps.push_back(OpAtScope);
9856         }
9857 
9858         return getWithOperands(V, NewOps);
9859       }
9860     }
9861     // If we got here, all operands are loop invariant.
9862     return V;
9863   }
9864   case scUnknown: {
9865     // If this instruction is evolved from a constant-evolving PHI, compute the
9866     // exit value from the loop without using SCEVs.
9867     const SCEVUnknown *SU = cast<SCEVUnknown>(V);
9868     Instruction *I = dyn_cast<Instruction>(SU->getValue());
9869     if (!I)
9870       return V; // This is some other type of SCEVUnknown, just return it.
9871 
9872     if (PHINode *PN = dyn_cast<PHINode>(I)) {
9873       const Loop *CurrLoop = this->LI[I->getParent()];
9874       // Looking for loop exit value.
9875       if (CurrLoop && CurrLoop->getParentLoop() == L &&
9876           PN->getParent() == CurrLoop->getHeader()) {
9877         // Okay, there is no closed form solution for the PHI node.  Check
9878         // to see if the loop that contains it has a known backedge-taken
9879         // count.  If so, we may be able to force computation of the exit
9880         // value.
9881         const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop);
9882         // This trivial case can show up in some degenerate cases where
9883         // the incoming IR has not yet been fully simplified.
9884         if (BackedgeTakenCount->isZero()) {
9885           Value *InitValue = nullptr;
9886           bool MultipleInitValues = false;
9887           for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
9888             if (!CurrLoop->contains(PN->getIncomingBlock(i))) {
9889               if (!InitValue)
9890                 InitValue = PN->getIncomingValue(i);
9891               else if (InitValue != PN->getIncomingValue(i)) {
9892                 MultipleInitValues = true;
9893                 break;
9894               }
9895             }
9896           }
9897           if (!MultipleInitValues && InitValue)
9898             return getSCEV(InitValue);
9899         }
9900         // Do we have a loop invariant value flowing around the backedge
9901         // for a loop which must execute the backedge?
9902         if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
9903             isKnownNonZero(BackedgeTakenCount) &&
9904             PN->getNumIncomingValues() == 2) {
9905 
9906           unsigned InLoopPred =
9907               CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1;
9908           Value *BackedgeVal = PN->getIncomingValue(InLoopPred);
9909           if (CurrLoop->isLoopInvariant(BackedgeVal))
9910             return getSCEV(BackedgeVal);
9911         }
9912         if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
9913           // Okay, we know how many times the containing loop executes.  If
9914           // this is a constant evolving PHI node, get the final value at
9915           // the specified iteration number.
9916           Constant *RV =
9917               getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), CurrLoop);
9918           if (RV)
9919             return getSCEV(RV);
9920         }
9921       }
9922     }
9923 
9924     // Okay, this is an expression that we cannot symbolically evaluate
9925     // into a SCEV.  Check to see if it's possible to symbolically evaluate
9926     // the arguments into constants, and if so, try to constant propagate the
9927     // result.  This is particularly useful for computing loop exit values.
9928     if (!CanConstantFold(I))
9929       return V; // This is some other type of SCEVUnknown, just return it.
9930 
9931     SmallVector<Constant *, 4> Operands;
9932     Operands.reserve(I->getNumOperands());
9933     bool MadeImprovement = false;
9934     for (Value *Op : I->operands()) {
9935       if (Constant *C = dyn_cast<Constant>(Op)) {
9936         Operands.push_back(C);
9937         continue;
9938       }
9939 
9940       // If any of the operands is non-constant and if they are
9941       // non-integer and non-pointer, don't even try to analyze them
9942       // with scev techniques.
9943       if (!isSCEVable(Op->getType()))
9944         return V;
9945 
9946       const SCEV *OrigV = getSCEV(Op);
9947       const SCEV *OpV = getSCEVAtScope(OrigV, L);
9948       MadeImprovement |= OrigV != OpV;
9949 
9950       Constant *C = BuildConstantFromSCEV(OpV);
9951       if (!C)
9952         return V;
9953       assert(C->getType() == Op->getType() && "Type mismatch");
9954       Operands.push_back(C);
9955     }
9956 
9957     // Check to see if getSCEVAtScope actually made an improvement.
9958     if (!MadeImprovement)
9959       return V; // This is some other type of SCEVUnknown, just return it.
9960 
9961     Constant *C = nullptr;
9962     const DataLayout &DL = getDataLayout();
9963     C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
9964     if (!C)
9965       return V;
9966     return getSCEV(C);
9967   }
9968   case scCouldNotCompute:
9969     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
9970   }
9971   llvm_unreachable("Unknown SCEV type!");
9972 }
9973 
9974 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
9975   return getSCEVAtScope(getSCEV(V), L);
9976 }
9977 
9978 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const {
9979   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S))
9980     return stripInjectiveFunctions(ZExt->getOperand());
9981   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S))
9982     return stripInjectiveFunctions(SExt->getOperand());
9983   return S;
9984 }
9985 
9986 /// Finds the minimum unsigned root of the following equation:
9987 ///
9988 ///     A * X = B (mod N)
9989 ///
9990 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
9991 /// A and B isn't important.
9992 ///
9993 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
9994 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B,
9995                                                ScalarEvolution &SE) {
9996   uint32_t BW = A.getBitWidth();
9997   assert(BW == SE.getTypeSizeInBits(B->getType()));
9998   assert(A != 0 && "A must be non-zero.");
9999 
10000   // 1. D = gcd(A, N)
10001   //
10002   // The gcd of A and N may have only one prime factor: 2. The number of
10003   // trailing zeros in A is its multiplicity
10004   uint32_t Mult2 = A.countr_zero();
10005   // D = 2^Mult2
10006 
10007   // 2. Check if B is divisible by D.
10008   //
10009   // B is divisible by D if and only if the multiplicity of prime factor 2 for B
10010   // is not less than multiplicity of this prime factor for D.
10011   if (SE.getMinTrailingZeros(B) < Mult2)
10012     return SE.getCouldNotCompute();
10013 
10014   // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
10015   // modulo (N / D).
10016   //
10017   // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
10018   // (N / D) in general. The inverse itself always fits into BW bits, though,
10019   // so we immediately truncate it.
10020   APInt AD = A.lshr(Mult2).zext(BW + 1);  // AD = A / D
10021   APInt Mod(BW + 1, 0);
10022   Mod.setBit(BW - Mult2);  // Mod = N / D
10023   APInt I = AD.multiplicativeInverse(Mod).trunc(BW);
10024 
10025   // 4. Compute the minimum unsigned root of the equation:
10026   // I * (B / D) mod (N / D)
10027   // To simplify the computation, we factor out the divide by D:
10028   // (I * B mod N) / D
10029   const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
10030   return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
10031 }
10032 
10033 /// For a given quadratic addrec, generate coefficients of the corresponding
10034 /// quadratic equation, multiplied by a common value to ensure that they are
10035 /// integers.
10036 /// The returned value is a tuple { A, B, C, M, BitWidth }, where
10037 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C
10038 /// were multiplied by, and BitWidth is the bit width of the original addrec
10039 /// coefficients.
10040 /// This function returns std::nullopt if the addrec coefficients are not
10041 /// compile- time constants.
10042 static std::optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>>
10043 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) {
10044   assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
10045   const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
10046   const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
10047   const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
10048   LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: "
10049                     << *AddRec << '\n');
10050 
10051   // We currently can only solve this if the coefficients are constants.
10052   if (!LC || !MC || !NC) {
10053     LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n");
10054     return std::nullopt;
10055   }
10056 
10057   APInt L = LC->getAPInt();
10058   APInt M = MC->getAPInt();
10059   APInt N = NC->getAPInt();
10060   assert(!N.isZero() && "This is not a quadratic addrec");
10061 
10062   unsigned BitWidth = LC->getAPInt().getBitWidth();
10063   unsigned NewWidth = BitWidth + 1;
10064   LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: "
10065                     << BitWidth << '\n');
10066   // The sign-extension (as opposed to a zero-extension) here matches the
10067   // extension used in SolveQuadraticEquationWrap (with the same motivation).
10068   N = N.sext(NewWidth);
10069   M = M.sext(NewWidth);
10070   L = L.sext(NewWidth);
10071 
10072   // The increments are M, M+N, M+2N, ..., so the accumulated values are
10073   //   L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is,
10074   //   L+M, L+2M+N, L+3M+3N, ...
10075   // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N.
10076   //
10077   // The equation Acc = 0 is then
10078   //   L + nM + n(n-1)/2 N = 0,  or  2L + 2M n + n(n-1) N = 0.
10079   // In a quadratic form it becomes:
10080   //   N n^2 + (2M-N) n + 2L = 0.
10081 
10082   APInt A = N;
10083   APInt B = 2 * M - A;
10084   APInt C = 2 * L;
10085   APInt T = APInt(NewWidth, 2);
10086   LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B
10087                     << "x + " << C << ", coeff bw: " << NewWidth
10088                     << ", multiplied by " << T << '\n');
10089   return std::make_tuple(A, B, C, T, BitWidth);
10090 }
10091 
10092 /// Helper function to compare optional APInts:
10093 /// (a) if X and Y both exist, return min(X, Y),
10094 /// (b) if neither X nor Y exist, return std::nullopt,
10095 /// (c) if exactly one of X and Y exists, return that value.
10096 static std::optional<APInt> MinOptional(std::optional<APInt> X,
10097                                         std::optional<APInt> Y) {
10098   if (X && Y) {
10099     unsigned W = std::max(X->getBitWidth(), Y->getBitWidth());
10100     APInt XW = X->sext(W);
10101     APInt YW = Y->sext(W);
10102     return XW.slt(YW) ? *X : *Y;
10103   }
10104   if (!X && !Y)
10105     return std::nullopt;
10106   return X ? *X : *Y;
10107 }
10108 
10109 /// Helper function to truncate an optional APInt to a given BitWidth.
10110 /// When solving addrec-related equations, it is preferable to return a value
10111 /// that has the same bit width as the original addrec's coefficients. If the
10112 /// solution fits in the original bit width, truncate it (except for i1).
10113 /// Returning a value of a different bit width may inhibit some optimizations.
10114 ///
10115 /// In general, a solution to a quadratic equation generated from an addrec
10116 /// may require BW+1 bits, where BW is the bit width of the addrec's
10117 /// coefficients. The reason is that the coefficients of the quadratic
10118 /// equation are BW+1 bits wide (to avoid truncation when converting from
10119 /// the addrec to the equation).
10120 static std::optional<APInt> TruncIfPossible(std::optional<APInt> X,
10121                                             unsigned BitWidth) {
10122   if (!X)
10123     return std::nullopt;
10124   unsigned W = X->getBitWidth();
10125   if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth))
10126     return X->trunc(BitWidth);
10127   return X;
10128 }
10129 
10130 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n
10131 /// iterations. The values L, M, N are assumed to be signed, and they
10132 /// should all have the same bit widths.
10133 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW,
10134 /// where BW is the bit width of the addrec's coefficients.
10135 /// If the calculated value is a BW-bit integer (for BW > 1), it will be
10136 /// returned as such, otherwise the bit width of the returned value may
10137 /// be greater than BW.
10138 ///
10139 /// This function returns std::nullopt if
10140 /// (a) the addrec coefficients are not constant, or
10141 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases
10142 ///     like x^2 = 5, no integer solutions exist, in other cases an integer
10143 ///     solution may exist, but SolveQuadraticEquationWrap may fail to find it.
10144 static std::optional<APInt>
10145 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
10146   APInt A, B, C, M;
10147   unsigned BitWidth;
10148   auto T = GetQuadraticEquation(AddRec);
10149   if (!T)
10150     return std::nullopt;
10151 
10152   std::tie(A, B, C, M, BitWidth) = *T;
10153   LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n");
10154   std::optional<APInt> X =
10155       APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth + 1);
10156   if (!X)
10157     return std::nullopt;
10158 
10159   ConstantInt *CX = ConstantInt::get(SE.getContext(), *X);
10160   ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE);
10161   if (!V->isZero())
10162     return std::nullopt;
10163 
10164   return TruncIfPossible(X, BitWidth);
10165 }
10166 
10167 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n
10168 /// iterations. The values M, N are assumed to be signed, and they
10169 /// should all have the same bit widths.
10170 /// Find the least n such that c(n) does not belong to the given range,
10171 /// while c(n-1) does.
10172 ///
10173 /// This function returns std::nullopt if
10174 /// (a) the addrec coefficients are not constant, or
10175 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the
10176 ///     bounds of the range.
10177 static std::optional<APInt>
10178 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec,
10179                           const ConstantRange &Range, ScalarEvolution &SE) {
10180   assert(AddRec->getOperand(0)->isZero() &&
10181          "Starting value of addrec should be 0");
10182   LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range "
10183                     << Range << ", addrec " << *AddRec << '\n');
10184   // This case is handled in getNumIterationsInRange. Here we can assume that
10185   // we start in the range.
10186   assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) &&
10187          "Addrec's initial value should be in range");
10188 
10189   APInt A, B, C, M;
10190   unsigned BitWidth;
10191   auto T = GetQuadraticEquation(AddRec);
10192   if (!T)
10193     return std::nullopt;
10194 
10195   // Be careful about the return value: there can be two reasons for not
10196   // returning an actual number. First, if no solutions to the equations
10197   // were found, and second, if the solutions don't leave the given range.
10198   // The first case means that the actual solution is "unknown", the second
10199   // means that it's known, but not valid. If the solution is unknown, we
10200   // cannot make any conclusions.
10201   // Return a pair: the optional solution and a flag indicating if the
10202   // solution was found.
10203   auto SolveForBoundary =
10204       [&](APInt Bound) -> std::pair<std::optional<APInt>, bool> {
10205     // Solve for signed overflow and unsigned overflow, pick the lower
10206     // solution.
10207     LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary "
10208                       << Bound << " (before multiplying by " << M << ")\n");
10209     Bound *= M; // The quadratic equation multiplier.
10210 
10211     std::optional<APInt> SO;
10212     if (BitWidth > 1) {
10213       LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
10214                            "signed overflow\n");
10215       SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth);
10216     }
10217     LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
10218                          "unsigned overflow\n");
10219     std::optional<APInt> UO =
10220         APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth + 1);
10221 
10222     auto LeavesRange = [&] (const APInt &X) {
10223       ConstantInt *C0 = ConstantInt::get(SE.getContext(), X);
10224       ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE);
10225       if (Range.contains(V0->getValue()))
10226         return false;
10227       // X should be at least 1, so X-1 is non-negative.
10228       ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1);
10229       ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE);
10230       if (Range.contains(V1->getValue()))
10231         return true;
10232       return false;
10233     };
10234 
10235     // If SolveQuadraticEquationWrap returns std::nullopt, it means that there
10236     // can be a solution, but the function failed to find it. We cannot treat it
10237     // as "no solution".
10238     if (!SO || !UO)
10239       return {std::nullopt, false};
10240 
10241     // Check the smaller value first to see if it leaves the range.
10242     // At this point, both SO and UO must have values.
10243     std::optional<APInt> Min = MinOptional(SO, UO);
10244     if (LeavesRange(*Min))
10245       return { Min, true };
10246     std::optional<APInt> Max = Min == SO ? UO : SO;
10247     if (LeavesRange(*Max))
10248       return { Max, true };
10249 
10250     // Solutions were found, but were eliminated, hence the "true".
10251     return {std::nullopt, true};
10252   };
10253 
10254   std::tie(A, B, C, M, BitWidth) = *T;
10255   // Lower bound is inclusive, subtract 1 to represent the exiting value.
10256   APInt Lower = Range.getLower().sext(A.getBitWidth()) - 1;
10257   APInt Upper = Range.getUpper().sext(A.getBitWidth());
10258   auto SL = SolveForBoundary(Lower);
10259   auto SU = SolveForBoundary(Upper);
10260   // If any of the solutions was unknown, no meaninigful conclusions can
10261   // be made.
10262   if (!SL.second || !SU.second)
10263     return std::nullopt;
10264 
10265   // Claim: The correct solution is not some value between Min and Max.
10266   //
10267   // Justification: Assuming that Min and Max are different values, one of
10268   // them is when the first signed overflow happens, the other is when the
10269   // first unsigned overflow happens. Crossing the range boundary is only
10270   // possible via an overflow (treating 0 as a special case of it, modeling
10271   // an overflow as crossing k*2^W for some k).
10272   //
10273   // The interesting case here is when Min was eliminated as an invalid
10274   // solution, but Max was not. The argument is that if there was another
10275   // overflow between Min and Max, it would also have been eliminated if
10276   // it was considered.
10277   //
10278   // For a given boundary, it is possible to have two overflows of the same
10279   // type (signed/unsigned) without having the other type in between: this
10280   // can happen when the vertex of the parabola is between the iterations
10281   // corresponding to the overflows. This is only possible when the two
10282   // overflows cross k*2^W for the same k. In such case, if the second one
10283   // left the range (and was the first one to do so), the first overflow
10284   // would have to enter the range, which would mean that either we had left
10285   // the range before or that we started outside of it. Both of these cases
10286   // are contradictions.
10287   //
10288   // Claim: In the case where SolveForBoundary returns std::nullopt, the correct
10289   // solution is not some value between the Max for this boundary and the
10290   // Min of the other boundary.
10291   //
10292   // Justification: Assume that we had such Max_A and Min_B corresponding
10293   // to range boundaries A and B and such that Max_A < Min_B. If there was
10294   // a solution between Max_A and Min_B, it would have to be caused by an
10295   // overflow corresponding to either A or B. It cannot correspond to B,
10296   // since Min_B is the first occurrence of such an overflow. If it
10297   // corresponded to A, it would have to be either a signed or an unsigned
10298   // overflow that is larger than both eliminated overflows for A. But
10299   // between the eliminated overflows and this overflow, the values would
10300   // cover the entire value space, thus crossing the other boundary, which
10301   // is a contradiction.
10302 
10303   return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth);
10304 }
10305 
10306 ScalarEvolution::ExitLimit ScalarEvolution::howFarToZero(const SCEV *V,
10307                                                          const Loop *L,
10308                                                          bool ControlsOnlyExit,
10309                                                          bool AllowPredicates) {
10310 
10311   // This is only used for loops with a "x != y" exit test. The exit condition
10312   // is now expressed as a single expression, V = x-y. So the exit test is
10313   // effectively V != 0.  We know and take advantage of the fact that this
10314   // expression only being used in a comparison by zero context.
10315 
10316   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
10317   // If the value is a constant
10318   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
10319     // If the value is already zero, the branch will execute zero times.
10320     if (C->getValue()->isZero()) return C;
10321     return getCouldNotCompute();  // Otherwise it will loop infinitely.
10322   }
10323 
10324   const SCEVAddRecExpr *AddRec =
10325       dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V));
10326 
10327   if (!AddRec && AllowPredicates)
10328     // Try to make this an AddRec using runtime tests, in the first X
10329     // iterations of this loop, where X is the SCEV expression found by the
10330     // algorithm below.
10331     AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
10332 
10333   if (!AddRec || AddRec->getLoop() != L)
10334     return getCouldNotCompute();
10335 
10336   // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
10337   // the quadratic equation to solve it.
10338   if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
10339     // We can only use this value if the chrec ends up with an exact zero
10340     // value at this index.  When solving for "X*X != 5", for example, we
10341     // should not accept a root of 2.
10342     if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) {
10343       const auto *R = cast<SCEVConstant>(getConstant(*S));
10344       return ExitLimit(R, R, R, false, Predicates);
10345     }
10346     return getCouldNotCompute();
10347   }
10348 
10349   // Otherwise we can only handle this if it is affine.
10350   if (!AddRec->isAffine())
10351     return getCouldNotCompute();
10352 
10353   // If this is an affine expression, the execution count of this branch is
10354   // the minimum unsigned root of the following equation:
10355   //
10356   //     Start + Step*N = 0 (mod 2^BW)
10357   //
10358   // equivalent to:
10359   //
10360   //             Step*N = -Start (mod 2^BW)
10361   //
10362   // where BW is the common bit width of Start and Step.
10363 
10364   // Get the initial value for the loop.
10365   const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
10366   const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
10367 
10368   // For now we handle only constant steps.
10369   //
10370   // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
10371   // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
10372   // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
10373   // We have not yet seen any such cases.
10374   const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
10375   if (!StepC || StepC->getValue()->isZero())
10376     return getCouldNotCompute();
10377 
10378   // For positive steps (counting up until unsigned overflow):
10379   //   N = -Start/Step (as unsigned)
10380   // For negative steps (counting down to zero):
10381   //   N = Start/-Step
10382   // First compute the unsigned distance from zero in the direction of Step.
10383   bool CountDown = StepC->getAPInt().isNegative();
10384   const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
10385 
10386   // Handle unitary steps, which cannot wraparound.
10387   // 1*N = -Start; -1*N = Start (mod 2^BW), so:
10388   //   N = Distance (as unsigned)
10389   if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) {
10390     APInt MaxBECount = getUnsignedRangeMax(applyLoopGuards(Distance, L));
10391     MaxBECount = APIntOps::umin(MaxBECount, getUnsignedRangeMax(Distance));
10392 
10393     // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
10394     // we end up with a loop whose backedge-taken count is n - 1.  Detect this
10395     // case, and see if we can improve the bound.
10396     //
10397     // Explicitly handling this here is necessary because getUnsignedRange
10398     // isn't context-sensitive; it doesn't know that we only care about the
10399     // range inside the loop.
10400     const SCEV *Zero = getZero(Distance->getType());
10401     const SCEV *One = getOne(Distance->getType());
10402     const SCEV *DistancePlusOne = getAddExpr(Distance, One);
10403     if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
10404       // If Distance + 1 doesn't overflow, we can compute the maximum distance
10405       // as "unsigned_max(Distance + 1) - 1".
10406       ConstantRange CR = getUnsignedRange(DistancePlusOne);
10407       MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1);
10408     }
10409     return ExitLimit(Distance, getConstant(MaxBECount), Distance, false,
10410                      Predicates);
10411   }
10412 
10413   // If the condition controls loop exit (the loop exits only if the expression
10414   // is true) and the addition is no-wrap we can use unsigned divide to
10415   // compute the backedge count.  In this case, the step may not divide the
10416   // distance, but we don't care because if the condition is "missed" the loop
10417   // will have undefined behavior due to wrapping.
10418   if (ControlsOnlyExit && AddRec->hasNoSelfWrap() &&
10419       loopHasNoAbnormalExits(AddRec->getLoop())) {
10420     const SCEV *Exact =
10421         getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
10422     const SCEV *ConstantMax = getCouldNotCompute();
10423     if (Exact != getCouldNotCompute()) {
10424       APInt MaxInt = getUnsignedRangeMax(applyLoopGuards(Exact, L));
10425       ConstantMax =
10426           getConstant(APIntOps::umin(MaxInt, getUnsignedRangeMax(Exact)));
10427     }
10428     const SCEV *SymbolicMax =
10429         isa<SCEVCouldNotCompute>(Exact) ? ConstantMax : Exact;
10430     return ExitLimit(Exact, ConstantMax, SymbolicMax, false, Predicates);
10431   }
10432 
10433   // Solve the general equation.
10434   const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(),
10435                                                getNegativeSCEV(Start), *this);
10436 
10437   const SCEV *M = E;
10438   if (E != getCouldNotCompute()) {
10439     APInt MaxWithGuards = getUnsignedRangeMax(applyLoopGuards(E, L));
10440     M = getConstant(APIntOps::umin(MaxWithGuards, getUnsignedRangeMax(E)));
10441   }
10442   auto *S = isa<SCEVCouldNotCompute>(E) ? M : E;
10443   return ExitLimit(E, M, S, false, Predicates);
10444 }
10445 
10446 ScalarEvolution::ExitLimit
10447 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
10448   // Loops that look like: while (X == 0) are very strange indeed.  We don't
10449   // handle them yet except for the trivial case.  This could be expanded in the
10450   // future as needed.
10451 
10452   // If the value is a constant, check to see if it is known to be non-zero
10453   // already.  If so, the backedge will execute zero times.
10454   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
10455     if (!C->getValue()->isZero())
10456       return getZero(C->getType());
10457     return getCouldNotCompute();  // Otherwise it will loop infinitely.
10458   }
10459 
10460   // We could implement others, but I really doubt anyone writes loops like
10461   // this, and if they did, they would already be constant folded.
10462   return getCouldNotCompute();
10463 }
10464 
10465 std::pair<const BasicBlock *, const BasicBlock *>
10466 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB)
10467     const {
10468   // If the block has a unique predecessor, then there is no path from the
10469   // predecessor to the block that does not go through the direct edge
10470   // from the predecessor to the block.
10471   if (const BasicBlock *Pred = BB->getSinglePredecessor())
10472     return {Pred, BB};
10473 
10474   // A loop's header is defined to be a block that dominates the loop.
10475   // If the header has a unique predecessor outside the loop, it must be
10476   // a block that has exactly one successor that can reach the loop.
10477   if (const Loop *L = LI.getLoopFor(BB))
10478     return {L->getLoopPredecessor(), L->getHeader()};
10479 
10480   return {nullptr, nullptr};
10481 }
10482 
10483 /// SCEV structural equivalence is usually sufficient for testing whether two
10484 /// expressions are equal, however for the purposes of looking for a condition
10485 /// guarding a loop, it can be useful to be a little more general, since a
10486 /// front-end may have replicated the controlling expression.
10487 static bool HasSameValue(const SCEV *A, const SCEV *B) {
10488   // Quick check to see if they are the same SCEV.
10489   if (A == B) return true;
10490 
10491   auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
10492     // Not all instructions that are "identical" compute the same value.  For
10493     // instance, two distinct alloca instructions allocating the same type are
10494     // identical and do not read memory; but compute distinct values.
10495     return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
10496   };
10497 
10498   // Otherwise, if they're both SCEVUnknown, it's possible that they hold
10499   // two different instructions with the same value. Check for this case.
10500   if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
10501     if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
10502       if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
10503         if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
10504           if (ComputesEqualValues(AI, BI))
10505             return true;
10506 
10507   // Otherwise assume they may have a different value.
10508   return false;
10509 }
10510 
10511 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
10512                                            const SCEV *&LHS, const SCEV *&RHS,
10513                                            unsigned Depth) {
10514   bool Changed = false;
10515   // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or
10516   // '0 != 0'.
10517   auto TrivialCase = [&](bool TriviallyTrue) {
10518     LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
10519     Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
10520     return true;
10521   };
10522   // If we hit the max recursion limit bail out.
10523   if (Depth >= 3)
10524     return false;
10525 
10526   // Canonicalize a constant to the right side.
10527   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
10528     // Check for both operands constant.
10529     if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
10530       if (ConstantExpr::getICmp(Pred,
10531                                 LHSC->getValue(),
10532                                 RHSC->getValue())->isNullValue())
10533         return TrivialCase(false);
10534       return TrivialCase(true);
10535     }
10536     // Otherwise swap the operands to put the constant on the right.
10537     std::swap(LHS, RHS);
10538     Pred = ICmpInst::getSwappedPredicate(Pred);
10539     Changed = true;
10540   }
10541 
10542   // If we're comparing an addrec with a value which is loop-invariant in the
10543   // addrec's loop, put the addrec on the left. Also make a dominance check,
10544   // as both operands could be addrecs loop-invariant in each other's loop.
10545   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
10546     const Loop *L = AR->getLoop();
10547     if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
10548       std::swap(LHS, RHS);
10549       Pred = ICmpInst::getSwappedPredicate(Pred);
10550       Changed = true;
10551     }
10552   }
10553 
10554   // If there's a constant operand, canonicalize comparisons with boundary
10555   // cases, and canonicalize *-or-equal comparisons to regular comparisons.
10556   if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
10557     const APInt &RA = RC->getAPInt();
10558 
10559     bool SimplifiedByConstantRange = false;
10560 
10561     if (!ICmpInst::isEquality(Pred)) {
10562       ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA);
10563       if (ExactCR.isFullSet())
10564         return TrivialCase(true);
10565       if (ExactCR.isEmptySet())
10566         return TrivialCase(false);
10567 
10568       APInt NewRHS;
10569       CmpInst::Predicate NewPred;
10570       if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
10571           ICmpInst::isEquality(NewPred)) {
10572         // We were able to convert an inequality to an equality.
10573         Pred = NewPred;
10574         RHS = getConstant(NewRHS);
10575         Changed = SimplifiedByConstantRange = true;
10576       }
10577     }
10578 
10579     if (!SimplifiedByConstantRange) {
10580       switch (Pred) {
10581       default:
10582         break;
10583       case ICmpInst::ICMP_EQ:
10584       case ICmpInst::ICMP_NE:
10585         // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
10586         if (!RA)
10587           if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
10588             if (const SCEVMulExpr *ME =
10589                     dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
10590               if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
10591                   ME->getOperand(0)->isAllOnesValue()) {
10592                 RHS = AE->getOperand(1);
10593                 LHS = ME->getOperand(1);
10594                 Changed = true;
10595               }
10596         break;
10597 
10598 
10599         // The "Should have been caught earlier!" messages refer to the fact
10600         // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
10601         // should have fired on the corresponding cases, and canonicalized the
10602         // check to trivial case.
10603 
10604       case ICmpInst::ICMP_UGE:
10605         assert(!RA.isMinValue() && "Should have been caught earlier!");
10606         Pred = ICmpInst::ICMP_UGT;
10607         RHS = getConstant(RA - 1);
10608         Changed = true;
10609         break;
10610       case ICmpInst::ICMP_ULE:
10611         assert(!RA.isMaxValue() && "Should have been caught earlier!");
10612         Pred = ICmpInst::ICMP_ULT;
10613         RHS = getConstant(RA + 1);
10614         Changed = true;
10615         break;
10616       case ICmpInst::ICMP_SGE:
10617         assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
10618         Pred = ICmpInst::ICMP_SGT;
10619         RHS = getConstant(RA - 1);
10620         Changed = true;
10621         break;
10622       case ICmpInst::ICMP_SLE:
10623         assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
10624         Pred = ICmpInst::ICMP_SLT;
10625         RHS = getConstant(RA + 1);
10626         Changed = true;
10627         break;
10628       }
10629     }
10630   }
10631 
10632   // Check for obvious equality.
10633   if (HasSameValue(LHS, RHS)) {
10634     if (ICmpInst::isTrueWhenEqual(Pred))
10635       return TrivialCase(true);
10636     if (ICmpInst::isFalseWhenEqual(Pred))
10637       return TrivialCase(false);
10638   }
10639 
10640   // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
10641   // adding or subtracting 1 from one of the operands.
10642   switch (Pred) {
10643   case ICmpInst::ICMP_SLE:
10644     if (!getSignedRangeMax(RHS).isMaxSignedValue()) {
10645       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
10646                        SCEV::FlagNSW);
10647       Pred = ICmpInst::ICMP_SLT;
10648       Changed = true;
10649     } else if (!getSignedRangeMin(LHS).isMinSignedValue()) {
10650       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
10651                        SCEV::FlagNSW);
10652       Pred = ICmpInst::ICMP_SLT;
10653       Changed = true;
10654     }
10655     break;
10656   case ICmpInst::ICMP_SGE:
10657     if (!getSignedRangeMin(RHS).isMinSignedValue()) {
10658       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
10659                        SCEV::FlagNSW);
10660       Pred = ICmpInst::ICMP_SGT;
10661       Changed = true;
10662     } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) {
10663       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
10664                        SCEV::FlagNSW);
10665       Pred = ICmpInst::ICMP_SGT;
10666       Changed = true;
10667     }
10668     break;
10669   case ICmpInst::ICMP_ULE:
10670     if (!getUnsignedRangeMax(RHS).isMaxValue()) {
10671       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
10672                        SCEV::FlagNUW);
10673       Pred = ICmpInst::ICMP_ULT;
10674       Changed = true;
10675     } else if (!getUnsignedRangeMin(LHS).isMinValue()) {
10676       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
10677       Pred = ICmpInst::ICMP_ULT;
10678       Changed = true;
10679     }
10680     break;
10681   case ICmpInst::ICMP_UGE:
10682     if (!getUnsignedRangeMin(RHS).isMinValue()) {
10683       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
10684       Pred = ICmpInst::ICMP_UGT;
10685       Changed = true;
10686     } else if (!getUnsignedRangeMax(LHS).isMaxValue()) {
10687       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
10688                        SCEV::FlagNUW);
10689       Pred = ICmpInst::ICMP_UGT;
10690       Changed = true;
10691     }
10692     break;
10693   default:
10694     break;
10695   }
10696 
10697   // TODO: More simplifications are possible here.
10698 
10699   // Recursively simplify until we either hit a recursion limit or nothing
10700   // changes.
10701   if (Changed)
10702     return SimplifyICmpOperands(Pred, LHS, RHS, Depth + 1);
10703 
10704   return Changed;
10705 }
10706 
10707 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
10708   return getSignedRangeMax(S).isNegative();
10709 }
10710 
10711 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
10712   return getSignedRangeMin(S).isStrictlyPositive();
10713 }
10714 
10715 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
10716   return !getSignedRangeMin(S).isNegative();
10717 }
10718 
10719 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
10720   return !getSignedRangeMax(S).isStrictlyPositive();
10721 }
10722 
10723 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
10724   return getUnsignedRangeMin(S) != 0;
10725 }
10726 
10727 std::pair<const SCEV *, const SCEV *>
10728 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) {
10729   // Compute SCEV on entry of loop L.
10730   const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this);
10731   if (Start == getCouldNotCompute())
10732     return { Start, Start };
10733   // Compute post increment SCEV for loop L.
10734   const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this);
10735   assert(PostInc != getCouldNotCompute() && "Unexpected could not compute");
10736   return { Start, PostInc };
10737 }
10738 
10739 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred,
10740                                           const SCEV *LHS, const SCEV *RHS) {
10741   // First collect all loops.
10742   SmallPtrSet<const Loop *, 8> LoopsUsed;
10743   getUsedLoops(LHS, LoopsUsed);
10744   getUsedLoops(RHS, LoopsUsed);
10745 
10746   if (LoopsUsed.empty())
10747     return false;
10748 
10749   // Domination relationship must be a linear order on collected loops.
10750 #ifndef NDEBUG
10751   for (const auto *L1 : LoopsUsed)
10752     for (const auto *L2 : LoopsUsed)
10753       assert((DT.dominates(L1->getHeader(), L2->getHeader()) ||
10754               DT.dominates(L2->getHeader(), L1->getHeader())) &&
10755              "Domination relationship is not a linear order");
10756 #endif
10757 
10758   const Loop *MDL =
10759       *std::max_element(LoopsUsed.begin(), LoopsUsed.end(),
10760                         [&](const Loop *L1, const Loop *L2) {
10761          return DT.properlyDominates(L1->getHeader(), L2->getHeader());
10762        });
10763 
10764   // Get init and post increment value for LHS.
10765   auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS);
10766   // if LHS contains unknown non-invariant SCEV then bail out.
10767   if (SplitLHS.first == getCouldNotCompute())
10768     return false;
10769   assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC");
10770   // Get init and post increment value for RHS.
10771   auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS);
10772   // if RHS contains unknown non-invariant SCEV then bail out.
10773   if (SplitRHS.first == getCouldNotCompute())
10774     return false;
10775   assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC");
10776   // It is possible that init SCEV contains an invariant load but it does
10777   // not dominate MDL and is not available at MDL loop entry, so we should
10778   // check it here.
10779   if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) ||
10780       !isAvailableAtLoopEntry(SplitRHS.first, MDL))
10781     return false;
10782 
10783   // It seems backedge guard check is faster than entry one so in some cases
10784   // it can speed up whole estimation by short circuit
10785   return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second,
10786                                      SplitRHS.second) &&
10787          isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first);
10788 }
10789 
10790 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
10791                                        const SCEV *LHS, const SCEV *RHS) {
10792   // Canonicalize the inputs first.
10793   (void)SimplifyICmpOperands(Pred, LHS, RHS);
10794 
10795   if (isKnownViaInduction(Pred, LHS, RHS))
10796     return true;
10797 
10798   if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
10799     return true;
10800 
10801   // Otherwise see what can be done with some simple reasoning.
10802   return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS);
10803 }
10804 
10805 std::optional<bool> ScalarEvolution::evaluatePredicate(ICmpInst::Predicate Pred,
10806                                                        const SCEV *LHS,
10807                                                        const SCEV *RHS) {
10808   if (isKnownPredicate(Pred, LHS, RHS))
10809     return true;
10810   if (isKnownPredicate(ICmpInst::getInversePredicate(Pred), LHS, RHS))
10811     return false;
10812   return std::nullopt;
10813 }
10814 
10815 bool ScalarEvolution::isKnownPredicateAt(ICmpInst::Predicate Pred,
10816                                          const SCEV *LHS, const SCEV *RHS,
10817                                          const Instruction *CtxI) {
10818   // TODO: Analyze guards and assumes from Context's block.
10819   return isKnownPredicate(Pred, LHS, RHS) ||
10820          isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS);
10821 }
10822 
10823 std::optional<bool>
10824 ScalarEvolution::evaluatePredicateAt(ICmpInst::Predicate Pred, const SCEV *LHS,
10825                                      const SCEV *RHS, const Instruction *CtxI) {
10826   std::optional<bool> KnownWithoutContext = evaluatePredicate(Pred, LHS, RHS);
10827   if (KnownWithoutContext)
10828     return KnownWithoutContext;
10829 
10830   if (isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS))
10831     return true;
10832   if (isBasicBlockEntryGuardedByCond(CtxI->getParent(),
10833                                           ICmpInst::getInversePredicate(Pred),
10834                                           LHS, RHS))
10835     return false;
10836   return std::nullopt;
10837 }
10838 
10839 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred,
10840                                               const SCEVAddRecExpr *LHS,
10841                                               const SCEV *RHS) {
10842   const Loop *L = LHS->getLoop();
10843   return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) &&
10844          isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS);
10845 }
10846 
10847 std::optional<ScalarEvolution::MonotonicPredicateType>
10848 ScalarEvolution::getMonotonicPredicateType(const SCEVAddRecExpr *LHS,
10849                                            ICmpInst::Predicate Pred) {
10850   auto Result = getMonotonicPredicateTypeImpl(LHS, Pred);
10851 
10852 #ifndef NDEBUG
10853   // Verify an invariant: inverting the predicate should turn a monotonically
10854   // increasing change to a monotonically decreasing one, and vice versa.
10855   if (Result) {
10856     auto ResultSwapped =
10857         getMonotonicPredicateTypeImpl(LHS, ICmpInst::getSwappedPredicate(Pred));
10858 
10859     assert(*ResultSwapped != *Result &&
10860            "monotonicity should flip as we flip the predicate");
10861   }
10862 #endif
10863 
10864   return Result;
10865 }
10866 
10867 std::optional<ScalarEvolution::MonotonicPredicateType>
10868 ScalarEvolution::getMonotonicPredicateTypeImpl(const SCEVAddRecExpr *LHS,
10869                                                ICmpInst::Predicate Pred) {
10870   // A zero step value for LHS means the induction variable is essentially a
10871   // loop invariant value. We don't really depend on the predicate actually
10872   // flipping from false to true (for increasing predicates, and the other way
10873   // around for decreasing predicates), all we care about is that *if* the
10874   // predicate changes then it only changes from false to true.
10875   //
10876   // A zero step value in itself is not very useful, but there may be places
10877   // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
10878   // as general as possible.
10879 
10880   // Only handle LE/LT/GE/GT predicates.
10881   if (!ICmpInst::isRelational(Pred))
10882     return std::nullopt;
10883 
10884   bool IsGreater = ICmpInst::isGE(Pred) || ICmpInst::isGT(Pred);
10885   assert((IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) &&
10886          "Should be greater or less!");
10887 
10888   // Check that AR does not wrap.
10889   if (ICmpInst::isUnsigned(Pred)) {
10890     if (!LHS->hasNoUnsignedWrap())
10891       return std::nullopt;
10892     return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
10893   }
10894   assert(ICmpInst::isSigned(Pred) &&
10895          "Relational predicate is either signed or unsigned!");
10896   if (!LHS->hasNoSignedWrap())
10897     return std::nullopt;
10898 
10899   const SCEV *Step = LHS->getStepRecurrence(*this);
10900 
10901   if (isKnownNonNegative(Step))
10902     return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
10903 
10904   if (isKnownNonPositive(Step))
10905     return !IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
10906 
10907   return std::nullopt;
10908 }
10909 
10910 std::optional<ScalarEvolution::LoopInvariantPredicate>
10911 ScalarEvolution::getLoopInvariantPredicate(ICmpInst::Predicate Pred,
10912                                            const SCEV *LHS, const SCEV *RHS,
10913                                            const Loop *L,
10914                                            const Instruction *CtxI) {
10915   // If there is a loop-invariant, force it into the RHS, otherwise bail out.
10916   if (!isLoopInvariant(RHS, L)) {
10917     if (!isLoopInvariant(LHS, L))
10918       return std::nullopt;
10919 
10920     std::swap(LHS, RHS);
10921     Pred = ICmpInst::getSwappedPredicate(Pred);
10922   }
10923 
10924   const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
10925   if (!ArLHS || ArLHS->getLoop() != L)
10926     return std::nullopt;
10927 
10928   auto MonotonicType = getMonotonicPredicateType(ArLHS, Pred);
10929   if (!MonotonicType)
10930     return std::nullopt;
10931   // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
10932   // true as the loop iterates, and the backedge is control dependent on
10933   // "ArLHS `Pred` RHS" == true then we can reason as follows:
10934   //
10935   //   * if the predicate was false in the first iteration then the predicate
10936   //     is never evaluated again, since the loop exits without taking the
10937   //     backedge.
10938   //   * if the predicate was true in the first iteration then it will
10939   //     continue to be true for all future iterations since it is
10940   //     monotonically increasing.
10941   //
10942   // For both the above possibilities, we can replace the loop varying
10943   // predicate with its value on the first iteration of the loop (which is
10944   // loop invariant).
10945   //
10946   // A similar reasoning applies for a monotonically decreasing predicate, by
10947   // replacing true with false and false with true in the above two bullets.
10948   bool Increasing = *MonotonicType == ScalarEvolution::MonotonicallyIncreasing;
10949   auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
10950 
10951   if (isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
10952     return ScalarEvolution::LoopInvariantPredicate(Pred, ArLHS->getStart(),
10953                                                    RHS);
10954 
10955   if (!CtxI)
10956     return std::nullopt;
10957   // Try to prove via context.
10958   // TODO: Support other cases.
10959   switch (Pred) {
10960   default:
10961     break;
10962   case ICmpInst::ICMP_ULE:
10963   case ICmpInst::ICMP_ULT: {
10964     assert(ArLHS->hasNoUnsignedWrap() && "Is a requirement of monotonicity!");
10965     // Given preconditions
10966     // (1) ArLHS does not cross the border of positive and negative parts of
10967     //     range because of:
10968     //     - Positive step; (TODO: lift this limitation)
10969     //     - nuw - does not cross zero boundary;
10970     //     - nsw - does not cross SINT_MAX boundary;
10971     // (2) ArLHS <s RHS
10972     // (3) RHS >=s 0
10973     // we can replace the loop variant ArLHS <u RHS condition with loop
10974     // invariant Start(ArLHS) <u RHS.
10975     //
10976     // Because of (1) there are two options:
10977     // - ArLHS is always negative. It means that ArLHS <u RHS is always false;
10978     // - ArLHS is always non-negative. Because of (3) RHS is also non-negative.
10979     //   It means that ArLHS <s RHS <=> ArLHS <u RHS.
10980     //   Because of (2) ArLHS <u RHS is trivially true.
10981     // All together it means that ArLHS <u RHS <=> Start(ArLHS) >=s 0.
10982     // We can strengthen this to Start(ArLHS) <u RHS.
10983     auto SignFlippedPred = ICmpInst::getFlippedSignednessPredicate(Pred);
10984     if (ArLHS->hasNoSignedWrap() && ArLHS->isAffine() &&
10985         isKnownPositive(ArLHS->getStepRecurrence(*this)) &&
10986         isKnownNonNegative(RHS) &&
10987         isKnownPredicateAt(SignFlippedPred, ArLHS, RHS, CtxI))
10988       return ScalarEvolution::LoopInvariantPredicate(Pred, ArLHS->getStart(),
10989                                                      RHS);
10990   }
10991   }
10992 
10993   return std::nullopt;
10994 }
10995 
10996 std::optional<ScalarEvolution::LoopInvariantPredicate>
10997 ScalarEvolution::getLoopInvariantExitCondDuringFirstIterations(
10998     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
10999     const Instruction *CtxI, const SCEV *MaxIter) {
11000   if (auto LIP = getLoopInvariantExitCondDuringFirstIterationsImpl(
11001           Pred, LHS, RHS, L, CtxI, MaxIter))
11002     return LIP;
11003   if (auto *UMin = dyn_cast<SCEVUMinExpr>(MaxIter))
11004     // Number of iterations expressed as UMIN isn't always great for expressing
11005     // the value on the last iteration. If the straightforward approach didn't
11006     // work, try the following trick: if the a predicate is invariant for X, it
11007     // is also invariant for umin(X, ...). So try to find something that works
11008     // among subexpressions of MaxIter expressed as umin.
11009     for (auto *Op : UMin->operands())
11010       if (auto LIP = getLoopInvariantExitCondDuringFirstIterationsImpl(
11011               Pred, LHS, RHS, L, CtxI, Op))
11012         return LIP;
11013   return std::nullopt;
11014 }
11015 
11016 std::optional<ScalarEvolution::LoopInvariantPredicate>
11017 ScalarEvolution::getLoopInvariantExitCondDuringFirstIterationsImpl(
11018     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
11019     const Instruction *CtxI, const SCEV *MaxIter) {
11020   // Try to prove the following set of facts:
11021   // - The predicate is monotonic in the iteration space.
11022   // - If the check does not fail on the 1st iteration:
11023   //   - No overflow will happen during first MaxIter iterations;
11024   //   - It will not fail on the MaxIter'th iteration.
11025   // If the check does fail on the 1st iteration, we leave the loop and no
11026   // other checks matter.
11027 
11028   // If there is a loop-invariant, force it into the RHS, otherwise bail out.
11029   if (!isLoopInvariant(RHS, L)) {
11030     if (!isLoopInvariant(LHS, L))
11031       return std::nullopt;
11032 
11033     std::swap(LHS, RHS);
11034     Pred = ICmpInst::getSwappedPredicate(Pred);
11035   }
11036 
11037   auto *AR = dyn_cast<SCEVAddRecExpr>(LHS);
11038   if (!AR || AR->getLoop() != L)
11039     return std::nullopt;
11040 
11041   // The predicate must be relational (i.e. <, <=, >=, >).
11042   if (!ICmpInst::isRelational(Pred))
11043     return std::nullopt;
11044 
11045   // TODO: Support steps other than +/- 1.
11046   const SCEV *Step = AR->getStepRecurrence(*this);
11047   auto *One = getOne(Step->getType());
11048   auto *MinusOne = getNegativeSCEV(One);
11049   if (Step != One && Step != MinusOne)
11050     return std::nullopt;
11051 
11052   // Type mismatch here means that MaxIter is potentially larger than max
11053   // unsigned value in start type, which mean we cannot prove no wrap for the
11054   // indvar.
11055   if (AR->getType() != MaxIter->getType())
11056     return std::nullopt;
11057 
11058   // Value of IV on suggested last iteration.
11059   const SCEV *Last = AR->evaluateAtIteration(MaxIter, *this);
11060   // Does it still meet the requirement?
11061   if (!isLoopBackedgeGuardedByCond(L, Pred, Last, RHS))
11062     return std::nullopt;
11063   // Because step is +/- 1 and MaxIter has same type as Start (i.e. it does
11064   // not exceed max unsigned value of this type), this effectively proves
11065   // that there is no wrap during the iteration. To prove that there is no
11066   // signed/unsigned wrap, we need to check that
11067   // Start <= Last for step = 1 or Start >= Last for step = -1.
11068   ICmpInst::Predicate NoOverflowPred =
11069       CmpInst::isSigned(Pred) ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
11070   if (Step == MinusOne)
11071     NoOverflowPred = CmpInst::getSwappedPredicate(NoOverflowPred);
11072   const SCEV *Start = AR->getStart();
11073   if (!isKnownPredicateAt(NoOverflowPred, Start, Last, CtxI))
11074     return std::nullopt;
11075 
11076   // Everything is fine.
11077   return ScalarEvolution::LoopInvariantPredicate(Pred, Start, RHS);
11078 }
11079 
11080 bool ScalarEvolution::isKnownPredicateViaConstantRanges(
11081     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
11082   if (HasSameValue(LHS, RHS))
11083     return ICmpInst::isTrueWhenEqual(Pred);
11084 
11085   // This code is split out from isKnownPredicate because it is called from
11086   // within isLoopEntryGuardedByCond.
11087 
11088   auto CheckRanges = [&](const ConstantRange &RangeLHS,
11089                          const ConstantRange &RangeRHS) {
11090     return RangeLHS.icmp(Pred, RangeRHS);
11091   };
11092 
11093   // The check at the top of the function catches the case where the values are
11094   // known to be equal.
11095   if (Pred == CmpInst::ICMP_EQ)
11096     return false;
11097 
11098   if (Pred == CmpInst::ICMP_NE) {
11099     auto SL = getSignedRange(LHS);
11100     auto SR = getSignedRange(RHS);
11101     if (CheckRanges(SL, SR))
11102       return true;
11103     auto UL = getUnsignedRange(LHS);
11104     auto UR = getUnsignedRange(RHS);
11105     if (CheckRanges(UL, UR))
11106       return true;
11107     auto *Diff = getMinusSCEV(LHS, RHS);
11108     return !isa<SCEVCouldNotCompute>(Diff) && isKnownNonZero(Diff);
11109   }
11110 
11111   if (CmpInst::isSigned(Pred)) {
11112     auto SL = getSignedRange(LHS);
11113     auto SR = getSignedRange(RHS);
11114     return CheckRanges(SL, SR);
11115   }
11116 
11117   auto UL = getUnsignedRange(LHS);
11118   auto UR = getUnsignedRange(RHS);
11119   return CheckRanges(UL, UR);
11120 }
11121 
11122 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
11123                                                     const SCEV *LHS,
11124                                                     const SCEV *RHS) {
11125   // Match X to (A + C1)<ExpectedFlags> and Y to (A + C2)<ExpectedFlags>, where
11126   // C1 and C2 are constant integers. If either X or Y are not add expressions,
11127   // consider them as X + 0 and Y + 0 respectively. C1 and C2 are returned via
11128   // OutC1 and OutC2.
11129   auto MatchBinaryAddToConst = [this](const SCEV *X, const SCEV *Y,
11130                                       APInt &OutC1, APInt &OutC2,
11131                                       SCEV::NoWrapFlags ExpectedFlags) {
11132     const SCEV *XNonConstOp, *XConstOp;
11133     const SCEV *YNonConstOp, *YConstOp;
11134     SCEV::NoWrapFlags XFlagsPresent;
11135     SCEV::NoWrapFlags YFlagsPresent;
11136 
11137     if (!splitBinaryAdd(X, XConstOp, XNonConstOp, XFlagsPresent)) {
11138       XConstOp = getZero(X->getType());
11139       XNonConstOp = X;
11140       XFlagsPresent = ExpectedFlags;
11141     }
11142     if (!isa<SCEVConstant>(XConstOp) ||
11143         (XFlagsPresent & ExpectedFlags) != ExpectedFlags)
11144       return false;
11145 
11146     if (!splitBinaryAdd(Y, YConstOp, YNonConstOp, YFlagsPresent)) {
11147       YConstOp = getZero(Y->getType());
11148       YNonConstOp = Y;
11149       YFlagsPresent = ExpectedFlags;
11150     }
11151 
11152     if (!isa<SCEVConstant>(YConstOp) ||
11153         (YFlagsPresent & ExpectedFlags) != ExpectedFlags)
11154       return false;
11155 
11156     if (YNonConstOp != XNonConstOp)
11157       return false;
11158 
11159     OutC1 = cast<SCEVConstant>(XConstOp)->getAPInt();
11160     OutC2 = cast<SCEVConstant>(YConstOp)->getAPInt();
11161 
11162     return true;
11163   };
11164 
11165   APInt C1;
11166   APInt C2;
11167 
11168   switch (Pred) {
11169   default:
11170     break;
11171 
11172   case ICmpInst::ICMP_SGE:
11173     std::swap(LHS, RHS);
11174     [[fallthrough]];
11175   case ICmpInst::ICMP_SLE:
11176     // (X + C1)<nsw> s<= (X + C2)<nsw> if C1 s<= C2.
11177     if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.sle(C2))
11178       return true;
11179 
11180     break;
11181 
11182   case ICmpInst::ICMP_SGT:
11183     std::swap(LHS, RHS);
11184     [[fallthrough]];
11185   case ICmpInst::ICMP_SLT:
11186     // (X + C1)<nsw> s< (X + C2)<nsw> if C1 s< C2.
11187     if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.slt(C2))
11188       return true;
11189 
11190     break;
11191 
11192   case ICmpInst::ICMP_UGE:
11193     std::swap(LHS, RHS);
11194     [[fallthrough]];
11195   case ICmpInst::ICMP_ULE:
11196     // (X + C1)<nuw> u<= (X + C2)<nuw> for C1 u<= C2.
11197     if (MatchBinaryAddToConst(RHS, LHS, C2, C1, SCEV::FlagNUW) && C1.ule(C2))
11198       return true;
11199 
11200     break;
11201 
11202   case ICmpInst::ICMP_UGT:
11203     std::swap(LHS, RHS);
11204     [[fallthrough]];
11205   case ICmpInst::ICMP_ULT:
11206     // (X + C1)<nuw> u< (X + C2)<nuw> if C1 u< C2.
11207     if (MatchBinaryAddToConst(RHS, LHS, C2, C1, SCEV::FlagNUW) && C1.ult(C2))
11208       return true;
11209     break;
11210   }
11211 
11212   return false;
11213 }
11214 
11215 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
11216                                                    const SCEV *LHS,
11217                                                    const SCEV *RHS) {
11218   if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
11219     return false;
11220 
11221   // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
11222   // the stack can result in exponential time complexity.
11223   SaveAndRestore Restore(ProvingSplitPredicate, true);
11224 
11225   // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
11226   //
11227   // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
11228   // isKnownPredicate.  isKnownPredicate is more powerful, but also more
11229   // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
11230   // interesting cases seen in practice.  We can consider "upgrading" L >= 0 to
11231   // use isKnownPredicate later if needed.
11232   return isKnownNonNegative(RHS) &&
11233          isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
11234          isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
11235 }
11236 
11237 bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB,
11238                                         ICmpInst::Predicate Pred,
11239                                         const SCEV *LHS, const SCEV *RHS) {
11240   // No need to even try if we know the module has no guards.
11241   if (!HasGuards)
11242     return false;
11243 
11244   return any_of(*BB, [&](const Instruction &I) {
11245     using namespace llvm::PatternMatch;
11246 
11247     Value *Condition;
11248     return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
11249                          m_Value(Condition))) &&
11250            isImpliedCond(Pred, LHS, RHS, Condition, false);
11251   });
11252 }
11253 
11254 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
11255 /// protected by a conditional between LHS and RHS.  This is used to
11256 /// to eliminate casts.
11257 bool
11258 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
11259                                              ICmpInst::Predicate Pred,
11260                                              const SCEV *LHS, const SCEV *RHS) {
11261   // Interpret a null as meaning no loop, where there is obviously no guard
11262   // (interprocedural conditions notwithstanding). Do not bother about
11263   // unreachable loops.
11264   if (!L || !DT.isReachableFromEntry(L->getHeader()))
11265     return true;
11266 
11267   if (VerifyIR)
11268     assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) &&
11269            "This cannot be done on broken IR!");
11270 
11271 
11272   if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
11273     return true;
11274 
11275   BasicBlock *Latch = L->getLoopLatch();
11276   if (!Latch)
11277     return false;
11278 
11279   BranchInst *LoopContinuePredicate =
11280     dyn_cast<BranchInst>(Latch->getTerminator());
11281   if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
11282       isImpliedCond(Pred, LHS, RHS,
11283                     LoopContinuePredicate->getCondition(),
11284                     LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
11285     return true;
11286 
11287   // We don't want more than one activation of the following loops on the stack
11288   // -- that can lead to O(n!) time complexity.
11289   if (WalkingBEDominatingConds)
11290     return false;
11291 
11292   SaveAndRestore ClearOnExit(WalkingBEDominatingConds, true);
11293 
11294   // See if we can exploit a trip count to prove the predicate.
11295   const auto &BETakenInfo = getBackedgeTakenInfo(L);
11296   const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
11297   if (LatchBECount != getCouldNotCompute()) {
11298     // We know that Latch branches back to the loop header exactly
11299     // LatchBECount times.  This means the backdege condition at Latch is
11300     // equivalent to  "{0,+,1} u< LatchBECount".
11301     Type *Ty = LatchBECount->getType();
11302     auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
11303     const SCEV *LoopCounter =
11304       getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
11305     if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
11306                       LatchBECount))
11307       return true;
11308   }
11309 
11310   // Check conditions due to any @llvm.assume intrinsics.
11311   for (auto &AssumeVH : AC.assumptions()) {
11312     if (!AssumeVH)
11313       continue;
11314     auto *CI = cast<CallInst>(AssumeVH);
11315     if (!DT.dominates(CI, Latch->getTerminator()))
11316       continue;
11317 
11318     if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
11319       return true;
11320   }
11321 
11322   if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
11323     return true;
11324 
11325   for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
11326        DTN != HeaderDTN; DTN = DTN->getIDom()) {
11327     assert(DTN && "should reach the loop header before reaching the root!");
11328 
11329     BasicBlock *BB = DTN->getBlock();
11330     if (isImpliedViaGuard(BB, Pred, LHS, RHS))
11331       return true;
11332 
11333     BasicBlock *PBB = BB->getSinglePredecessor();
11334     if (!PBB)
11335       continue;
11336 
11337     BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
11338     if (!ContinuePredicate || !ContinuePredicate->isConditional())
11339       continue;
11340 
11341     Value *Condition = ContinuePredicate->getCondition();
11342 
11343     // If we have an edge `E` within the loop body that dominates the only
11344     // latch, the condition guarding `E` also guards the backedge.  This
11345     // reasoning works only for loops with a single latch.
11346 
11347     BasicBlockEdge DominatingEdge(PBB, BB);
11348     if (DominatingEdge.isSingleEdge()) {
11349       // We're constructively (and conservatively) enumerating edges within the
11350       // loop body that dominate the latch.  The dominator tree better agree
11351       // with us on this:
11352       assert(DT.dominates(DominatingEdge, Latch) && "should be!");
11353 
11354       if (isImpliedCond(Pred, LHS, RHS, Condition,
11355                         BB != ContinuePredicate->getSuccessor(0)))
11356         return true;
11357     }
11358   }
11359 
11360   return false;
11361 }
11362 
11363 bool ScalarEvolution::isBasicBlockEntryGuardedByCond(const BasicBlock *BB,
11364                                                      ICmpInst::Predicate Pred,
11365                                                      const SCEV *LHS,
11366                                                      const SCEV *RHS) {
11367   // Do not bother proving facts for unreachable code.
11368   if (!DT.isReachableFromEntry(BB))
11369     return true;
11370   if (VerifyIR)
11371     assert(!verifyFunction(*BB->getParent(), &dbgs()) &&
11372            "This cannot be done on broken IR!");
11373 
11374   // If we cannot prove strict comparison (e.g. a > b), maybe we can prove
11375   // the facts (a >= b && a != b) separately. A typical situation is when the
11376   // non-strict comparison is known from ranges and non-equality is known from
11377   // dominating predicates. If we are proving strict comparison, we always try
11378   // to prove non-equality and non-strict comparison separately.
11379   auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred);
11380   const bool ProvingStrictComparison = (Pred != NonStrictPredicate);
11381   bool ProvedNonStrictComparison = false;
11382   bool ProvedNonEquality = false;
11383 
11384   auto SplitAndProve =
11385     [&](std::function<bool(ICmpInst::Predicate)> Fn) -> bool {
11386     if (!ProvedNonStrictComparison)
11387       ProvedNonStrictComparison = Fn(NonStrictPredicate);
11388     if (!ProvedNonEquality)
11389       ProvedNonEquality = Fn(ICmpInst::ICMP_NE);
11390     if (ProvedNonStrictComparison && ProvedNonEquality)
11391       return true;
11392     return false;
11393   };
11394 
11395   if (ProvingStrictComparison) {
11396     auto ProofFn = [&](ICmpInst::Predicate P) {
11397       return isKnownViaNonRecursiveReasoning(P, LHS, RHS);
11398     };
11399     if (SplitAndProve(ProofFn))
11400       return true;
11401   }
11402 
11403   // Try to prove (Pred, LHS, RHS) using isImpliedCond.
11404   auto ProveViaCond = [&](const Value *Condition, bool Inverse) {
11405     const Instruction *CtxI = &BB->front();
11406     if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse, CtxI))
11407       return true;
11408     if (ProvingStrictComparison) {
11409       auto ProofFn = [&](ICmpInst::Predicate P) {
11410         return isImpliedCond(P, LHS, RHS, Condition, Inverse, CtxI);
11411       };
11412       if (SplitAndProve(ProofFn))
11413         return true;
11414     }
11415     return false;
11416   };
11417 
11418   // Starting at the block's predecessor, climb up the predecessor chain, as long
11419   // as there are predecessors that can be found that have unique successors
11420   // leading to the original block.
11421   const Loop *ContainingLoop = LI.getLoopFor(BB);
11422   const BasicBlock *PredBB;
11423   if (ContainingLoop && ContainingLoop->getHeader() == BB)
11424     PredBB = ContainingLoop->getLoopPredecessor();
11425   else
11426     PredBB = BB->getSinglePredecessor();
11427   for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB);
11428        Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
11429     const BranchInst *BlockEntryPredicate =
11430         dyn_cast<BranchInst>(Pair.first->getTerminator());
11431     if (!BlockEntryPredicate || BlockEntryPredicate->isUnconditional())
11432       continue;
11433 
11434     if (ProveViaCond(BlockEntryPredicate->getCondition(),
11435                      BlockEntryPredicate->getSuccessor(0) != Pair.second))
11436       return true;
11437   }
11438 
11439   // Check conditions due to any @llvm.assume intrinsics.
11440   for (auto &AssumeVH : AC.assumptions()) {
11441     if (!AssumeVH)
11442       continue;
11443     auto *CI = cast<CallInst>(AssumeVH);
11444     if (!DT.dominates(CI, BB))
11445       continue;
11446 
11447     if (ProveViaCond(CI->getArgOperand(0), false))
11448       return true;
11449   }
11450 
11451   // Check conditions due to any @llvm.experimental.guard intrinsics.
11452   auto *GuardDecl = F.getParent()->getFunction(
11453       Intrinsic::getName(Intrinsic::experimental_guard));
11454   if (GuardDecl)
11455     for (const auto *GU : GuardDecl->users())
11456       if (const auto *Guard = dyn_cast<IntrinsicInst>(GU))
11457         if (Guard->getFunction() == BB->getParent() && DT.dominates(Guard, BB))
11458           if (ProveViaCond(Guard->getArgOperand(0), false))
11459             return true;
11460   return false;
11461 }
11462 
11463 bool ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
11464                                                ICmpInst::Predicate Pred,
11465                                                const SCEV *LHS,
11466                                                const SCEV *RHS) {
11467   // Interpret a null as meaning no loop, where there is obviously no guard
11468   // (interprocedural conditions notwithstanding).
11469   if (!L)
11470     return false;
11471 
11472   // Both LHS and RHS must be available at loop entry.
11473   assert(isAvailableAtLoopEntry(LHS, L) &&
11474          "LHS is not available at Loop Entry");
11475   assert(isAvailableAtLoopEntry(RHS, L) &&
11476          "RHS is not available at Loop Entry");
11477 
11478   if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
11479     return true;
11480 
11481   return isBasicBlockEntryGuardedByCond(L->getHeader(), Pred, LHS, RHS);
11482 }
11483 
11484 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
11485                                     const SCEV *RHS,
11486                                     const Value *FoundCondValue, bool Inverse,
11487                                     const Instruction *CtxI) {
11488   // False conditions implies anything. Do not bother analyzing it further.
11489   if (FoundCondValue ==
11490       ConstantInt::getBool(FoundCondValue->getContext(), Inverse))
11491     return true;
11492 
11493   if (!PendingLoopPredicates.insert(FoundCondValue).second)
11494     return false;
11495 
11496   auto ClearOnExit =
11497       make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
11498 
11499   // Recursively handle And and Or conditions.
11500   const Value *Op0, *Op1;
11501   if (match(FoundCondValue, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
11502     if (!Inverse)
11503       return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) ||
11504              isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI);
11505   } else if (match(FoundCondValue, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) {
11506     if (Inverse)
11507       return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) ||
11508              isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI);
11509   }
11510 
11511   const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
11512   if (!ICI) return false;
11513 
11514   // Now that we found a conditional branch that dominates the loop or controls
11515   // the loop latch. Check to see if it is the comparison we are looking for.
11516   ICmpInst::Predicate FoundPred;
11517   if (Inverse)
11518     FoundPred = ICI->getInversePredicate();
11519   else
11520     FoundPred = ICI->getPredicate();
11521 
11522   const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
11523   const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
11524 
11525   return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, CtxI);
11526 }
11527 
11528 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
11529                                     const SCEV *RHS,
11530                                     ICmpInst::Predicate FoundPred,
11531                                     const SCEV *FoundLHS, const SCEV *FoundRHS,
11532                                     const Instruction *CtxI) {
11533   // Balance the types.
11534   if (getTypeSizeInBits(LHS->getType()) <
11535       getTypeSizeInBits(FoundLHS->getType())) {
11536     // For unsigned and equality predicates, try to prove that both found
11537     // operands fit into narrow unsigned range. If so, try to prove facts in
11538     // narrow types.
11539     if (!CmpInst::isSigned(FoundPred) && !FoundLHS->getType()->isPointerTy() &&
11540         !FoundRHS->getType()->isPointerTy()) {
11541       auto *NarrowType = LHS->getType();
11542       auto *WideType = FoundLHS->getType();
11543       auto BitWidth = getTypeSizeInBits(NarrowType);
11544       const SCEV *MaxValue = getZeroExtendExpr(
11545           getConstant(APInt::getMaxValue(BitWidth)), WideType);
11546       if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundLHS,
11547                                           MaxValue) &&
11548           isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundRHS,
11549                                           MaxValue)) {
11550         const SCEV *TruncFoundLHS = getTruncateExpr(FoundLHS, NarrowType);
11551         const SCEV *TruncFoundRHS = getTruncateExpr(FoundRHS, NarrowType);
11552         if (isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, TruncFoundLHS,
11553                                        TruncFoundRHS, CtxI))
11554           return true;
11555       }
11556     }
11557 
11558     if (LHS->getType()->isPointerTy() || RHS->getType()->isPointerTy())
11559       return false;
11560     if (CmpInst::isSigned(Pred)) {
11561       LHS = getSignExtendExpr(LHS, FoundLHS->getType());
11562       RHS = getSignExtendExpr(RHS, FoundLHS->getType());
11563     } else {
11564       LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
11565       RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
11566     }
11567   } else if (getTypeSizeInBits(LHS->getType()) >
11568       getTypeSizeInBits(FoundLHS->getType())) {
11569     if (FoundLHS->getType()->isPointerTy() || FoundRHS->getType()->isPointerTy())
11570       return false;
11571     if (CmpInst::isSigned(FoundPred)) {
11572       FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
11573       FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
11574     } else {
11575       FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
11576       FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
11577     }
11578   }
11579   return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS,
11580                                     FoundRHS, CtxI);
11581 }
11582 
11583 bool ScalarEvolution::isImpliedCondBalancedTypes(
11584     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
11585     ICmpInst::Predicate FoundPred, const SCEV *FoundLHS, const SCEV *FoundRHS,
11586     const Instruction *CtxI) {
11587   assert(getTypeSizeInBits(LHS->getType()) ==
11588              getTypeSizeInBits(FoundLHS->getType()) &&
11589          "Types should be balanced!");
11590   // Canonicalize the query to match the way instcombine will have
11591   // canonicalized the comparison.
11592   if (SimplifyICmpOperands(Pred, LHS, RHS))
11593     if (LHS == RHS)
11594       return CmpInst::isTrueWhenEqual(Pred);
11595   if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
11596     if (FoundLHS == FoundRHS)
11597       return CmpInst::isFalseWhenEqual(FoundPred);
11598 
11599   // Check to see if we can make the LHS or RHS match.
11600   if (LHS == FoundRHS || RHS == FoundLHS) {
11601     if (isa<SCEVConstant>(RHS)) {
11602       std::swap(FoundLHS, FoundRHS);
11603       FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
11604     } else {
11605       std::swap(LHS, RHS);
11606       Pred = ICmpInst::getSwappedPredicate(Pred);
11607     }
11608   }
11609 
11610   // Check whether the found predicate is the same as the desired predicate.
11611   if (FoundPred == Pred)
11612     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI);
11613 
11614   // Check whether swapping the found predicate makes it the same as the
11615   // desired predicate.
11616   if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
11617     // We can write the implication
11618     // 0.  LHS Pred      RHS  <-   FoundLHS SwapPred  FoundRHS
11619     // using one of the following ways:
11620     // 1.  LHS Pred      RHS  <-   FoundRHS Pred      FoundLHS
11621     // 2.  RHS SwapPred  LHS  <-   FoundLHS SwapPred  FoundRHS
11622     // 3.  LHS Pred      RHS  <-  ~FoundLHS Pred     ~FoundRHS
11623     // 4. ~LHS SwapPred ~RHS  <-   FoundLHS SwapPred  FoundRHS
11624     // Forms 1. and 2. require swapping the operands of one condition. Don't
11625     // do this if it would break canonical constant/addrec ordering.
11626     if (!isa<SCEVConstant>(RHS) && !isa<SCEVAddRecExpr>(LHS))
11627       return isImpliedCondOperands(FoundPred, RHS, LHS, FoundLHS, FoundRHS,
11628                                    CtxI);
11629     if (!isa<SCEVConstant>(FoundRHS) && !isa<SCEVAddRecExpr>(FoundLHS))
11630       return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS, CtxI);
11631 
11632     // There's no clear preference between forms 3. and 4., try both.  Avoid
11633     // forming getNotSCEV of pointer values as the resulting subtract is
11634     // not legal.
11635     if (!LHS->getType()->isPointerTy() && !RHS->getType()->isPointerTy() &&
11636         isImpliedCondOperands(FoundPred, getNotSCEV(LHS), getNotSCEV(RHS),
11637                               FoundLHS, FoundRHS, CtxI))
11638       return true;
11639 
11640     if (!FoundLHS->getType()->isPointerTy() &&
11641         !FoundRHS->getType()->isPointerTy() &&
11642         isImpliedCondOperands(Pred, LHS, RHS, getNotSCEV(FoundLHS),
11643                               getNotSCEV(FoundRHS), CtxI))
11644       return true;
11645 
11646     return false;
11647   }
11648 
11649   auto IsSignFlippedPredicate = [](CmpInst::Predicate P1,
11650                                    CmpInst::Predicate P2) {
11651     assert(P1 != P2 && "Handled earlier!");
11652     return CmpInst::isRelational(P2) &&
11653            P1 == CmpInst::getFlippedSignednessPredicate(P2);
11654   };
11655   if (IsSignFlippedPredicate(Pred, FoundPred)) {
11656     // Unsigned comparison is the same as signed comparison when both the
11657     // operands are non-negative or negative.
11658     if ((isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) ||
11659         (isKnownNegative(FoundLHS) && isKnownNegative(FoundRHS)))
11660       return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI);
11661     // Create local copies that we can freely swap and canonicalize our
11662     // conditions to "le/lt".
11663     ICmpInst::Predicate CanonicalPred = Pred, CanonicalFoundPred = FoundPred;
11664     const SCEV *CanonicalLHS = LHS, *CanonicalRHS = RHS,
11665                *CanonicalFoundLHS = FoundLHS, *CanonicalFoundRHS = FoundRHS;
11666     if (ICmpInst::isGT(CanonicalPred) || ICmpInst::isGE(CanonicalPred)) {
11667       CanonicalPred = ICmpInst::getSwappedPredicate(CanonicalPred);
11668       CanonicalFoundPred = ICmpInst::getSwappedPredicate(CanonicalFoundPred);
11669       std::swap(CanonicalLHS, CanonicalRHS);
11670       std::swap(CanonicalFoundLHS, CanonicalFoundRHS);
11671     }
11672     assert((ICmpInst::isLT(CanonicalPred) || ICmpInst::isLE(CanonicalPred)) &&
11673            "Must be!");
11674     assert((ICmpInst::isLT(CanonicalFoundPred) ||
11675             ICmpInst::isLE(CanonicalFoundPred)) &&
11676            "Must be!");
11677     if (ICmpInst::isSigned(CanonicalPred) && isKnownNonNegative(CanonicalRHS))
11678       // Use implication:
11679       // x <u y && y >=s 0 --> x <s y.
11680       // If we can prove the left part, the right part is also proven.
11681       return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS,
11682                                    CanonicalRHS, CanonicalFoundLHS,
11683                                    CanonicalFoundRHS);
11684     if (ICmpInst::isUnsigned(CanonicalPred) && isKnownNegative(CanonicalRHS))
11685       // Use implication:
11686       // x <s y && y <s 0 --> x <u y.
11687       // If we can prove the left part, the right part is also proven.
11688       return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS,
11689                                    CanonicalRHS, CanonicalFoundLHS,
11690                                    CanonicalFoundRHS);
11691   }
11692 
11693   // Check if we can make progress by sharpening ranges.
11694   if (FoundPred == ICmpInst::ICMP_NE &&
11695       (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
11696 
11697     const SCEVConstant *C = nullptr;
11698     const SCEV *V = nullptr;
11699 
11700     if (isa<SCEVConstant>(FoundLHS)) {
11701       C = cast<SCEVConstant>(FoundLHS);
11702       V = FoundRHS;
11703     } else {
11704       C = cast<SCEVConstant>(FoundRHS);
11705       V = FoundLHS;
11706     }
11707 
11708     // The guarding predicate tells us that C != V. If the known range
11709     // of V is [C, t), we can sharpen the range to [C + 1, t).  The
11710     // range we consider has to correspond to same signedness as the
11711     // predicate we're interested in folding.
11712 
11713     APInt Min = ICmpInst::isSigned(Pred) ?
11714         getSignedRangeMin(V) : getUnsignedRangeMin(V);
11715 
11716     if (Min == C->getAPInt()) {
11717       // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
11718       // This is true even if (Min + 1) wraps around -- in case of
11719       // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
11720 
11721       APInt SharperMin = Min + 1;
11722 
11723       switch (Pred) {
11724         case ICmpInst::ICMP_SGE:
11725         case ICmpInst::ICMP_UGE:
11726           // We know V `Pred` SharperMin.  If this implies LHS `Pred`
11727           // RHS, we're done.
11728           if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(SharperMin),
11729                                     CtxI))
11730             return true;
11731           [[fallthrough]];
11732 
11733         case ICmpInst::ICMP_SGT:
11734         case ICmpInst::ICMP_UGT:
11735           // We know from the range information that (V `Pred` Min ||
11736           // V == Min).  We know from the guarding condition that !(V
11737           // == Min).  This gives us
11738           //
11739           //       V `Pred` Min || V == Min && !(V == Min)
11740           //   =>  V `Pred` Min
11741           //
11742           // If V `Pred` Min implies LHS `Pred` RHS, we're done.
11743 
11744           if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min), CtxI))
11745             return true;
11746           break;
11747 
11748         // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively.
11749         case ICmpInst::ICMP_SLE:
11750         case ICmpInst::ICMP_ULE:
11751           if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS,
11752                                     LHS, V, getConstant(SharperMin), CtxI))
11753             return true;
11754           [[fallthrough]];
11755 
11756         case ICmpInst::ICMP_SLT:
11757         case ICmpInst::ICMP_ULT:
11758           if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS,
11759                                     LHS, V, getConstant(Min), CtxI))
11760             return true;
11761           break;
11762 
11763         default:
11764           // No change
11765           break;
11766       }
11767     }
11768   }
11769 
11770   // Check whether the actual condition is beyond sufficient.
11771   if (FoundPred == ICmpInst::ICMP_EQ)
11772     if (ICmpInst::isTrueWhenEqual(Pred))
11773       if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
11774         return true;
11775   if (Pred == ICmpInst::ICMP_NE)
11776     if (!ICmpInst::isTrueWhenEqual(FoundPred))
11777       if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
11778         return true;
11779 
11780   if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS))
11781     return true;
11782 
11783   // Otherwise assume the worst.
11784   return false;
11785 }
11786 
11787 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
11788                                      const SCEV *&L, const SCEV *&R,
11789                                      SCEV::NoWrapFlags &Flags) {
11790   const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
11791   if (!AE || AE->getNumOperands() != 2)
11792     return false;
11793 
11794   L = AE->getOperand(0);
11795   R = AE->getOperand(1);
11796   Flags = AE->getNoWrapFlags();
11797   return true;
11798 }
11799 
11800 std::optional<APInt>
11801 ScalarEvolution::computeConstantDifference(const SCEV *More, const SCEV *Less) {
11802   // We avoid subtracting expressions here because this function is usually
11803   // fairly deep in the call stack (i.e. is called many times).
11804 
11805   // X - X = 0.
11806   if (More == Less)
11807     return APInt(getTypeSizeInBits(More->getType()), 0);
11808 
11809   if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
11810     const auto *LAR = cast<SCEVAddRecExpr>(Less);
11811     const auto *MAR = cast<SCEVAddRecExpr>(More);
11812 
11813     if (LAR->getLoop() != MAR->getLoop())
11814       return std::nullopt;
11815 
11816     // We look at affine expressions only; not for correctness but to keep
11817     // getStepRecurrence cheap.
11818     if (!LAR->isAffine() || !MAR->isAffine())
11819       return std::nullopt;
11820 
11821     if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
11822       return std::nullopt;
11823 
11824     Less = LAR->getStart();
11825     More = MAR->getStart();
11826 
11827     // fall through
11828   }
11829 
11830   if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
11831     const auto &M = cast<SCEVConstant>(More)->getAPInt();
11832     const auto &L = cast<SCEVConstant>(Less)->getAPInt();
11833     return M - L;
11834   }
11835 
11836   SCEV::NoWrapFlags Flags;
11837   const SCEV *LLess = nullptr, *RLess = nullptr;
11838   const SCEV *LMore = nullptr, *RMore = nullptr;
11839   const SCEVConstant *C1 = nullptr, *C2 = nullptr;
11840   // Compare (X + C1) vs X.
11841   if (splitBinaryAdd(Less, LLess, RLess, Flags))
11842     if ((C1 = dyn_cast<SCEVConstant>(LLess)))
11843       if (RLess == More)
11844         return -(C1->getAPInt());
11845 
11846   // Compare X vs (X + C2).
11847   if (splitBinaryAdd(More, LMore, RMore, Flags))
11848     if ((C2 = dyn_cast<SCEVConstant>(LMore)))
11849       if (RMore == Less)
11850         return C2->getAPInt();
11851 
11852   // Compare (X + C1) vs (X + C2).
11853   if (C1 && C2 && RLess == RMore)
11854     return C2->getAPInt() - C1->getAPInt();
11855 
11856   return std::nullopt;
11857 }
11858 
11859 bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart(
11860     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
11861     const SCEV *FoundLHS, const SCEV *FoundRHS, const Instruction *CtxI) {
11862   // Try to recognize the following pattern:
11863   //
11864   //   FoundRHS = ...
11865   // ...
11866   // loop:
11867   //   FoundLHS = {Start,+,W}
11868   // context_bb: // Basic block from the same loop
11869   //   known(Pred, FoundLHS, FoundRHS)
11870   //
11871   // If some predicate is known in the context of a loop, it is also known on
11872   // each iteration of this loop, including the first iteration. Therefore, in
11873   // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to
11874   // prove the original pred using this fact.
11875   if (!CtxI)
11876     return false;
11877   const BasicBlock *ContextBB = CtxI->getParent();
11878   // Make sure AR varies in the context block.
11879   if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) {
11880     const Loop *L = AR->getLoop();
11881     // Make sure that context belongs to the loop and executes on 1st iteration
11882     // (if it ever executes at all).
11883     if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch()))
11884       return false;
11885     if (!isAvailableAtLoopEntry(FoundRHS, AR->getLoop()))
11886       return false;
11887     return isImpliedCondOperands(Pred, LHS, RHS, AR->getStart(), FoundRHS);
11888   }
11889 
11890   if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) {
11891     const Loop *L = AR->getLoop();
11892     // Make sure that context belongs to the loop and executes on 1st iteration
11893     // (if it ever executes at all).
11894     if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch()))
11895       return false;
11896     if (!isAvailableAtLoopEntry(FoundLHS, AR->getLoop()))
11897       return false;
11898     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->getStart());
11899   }
11900 
11901   return false;
11902 }
11903 
11904 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
11905     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
11906     const SCEV *FoundLHS, const SCEV *FoundRHS) {
11907   if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
11908     return false;
11909 
11910   const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
11911   if (!AddRecLHS)
11912     return false;
11913 
11914   const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
11915   if (!AddRecFoundLHS)
11916     return false;
11917 
11918   // We'd like to let SCEV reason about control dependencies, so we constrain
11919   // both the inequalities to be about add recurrences on the same loop.  This
11920   // way we can use isLoopEntryGuardedByCond later.
11921 
11922   const Loop *L = AddRecFoundLHS->getLoop();
11923   if (L != AddRecLHS->getLoop())
11924     return false;
11925 
11926   //  FoundLHS u< FoundRHS u< -C =>  (FoundLHS + C) u< (FoundRHS + C) ... (1)
11927   //
11928   //  FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
11929   //                                                                  ... (2)
11930   //
11931   // Informal proof for (2), assuming (1) [*]:
11932   //
11933   // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
11934   //
11935   // Then
11936   //
11937   //       FoundLHS s< FoundRHS s< INT_MIN - C
11938   // <=>  (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C   [ using (3) ]
11939   // <=>  (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
11940   // <=>  (FoundLHS + INT_MIN + C + INT_MIN) s<
11941   //                        (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
11942   // <=>  FoundLHS + C s< FoundRHS + C
11943   //
11944   // [*]: (1) can be proved by ruling out overflow.
11945   //
11946   // [**]: This can be proved by analyzing all the four possibilities:
11947   //    (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
11948   //    (A s>= 0, B s>= 0).
11949   //
11950   // Note:
11951   // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
11952   // will not sign underflow.  For instance, say FoundLHS = (i8 -128), FoundRHS
11953   // = (i8 -127) and C = (i8 -100).  Then INT_MIN - C = (i8 -28), and FoundRHS
11954   // s< (INT_MIN - C).  Lack of sign overflow / underflow in "FoundRHS + C" is
11955   // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
11956   // C)".
11957 
11958   std::optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
11959   std::optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
11960   if (!LDiff || !RDiff || *LDiff != *RDiff)
11961     return false;
11962 
11963   if (LDiff->isMinValue())
11964     return true;
11965 
11966   APInt FoundRHSLimit;
11967 
11968   if (Pred == CmpInst::ICMP_ULT) {
11969     FoundRHSLimit = -(*RDiff);
11970   } else {
11971     assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
11972     FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
11973   }
11974 
11975   // Try to prove (1) or (2), as needed.
11976   return isAvailableAtLoopEntry(FoundRHS, L) &&
11977          isLoopEntryGuardedByCond(L, Pred, FoundRHS,
11978                                   getConstant(FoundRHSLimit));
11979 }
11980 
11981 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred,
11982                                         const SCEV *LHS, const SCEV *RHS,
11983                                         const SCEV *FoundLHS,
11984                                         const SCEV *FoundRHS, unsigned Depth) {
11985   const PHINode *LPhi = nullptr, *RPhi = nullptr;
11986 
11987   auto ClearOnExit = make_scope_exit([&]() {
11988     if (LPhi) {
11989       bool Erased = PendingMerges.erase(LPhi);
11990       assert(Erased && "Failed to erase LPhi!");
11991       (void)Erased;
11992     }
11993     if (RPhi) {
11994       bool Erased = PendingMerges.erase(RPhi);
11995       assert(Erased && "Failed to erase RPhi!");
11996       (void)Erased;
11997     }
11998   });
11999 
12000   // Find respective Phis and check that they are not being pending.
12001   if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS))
12002     if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) {
12003       if (!PendingMerges.insert(Phi).second)
12004         return false;
12005       LPhi = Phi;
12006     }
12007   if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS))
12008     if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) {
12009       // If we detect a loop of Phi nodes being processed by this method, for
12010       // example:
12011       //
12012       //   %a = phi i32 [ %some1, %preheader ], [ %b, %latch ]
12013       //   %b = phi i32 [ %some2, %preheader ], [ %a, %latch ]
12014       //
12015       // we don't want to deal with a case that complex, so return conservative
12016       // answer false.
12017       if (!PendingMerges.insert(Phi).second)
12018         return false;
12019       RPhi = Phi;
12020     }
12021 
12022   // If none of LHS, RHS is a Phi, nothing to do here.
12023   if (!LPhi && !RPhi)
12024     return false;
12025 
12026   // If there is a SCEVUnknown Phi we are interested in, make it left.
12027   if (!LPhi) {
12028     std::swap(LHS, RHS);
12029     std::swap(FoundLHS, FoundRHS);
12030     std::swap(LPhi, RPhi);
12031     Pred = ICmpInst::getSwappedPredicate(Pred);
12032   }
12033 
12034   assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!");
12035   const BasicBlock *LBB = LPhi->getParent();
12036   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
12037 
12038   auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) {
12039     return isKnownViaNonRecursiveReasoning(Pred, S1, S2) ||
12040            isImpliedCondOperandsViaRanges(Pred, S1, S2, Pred, FoundLHS, FoundRHS) ||
12041            isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth);
12042   };
12043 
12044   if (RPhi && RPhi->getParent() == LBB) {
12045     // Case one: RHS is also a SCEVUnknown Phi from the same basic block.
12046     // If we compare two Phis from the same block, and for each entry block
12047     // the predicate is true for incoming values from this block, then the
12048     // predicate is also true for the Phis.
12049     for (const BasicBlock *IncBB : predecessors(LBB)) {
12050       const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
12051       const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB));
12052       if (!ProvedEasily(L, R))
12053         return false;
12054     }
12055   } else if (RAR && RAR->getLoop()->getHeader() == LBB) {
12056     // Case two: RHS is also a Phi from the same basic block, and it is an
12057     // AddRec. It means that there is a loop which has both AddRec and Unknown
12058     // PHIs, for it we can compare incoming values of AddRec from above the loop
12059     // and latch with their respective incoming values of LPhi.
12060     // TODO: Generalize to handle loops with many inputs in a header.
12061     if (LPhi->getNumIncomingValues() != 2) return false;
12062 
12063     auto *RLoop = RAR->getLoop();
12064     auto *Predecessor = RLoop->getLoopPredecessor();
12065     assert(Predecessor && "Loop with AddRec with no predecessor?");
12066     const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor));
12067     if (!ProvedEasily(L1, RAR->getStart()))
12068       return false;
12069     auto *Latch = RLoop->getLoopLatch();
12070     assert(Latch && "Loop with AddRec with no latch?");
12071     const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch));
12072     if (!ProvedEasily(L2, RAR->getPostIncExpr(*this)))
12073       return false;
12074   } else {
12075     // In all other cases go over inputs of LHS and compare each of them to RHS,
12076     // the predicate is true for (LHS, RHS) if it is true for all such pairs.
12077     // At this point RHS is either a non-Phi, or it is a Phi from some block
12078     // different from LBB.
12079     for (const BasicBlock *IncBB : predecessors(LBB)) {
12080       // Check that RHS is available in this block.
12081       if (!dominates(RHS, IncBB))
12082         return false;
12083       const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
12084       // Make sure L does not refer to a value from a potentially previous
12085       // iteration of a loop.
12086       if (!properlyDominates(L, LBB))
12087         return false;
12088       if (!ProvedEasily(L, RHS))
12089         return false;
12090     }
12091   }
12092   return true;
12093 }
12094 
12095 bool ScalarEvolution::isImpliedCondOperandsViaShift(ICmpInst::Predicate Pred,
12096                                                     const SCEV *LHS,
12097                                                     const SCEV *RHS,
12098                                                     const SCEV *FoundLHS,
12099                                                     const SCEV *FoundRHS) {
12100   // We want to imply LHS < RHS from LHS < (RHS >> shiftvalue).  First, make
12101   // sure that we are dealing with same LHS.
12102   if (RHS == FoundRHS) {
12103     std::swap(LHS, RHS);
12104     std::swap(FoundLHS, FoundRHS);
12105     Pred = ICmpInst::getSwappedPredicate(Pred);
12106   }
12107   if (LHS != FoundLHS)
12108     return false;
12109 
12110   auto *SUFoundRHS = dyn_cast<SCEVUnknown>(FoundRHS);
12111   if (!SUFoundRHS)
12112     return false;
12113 
12114   Value *Shiftee, *ShiftValue;
12115 
12116   using namespace PatternMatch;
12117   if (match(SUFoundRHS->getValue(),
12118             m_LShr(m_Value(Shiftee), m_Value(ShiftValue)))) {
12119     auto *ShifteeS = getSCEV(Shiftee);
12120     // Prove one of the following:
12121     // LHS <u (shiftee >> shiftvalue) && shiftee <=u RHS ---> LHS <u RHS
12122     // LHS <=u (shiftee >> shiftvalue) && shiftee <=u RHS ---> LHS <=u RHS
12123     // LHS <s (shiftee >> shiftvalue) && shiftee <=s RHS && shiftee >=s 0
12124     //   ---> LHS <s RHS
12125     // LHS <=s (shiftee >> shiftvalue) && shiftee <=s RHS && shiftee >=s 0
12126     //   ---> LHS <=s RHS
12127     if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE)
12128       return isKnownPredicate(ICmpInst::ICMP_ULE, ShifteeS, RHS);
12129     if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
12130       if (isKnownNonNegative(ShifteeS))
12131         return isKnownPredicate(ICmpInst::ICMP_SLE, ShifteeS, RHS);
12132   }
12133 
12134   return false;
12135 }
12136 
12137 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
12138                                             const SCEV *LHS, const SCEV *RHS,
12139                                             const SCEV *FoundLHS,
12140                                             const SCEV *FoundRHS,
12141                                             const Instruction *CtxI) {
12142   if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, Pred, FoundLHS, FoundRHS))
12143     return true;
12144 
12145   if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
12146     return true;
12147 
12148   if (isImpliedCondOperandsViaShift(Pred, LHS, RHS, FoundLHS, FoundRHS))
12149     return true;
12150 
12151   if (isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS,
12152                                           CtxI))
12153     return true;
12154 
12155   return isImpliedCondOperandsHelper(Pred, LHS, RHS,
12156                                      FoundLHS, FoundRHS);
12157 }
12158 
12159 /// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values?
12160 template <typename MinMaxExprType>
12161 static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr,
12162                                  const SCEV *Candidate) {
12163   const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr);
12164   if (!MinMaxExpr)
12165     return false;
12166 
12167   return is_contained(MinMaxExpr->operands(), Candidate);
12168 }
12169 
12170 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
12171                                            ICmpInst::Predicate Pred,
12172                                            const SCEV *LHS, const SCEV *RHS) {
12173   // If both sides are affine addrecs for the same loop, with equal
12174   // steps, and we know the recurrences don't wrap, then we only
12175   // need to check the predicate on the starting values.
12176 
12177   if (!ICmpInst::isRelational(Pred))
12178     return false;
12179 
12180   const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
12181   if (!LAR)
12182     return false;
12183   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
12184   if (!RAR)
12185     return false;
12186   if (LAR->getLoop() != RAR->getLoop())
12187     return false;
12188   if (!LAR->isAffine() || !RAR->isAffine())
12189     return false;
12190 
12191   if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
12192     return false;
12193 
12194   SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
12195                          SCEV::FlagNSW : SCEV::FlagNUW;
12196   if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
12197     return false;
12198 
12199   return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
12200 }
12201 
12202 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
12203 /// expression?
12204 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
12205                                         ICmpInst::Predicate Pred,
12206                                         const SCEV *LHS, const SCEV *RHS) {
12207   switch (Pred) {
12208   default:
12209     return false;
12210 
12211   case ICmpInst::ICMP_SGE:
12212     std::swap(LHS, RHS);
12213     [[fallthrough]];
12214   case ICmpInst::ICMP_SLE:
12215     return
12216         // min(A, ...) <= A
12217         IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) ||
12218         // A <= max(A, ...)
12219         IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
12220 
12221   case ICmpInst::ICMP_UGE:
12222     std::swap(LHS, RHS);
12223     [[fallthrough]];
12224   case ICmpInst::ICMP_ULE:
12225     return
12226         // min(A, ...) <= A
12227         // FIXME: what about umin_seq?
12228         IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) ||
12229         // A <= max(A, ...)
12230         IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
12231   }
12232 
12233   llvm_unreachable("covered switch fell through?!");
12234 }
12235 
12236 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred,
12237                                              const SCEV *LHS, const SCEV *RHS,
12238                                              const SCEV *FoundLHS,
12239                                              const SCEV *FoundRHS,
12240                                              unsigned Depth) {
12241   assert(getTypeSizeInBits(LHS->getType()) ==
12242              getTypeSizeInBits(RHS->getType()) &&
12243          "LHS and RHS have different sizes?");
12244   assert(getTypeSizeInBits(FoundLHS->getType()) ==
12245              getTypeSizeInBits(FoundRHS->getType()) &&
12246          "FoundLHS and FoundRHS have different sizes?");
12247   // We want to avoid hurting the compile time with analysis of too big trees.
12248   if (Depth > MaxSCEVOperationsImplicationDepth)
12249     return false;
12250 
12251   // We only want to work with GT comparison so far.
12252   if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT) {
12253     Pred = CmpInst::getSwappedPredicate(Pred);
12254     std::swap(LHS, RHS);
12255     std::swap(FoundLHS, FoundRHS);
12256   }
12257 
12258   // For unsigned, try to reduce it to corresponding signed comparison.
12259   if (Pred == ICmpInst::ICMP_UGT)
12260     // We can replace unsigned predicate with its signed counterpart if all
12261     // involved values are non-negative.
12262     // TODO: We could have better support for unsigned.
12263     if (isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) {
12264       // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing
12265       // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us
12266       // use this fact to prove that LHS and RHS are non-negative.
12267       const SCEV *MinusOne = getMinusOne(LHS->getType());
12268       if (isImpliedCondOperands(ICmpInst::ICMP_SGT, LHS, MinusOne, FoundLHS,
12269                                 FoundRHS) &&
12270           isImpliedCondOperands(ICmpInst::ICMP_SGT, RHS, MinusOne, FoundLHS,
12271                                 FoundRHS))
12272         Pred = ICmpInst::ICMP_SGT;
12273     }
12274 
12275   if (Pred != ICmpInst::ICMP_SGT)
12276     return false;
12277 
12278   auto GetOpFromSExt = [&](const SCEV *S) {
12279     if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
12280       return Ext->getOperand();
12281     // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
12282     // the constant in some cases.
12283     return S;
12284   };
12285 
12286   // Acquire values from extensions.
12287   auto *OrigLHS = LHS;
12288   auto *OrigFoundLHS = FoundLHS;
12289   LHS = GetOpFromSExt(LHS);
12290   FoundLHS = GetOpFromSExt(FoundLHS);
12291 
12292   // Is the SGT predicate can be proved trivially or using the found context.
12293   auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
12294     return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
12295            isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
12296                                   FoundRHS, Depth + 1);
12297   };
12298 
12299   if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
12300     // We want to avoid creation of any new non-constant SCEV. Since we are
12301     // going to compare the operands to RHS, we should be certain that we don't
12302     // need any size extensions for this. So let's decline all cases when the
12303     // sizes of types of LHS and RHS do not match.
12304     // TODO: Maybe try to get RHS from sext to catch more cases?
12305     if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType()))
12306       return false;
12307 
12308     // Should not overflow.
12309     if (!LHSAddExpr->hasNoSignedWrap())
12310       return false;
12311 
12312     auto *LL = LHSAddExpr->getOperand(0);
12313     auto *LR = LHSAddExpr->getOperand(1);
12314     auto *MinusOne = getMinusOne(RHS->getType());
12315 
12316     // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
12317     auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
12318       return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
12319     };
12320     // Try to prove the following rule:
12321     // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
12322     // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
12323     if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
12324       return true;
12325   } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
12326     Value *LL, *LR;
12327     // FIXME: Once we have SDiv implemented, we can get rid of this matching.
12328 
12329     using namespace llvm::PatternMatch;
12330 
12331     if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
12332       // Rules for division.
12333       // We are going to perform some comparisons with Denominator and its
12334       // derivative expressions. In general case, creating a SCEV for it may
12335       // lead to a complex analysis of the entire graph, and in particular it
12336       // can request trip count recalculation for the same loop. This would
12337       // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
12338       // this, we only want to create SCEVs that are constants in this section.
12339       // So we bail if Denominator is not a constant.
12340       if (!isa<ConstantInt>(LR))
12341         return false;
12342 
12343       auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
12344 
12345       // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
12346       // then a SCEV for the numerator already exists and matches with FoundLHS.
12347       auto *Numerator = getExistingSCEV(LL);
12348       if (!Numerator || Numerator->getType() != FoundLHS->getType())
12349         return false;
12350 
12351       // Make sure that the numerator matches with FoundLHS and the denominator
12352       // is positive.
12353       if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
12354         return false;
12355 
12356       auto *DTy = Denominator->getType();
12357       auto *FRHSTy = FoundRHS->getType();
12358       if (DTy->isPointerTy() != FRHSTy->isPointerTy())
12359         // One of types is a pointer and another one is not. We cannot extend
12360         // them properly to a wider type, so let us just reject this case.
12361         // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
12362         // to avoid this check.
12363         return false;
12364 
12365       // Given that:
12366       // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
12367       auto *WTy = getWiderType(DTy, FRHSTy);
12368       auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
12369       auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
12370 
12371       // Try to prove the following rule:
12372       // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
12373       // For example, given that FoundLHS > 2. It means that FoundLHS is at
12374       // least 3. If we divide it by Denominator < 4, we will have at least 1.
12375       auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
12376       if (isKnownNonPositive(RHS) &&
12377           IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
12378         return true;
12379 
12380       // Try to prove the following rule:
12381       // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
12382       // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
12383       // If we divide it by Denominator > 2, then:
12384       // 1. If FoundLHS is negative, then the result is 0.
12385       // 2. If FoundLHS is non-negative, then the result is non-negative.
12386       // Anyways, the result is non-negative.
12387       auto *MinusOne = getMinusOne(WTy);
12388       auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
12389       if (isKnownNegative(RHS) &&
12390           IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
12391         return true;
12392     }
12393   }
12394 
12395   // If our expression contained SCEVUnknown Phis, and we split it down and now
12396   // need to prove something for them, try to prove the predicate for every
12397   // possible incoming values of those Phis.
12398   if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1))
12399     return true;
12400 
12401   return false;
12402 }
12403 
12404 static bool isKnownPredicateExtendIdiom(ICmpInst::Predicate Pred,
12405                                         const SCEV *LHS, const SCEV *RHS) {
12406   // zext x u<= sext x, sext x s<= zext x
12407   switch (Pred) {
12408   case ICmpInst::ICMP_SGE:
12409     std::swap(LHS, RHS);
12410     [[fallthrough]];
12411   case ICmpInst::ICMP_SLE: {
12412     // If operand >=s 0 then ZExt == SExt.  If operand <s 0 then SExt <s ZExt.
12413     const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(LHS);
12414     const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(RHS);
12415     if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand())
12416       return true;
12417     break;
12418   }
12419   case ICmpInst::ICMP_UGE:
12420     std::swap(LHS, RHS);
12421     [[fallthrough]];
12422   case ICmpInst::ICMP_ULE: {
12423     // If operand >=s 0 then ZExt == SExt.  If operand <s 0 then ZExt <u SExt.
12424     const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS);
12425     const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(RHS);
12426     if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand())
12427       return true;
12428     break;
12429   }
12430   default:
12431     break;
12432   };
12433   return false;
12434 }
12435 
12436 bool
12437 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred,
12438                                            const SCEV *LHS, const SCEV *RHS) {
12439   return isKnownPredicateExtendIdiom(Pred, LHS, RHS) ||
12440          isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
12441          IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
12442          IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
12443          isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
12444 }
12445 
12446 bool
12447 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
12448                                              const SCEV *LHS, const SCEV *RHS,
12449                                              const SCEV *FoundLHS,
12450                                              const SCEV *FoundRHS) {
12451   switch (Pred) {
12452   default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
12453   case ICmpInst::ICMP_EQ:
12454   case ICmpInst::ICMP_NE:
12455     if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
12456       return true;
12457     break;
12458   case ICmpInst::ICMP_SLT:
12459   case ICmpInst::ICMP_SLE:
12460     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
12461         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS))
12462       return true;
12463     break;
12464   case ICmpInst::ICMP_SGT:
12465   case ICmpInst::ICMP_SGE:
12466     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
12467         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS))
12468       return true;
12469     break;
12470   case ICmpInst::ICMP_ULT:
12471   case ICmpInst::ICMP_ULE:
12472     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
12473         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS))
12474       return true;
12475     break;
12476   case ICmpInst::ICMP_UGT:
12477   case ICmpInst::ICMP_UGE:
12478     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
12479         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS))
12480       return true;
12481     break;
12482   }
12483 
12484   // Maybe it can be proved via operations?
12485   if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
12486     return true;
12487 
12488   return false;
12489 }
12490 
12491 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
12492                                                      const SCEV *LHS,
12493                                                      const SCEV *RHS,
12494                                                      ICmpInst::Predicate FoundPred,
12495                                                      const SCEV *FoundLHS,
12496                                                      const SCEV *FoundRHS) {
12497   if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
12498     // The restriction on `FoundRHS` be lifted easily -- it exists only to
12499     // reduce the compile time impact of this optimization.
12500     return false;
12501 
12502   std::optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
12503   if (!Addend)
12504     return false;
12505 
12506   const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
12507 
12508   // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
12509   // antecedent "`FoundLHS` `FoundPred` `FoundRHS`".
12510   ConstantRange FoundLHSRange =
12511       ConstantRange::makeExactICmpRegion(FoundPred, ConstFoundRHS);
12512 
12513   // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
12514   ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
12515 
12516   // We can also compute the range of values for `LHS` that satisfy the
12517   // consequent, "`LHS` `Pred` `RHS`":
12518   const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
12519   // The antecedent implies the consequent if every value of `LHS` that
12520   // satisfies the antecedent also satisfies the consequent.
12521   return LHSRange.icmp(Pred, ConstRHS);
12522 }
12523 
12524 bool ScalarEvolution::canIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
12525                                         bool IsSigned) {
12526   assert(isKnownPositive(Stride) && "Positive stride expected!");
12527 
12528   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
12529   const SCEV *One = getOne(Stride->getType());
12530 
12531   if (IsSigned) {
12532     APInt MaxRHS = getSignedRangeMax(RHS);
12533     APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
12534     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
12535 
12536     // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
12537     return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS);
12538   }
12539 
12540   APInt MaxRHS = getUnsignedRangeMax(RHS);
12541   APInt MaxValue = APInt::getMaxValue(BitWidth);
12542   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
12543 
12544   // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
12545   return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS);
12546 }
12547 
12548 bool ScalarEvolution::canIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
12549                                         bool IsSigned) {
12550 
12551   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
12552   const SCEV *One = getOne(Stride->getType());
12553 
12554   if (IsSigned) {
12555     APInt MinRHS = getSignedRangeMin(RHS);
12556     APInt MinValue = APInt::getSignedMinValue(BitWidth);
12557     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
12558 
12559     // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
12560     return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS);
12561   }
12562 
12563   APInt MinRHS = getUnsignedRangeMin(RHS);
12564   APInt MinValue = APInt::getMinValue(BitWidth);
12565   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
12566 
12567   // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
12568   return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS);
12569 }
12570 
12571 const SCEV *ScalarEvolution::getUDivCeilSCEV(const SCEV *N, const SCEV *D) {
12572   // umin(N, 1) + floor((N - umin(N, 1)) / D)
12573   // This is equivalent to "1 + floor((N - 1) / D)" for N != 0. The umin
12574   // expression fixes the case of N=0.
12575   const SCEV *MinNOne = getUMinExpr(N, getOne(N->getType()));
12576   const SCEV *NMinusOne = getMinusSCEV(N, MinNOne);
12577   return getAddExpr(MinNOne, getUDivExpr(NMinusOne, D));
12578 }
12579 
12580 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start,
12581                                                     const SCEV *Stride,
12582                                                     const SCEV *End,
12583                                                     unsigned BitWidth,
12584                                                     bool IsSigned) {
12585   // The logic in this function assumes we can represent a positive stride.
12586   // If we can't, the backedge-taken count must be zero.
12587   if (IsSigned && BitWidth == 1)
12588     return getZero(Stride->getType());
12589 
12590   // This code below only been closely audited for negative strides in the
12591   // unsigned comparison case, it may be correct for signed comparison, but
12592   // that needs to be established.
12593   if (IsSigned && isKnownNegative(Stride))
12594     return getCouldNotCompute();
12595 
12596   // Calculate the maximum backedge count based on the range of values
12597   // permitted by Start, End, and Stride.
12598   APInt MinStart =
12599       IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start);
12600 
12601   APInt MinStride =
12602       IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride);
12603 
12604   // We assume either the stride is positive, or the backedge-taken count
12605   // is zero. So force StrideForMaxBECount to be at least one.
12606   APInt One(BitWidth, 1);
12607   APInt StrideForMaxBECount = IsSigned ? APIntOps::smax(One, MinStride)
12608                                        : APIntOps::umax(One, MinStride);
12609 
12610   APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth)
12611                             : APInt::getMaxValue(BitWidth);
12612   APInt Limit = MaxValue - (StrideForMaxBECount - 1);
12613 
12614   // Although End can be a MAX expression we estimate MaxEnd considering only
12615   // the case End = RHS of the loop termination condition. This is safe because
12616   // in the other case (End - Start) is zero, leading to a zero maximum backedge
12617   // taken count.
12618   APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit)
12619                           : APIntOps::umin(getUnsignedRangeMax(End), Limit);
12620 
12621   // MaxBECount = ceil((max(MaxEnd, MinStart) - MinStart) / Stride)
12622   MaxEnd = IsSigned ? APIntOps::smax(MaxEnd, MinStart)
12623                     : APIntOps::umax(MaxEnd, MinStart);
12624 
12625   return getUDivCeilSCEV(getConstant(MaxEnd - MinStart) /* Delta */,
12626                          getConstant(StrideForMaxBECount) /* Step */);
12627 }
12628 
12629 ScalarEvolution::ExitLimit
12630 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
12631                                   const Loop *L, bool IsSigned,
12632                                   bool ControlsOnlyExit, bool AllowPredicates) {
12633   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
12634 
12635   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
12636   bool PredicatedIV = false;
12637 
12638   auto canAssumeNoSelfWrap = [&](const SCEVAddRecExpr *AR) {
12639     // Can we prove this loop *must* be UB if overflow of IV occurs?
12640     // Reasoning goes as follows:
12641     // * Suppose the IV did self wrap.
12642     // * If Stride evenly divides the iteration space, then once wrap
12643     //   occurs, the loop must revisit the same values.
12644     // * We know that RHS is invariant, and that none of those values
12645     //   caused this exit to be taken previously.  Thus, this exit is
12646     //   dynamically dead.
12647     // * If this is the sole exit, then a dead exit implies the loop
12648     //   must be infinite if there are no abnormal exits.
12649     // * If the loop were infinite, then it must either not be mustprogress
12650     //   or have side effects. Otherwise, it must be UB.
12651     // * It can't (by assumption), be UB so we have contradicted our
12652     //   premise and can conclude the IV did not in fact self-wrap.
12653     if (!isLoopInvariant(RHS, L))
12654       return false;
12655 
12656     auto *StrideC = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this));
12657     if (!StrideC || !StrideC->getAPInt().isPowerOf2())
12658       return false;
12659 
12660     if (!ControlsOnlyExit || !loopHasNoAbnormalExits(L))
12661       return false;
12662 
12663     return loopIsFiniteByAssumption(L);
12664   };
12665 
12666   if (!IV) {
12667     if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS)) {
12668       const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(ZExt->getOperand());
12669       if (AR && AR->getLoop() == L && AR->isAffine()) {
12670         auto canProveNUW = [&]() {
12671           // We can use the comparison to infer no-wrap flags only if it fully
12672           // controls the loop exit.
12673           if (!ControlsOnlyExit)
12674             return false;
12675 
12676           if (!isLoopInvariant(RHS, L))
12677             return false;
12678 
12679           if (!isKnownNonZero(AR->getStepRecurrence(*this)))
12680             // We need the sequence defined by AR to strictly increase in the
12681             // unsigned integer domain for the logic below to hold.
12682             return false;
12683 
12684           const unsigned InnerBitWidth = getTypeSizeInBits(AR->getType());
12685           const unsigned OuterBitWidth = getTypeSizeInBits(RHS->getType());
12686           // If RHS <=u Limit, then there must exist a value V in the sequence
12687           // defined by AR (e.g. {Start,+,Step}) such that V >u RHS, and
12688           // V <=u UINT_MAX.  Thus, we must exit the loop before unsigned
12689           // overflow occurs.  This limit also implies that a signed comparison
12690           // (in the wide bitwidth) is equivalent to an unsigned comparison as
12691           // the high bits on both sides must be zero.
12692           APInt StrideMax = getUnsignedRangeMax(AR->getStepRecurrence(*this));
12693           APInt Limit = APInt::getMaxValue(InnerBitWidth) - (StrideMax - 1);
12694           Limit = Limit.zext(OuterBitWidth);
12695           return getUnsignedRangeMax(applyLoopGuards(RHS, L)).ule(Limit);
12696         };
12697         auto Flags = AR->getNoWrapFlags();
12698         if (!hasFlags(Flags, SCEV::FlagNUW) && canProveNUW())
12699           Flags = setFlags(Flags, SCEV::FlagNUW);
12700 
12701         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
12702         if (AR->hasNoUnsignedWrap()) {
12703           // Emulate what getZeroExtendExpr would have done during construction
12704           // if we'd been able to infer the fact just above at that time.
12705           const SCEV *Step = AR->getStepRecurrence(*this);
12706           Type *Ty = ZExt->getType();
12707           auto *S = getAddRecExpr(
12708             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 0),
12709             getZeroExtendExpr(Step, Ty, 0), L, AR->getNoWrapFlags());
12710           IV = dyn_cast<SCEVAddRecExpr>(S);
12711         }
12712       }
12713     }
12714   }
12715 
12716 
12717   if (!IV && AllowPredicates) {
12718     // Try to make this an AddRec using runtime tests, in the first X
12719     // iterations of this loop, where X is the SCEV expression found by the
12720     // algorithm below.
12721     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
12722     PredicatedIV = true;
12723   }
12724 
12725   // Avoid weird loops
12726   if (!IV || IV->getLoop() != L || !IV->isAffine())
12727     return getCouldNotCompute();
12728 
12729   // A precondition of this method is that the condition being analyzed
12730   // reaches an exiting branch which dominates the latch.  Given that, we can
12731   // assume that an increment which violates the nowrap specification and
12732   // produces poison must cause undefined behavior when the resulting poison
12733   // value is branched upon and thus we can conclude that the backedge is
12734   // taken no more often than would be required to produce that poison value.
12735   // Note that a well defined loop can exit on the iteration which violates
12736   // the nowrap specification if there is another exit (either explicit or
12737   // implicit/exceptional) which causes the loop to execute before the
12738   // exiting instruction we're analyzing would trigger UB.
12739   auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW;
12740   bool NoWrap = ControlsOnlyExit && IV->getNoWrapFlags(WrapType);
12741   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
12742 
12743   const SCEV *Stride = IV->getStepRecurrence(*this);
12744 
12745   bool PositiveStride = isKnownPositive(Stride);
12746 
12747   // Avoid negative or zero stride values.
12748   if (!PositiveStride) {
12749     // We can compute the correct backedge taken count for loops with unknown
12750     // strides if we can prove that the loop is not an infinite loop with side
12751     // effects. Here's the loop structure we are trying to handle -
12752     //
12753     // i = start
12754     // do {
12755     //   A[i] = i;
12756     //   i += s;
12757     // } while (i < end);
12758     //
12759     // The backedge taken count for such loops is evaluated as -
12760     // (max(end, start + stride) - start - 1) /u stride
12761     //
12762     // The additional preconditions that we need to check to prove correctness
12763     // of the above formula is as follows -
12764     //
12765     // a) IV is either nuw or nsw depending upon signedness (indicated by the
12766     //    NoWrap flag).
12767     // b) the loop is guaranteed to be finite (e.g. is mustprogress and has
12768     //    no side effects within the loop)
12769     // c) loop has a single static exit (with no abnormal exits)
12770     //
12771     // Precondition a) implies that if the stride is negative, this is a single
12772     // trip loop. The backedge taken count formula reduces to zero in this case.
12773     //
12774     // Precondition b) and c) combine to imply that if rhs is invariant in L,
12775     // then a zero stride means the backedge can't be taken without executing
12776     // undefined behavior.
12777     //
12778     // The positive stride case is the same as isKnownPositive(Stride) returning
12779     // true (original behavior of the function).
12780     //
12781     if (PredicatedIV || !NoWrap || !loopIsFiniteByAssumption(L) ||
12782         !loopHasNoAbnormalExits(L))
12783       return getCouldNotCompute();
12784 
12785     if (!isKnownNonZero(Stride)) {
12786       // If we have a step of zero, and RHS isn't invariant in L, we don't know
12787       // if it might eventually be greater than start and if so, on which
12788       // iteration.  We can't even produce a useful upper bound.
12789       if (!isLoopInvariant(RHS, L))
12790         return getCouldNotCompute();
12791 
12792       // We allow a potentially zero stride, but we need to divide by stride
12793       // below.  Since the loop can't be infinite and this check must control
12794       // the sole exit, we can infer the exit must be taken on the first
12795       // iteration (e.g. backedge count = 0) if the stride is zero.  Given that,
12796       // we know the numerator in the divides below must be zero, so we can
12797       // pick an arbitrary non-zero value for the denominator (e.g. stride)
12798       // and produce the right result.
12799       // FIXME: Handle the case where Stride is poison?
12800       auto wouldZeroStrideBeUB = [&]() {
12801         // Proof by contradiction.  Suppose the stride were zero.  If we can
12802         // prove that the backedge *is* taken on the first iteration, then since
12803         // we know this condition controls the sole exit, we must have an
12804         // infinite loop.  We can't have a (well defined) infinite loop per
12805         // check just above.
12806         // Note: The (Start - Stride) term is used to get the start' term from
12807         // (start' + stride,+,stride). Remember that we only care about the
12808         // result of this expression when stride == 0 at runtime.
12809         auto *StartIfZero = getMinusSCEV(IV->getStart(), Stride);
12810         return isLoopEntryGuardedByCond(L, Cond, StartIfZero, RHS);
12811       };
12812       if (!wouldZeroStrideBeUB()) {
12813         Stride = getUMaxExpr(Stride, getOne(Stride->getType()));
12814       }
12815     }
12816   } else if (!Stride->isOne() && !NoWrap) {
12817     auto isUBOnWrap = [&]() {
12818       // From no-self-wrap, we need to then prove no-(un)signed-wrap.  This
12819       // follows trivially from the fact that every (un)signed-wrapped, but
12820       // not self-wrapped value must be LT than the last value before
12821       // (un)signed wrap.  Since we know that last value didn't exit, nor
12822       // will any smaller one.
12823       return canAssumeNoSelfWrap(IV);
12824     };
12825 
12826     // Avoid proven overflow cases: this will ensure that the backedge taken
12827     // count will not generate any unsigned overflow. Relaxed no-overflow
12828     // conditions exploit NoWrapFlags, allowing to optimize in presence of
12829     // undefined behaviors like the case of C language.
12830     if (canIVOverflowOnLT(RHS, Stride, IsSigned) && !isUBOnWrap())
12831       return getCouldNotCompute();
12832   }
12833 
12834   // On all paths just preceeding, we established the following invariant:
12835   //   IV can be assumed not to overflow up to and including the exiting
12836   //   iteration.  We proved this in one of two ways:
12837   //   1) We can show overflow doesn't occur before the exiting iteration
12838   //      1a) canIVOverflowOnLT, and b) step of one
12839   //   2) We can show that if overflow occurs, the loop must execute UB
12840   //      before any possible exit.
12841   // Note that we have not yet proved RHS invariant (in general).
12842 
12843   const SCEV *Start = IV->getStart();
12844 
12845   // Preserve pointer-typed Start/RHS to pass to isLoopEntryGuardedByCond.
12846   // If we convert to integers, isLoopEntryGuardedByCond will miss some cases.
12847   // Use integer-typed versions for actual computation; we can't subtract
12848   // pointers in general.
12849   const SCEV *OrigStart = Start;
12850   const SCEV *OrigRHS = RHS;
12851   if (Start->getType()->isPointerTy()) {
12852     Start = getLosslessPtrToIntExpr(Start);
12853     if (isa<SCEVCouldNotCompute>(Start))
12854       return Start;
12855   }
12856   if (RHS->getType()->isPointerTy()) {
12857     RHS = getLosslessPtrToIntExpr(RHS);
12858     if (isa<SCEVCouldNotCompute>(RHS))
12859       return RHS;
12860   }
12861 
12862   // When the RHS is not invariant, we do not know the end bound of the loop and
12863   // cannot calculate the ExactBECount needed by ExitLimit. However, we can
12864   // calculate the MaxBECount, given the start, stride and max value for the end
12865   // bound of the loop (RHS), and the fact that IV does not overflow (which is
12866   // checked above).
12867   if (!isLoopInvariant(RHS, L)) {
12868     const SCEV *MaxBECount = computeMaxBECountForLT(
12869         Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
12870     return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount,
12871                      MaxBECount, false /*MaxOrZero*/, Predicates);
12872   }
12873 
12874   // We use the expression (max(End,Start)-Start)/Stride to describe the
12875   // backedge count, as if the backedge is taken at least once max(End,Start)
12876   // is End and so the result is as above, and if not max(End,Start) is Start
12877   // so we get a backedge count of zero.
12878   const SCEV *BECount = nullptr;
12879   auto *OrigStartMinusStride = getMinusSCEV(OrigStart, Stride);
12880   assert(isAvailableAtLoopEntry(OrigStartMinusStride, L) && "Must be!");
12881   assert(isAvailableAtLoopEntry(OrigStart, L) && "Must be!");
12882   assert(isAvailableAtLoopEntry(OrigRHS, L) && "Must be!");
12883   // Can we prove (max(RHS,Start) > Start - Stride?
12884   if (isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigStart) &&
12885       isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigRHS)) {
12886     // In this case, we can use a refined formula for computing backedge taken
12887     // count.  The general formula remains:
12888     //   "End-Start /uceiling Stride" where "End = max(RHS,Start)"
12889     // We want to use the alternate formula:
12890     //   "((End - 1) - (Start - Stride)) /u Stride"
12891     // Let's do a quick case analysis to show these are equivalent under
12892     // our precondition that max(RHS,Start) > Start - Stride.
12893     // * For RHS <= Start, the backedge-taken count must be zero.
12894     //   "((End - 1) - (Start - Stride)) /u Stride" reduces to
12895     //   "((Start - 1) - (Start - Stride)) /u Stride" which simplies to
12896     //   "Stride - 1 /u Stride" which is indeed zero for all non-zero values
12897     //     of Stride.  For 0 stride, we've use umin(1,Stride) above, reducing
12898     //     this to the stride of 1 case.
12899     // * For RHS >= Start, the backedge count must be "RHS-Start /uceil Stride".
12900     //   "((End - 1) - (Start - Stride)) /u Stride" reduces to
12901     //   "((RHS - 1) - (Start - Stride)) /u Stride" reassociates to
12902     //   "((RHS - (Start - Stride) - 1) /u Stride".
12903     //   Our preconditions trivially imply no overflow in that form.
12904     const SCEV *MinusOne = getMinusOne(Stride->getType());
12905     const SCEV *Numerator =
12906         getMinusSCEV(getAddExpr(RHS, MinusOne), getMinusSCEV(Start, Stride));
12907     BECount = getUDivExpr(Numerator, Stride);
12908   }
12909 
12910   const SCEV *BECountIfBackedgeTaken = nullptr;
12911   if (!BECount) {
12912     auto canProveRHSGreaterThanEqualStart = [&]() {
12913       auto CondGE = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
12914       const SCEV *GuardedRHS = applyLoopGuards(OrigRHS, L);
12915       const SCEV *GuardedStart = applyLoopGuards(OrigStart, L);
12916 
12917       if (isLoopEntryGuardedByCond(L, CondGE, OrigRHS, OrigStart) ||
12918           isKnownPredicate(CondGE, GuardedRHS, GuardedStart))
12919         return true;
12920 
12921       // (RHS > Start - 1) implies RHS >= Start.
12922       // * "RHS >= Start" is trivially equivalent to "RHS > Start - 1" if
12923       //   "Start - 1" doesn't overflow.
12924       // * For signed comparison, if Start - 1 does overflow, it's equal
12925       //   to INT_MAX, and "RHS >s INT_MAX" is trivially false.
12926       // * For unsigned comparison, if Start - 1 does overflow, it's equal
12927       //   to UINT_MAX, and "RHS >u UINT_MAX" is trivially false.
12928       //
12929       // FIXME: Should isLoopEntryGuardedByCond do this for us?
12930       auto CondGT = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
12931       auto *StartMinusOne = getAddExpr(OrigStart,
12932                                        getMinusOne(OrigStart->getType()));
12933       return isLoopEntryGuardedByCond(L, CondGT, OrigRHS, StartMinusOne);
12934     };
12935 
12936     // If we know that RHS >= Start in the context of loop, then we know that
12937     // max(RHS, Start) = RHS at this point.
12938     const SCEV *End;
12939     if (canProveRHSGreaterThanEqualStart()) {
12940       End = RHS;
12941     } else {
12942       // If RHS < Start, the backedge will be taken zero times.  So in
12943       // general, we can write the backedge-taken count as:
12944       //
12945       //     RHS >= Start ? ceil(RHS - Start) / Stride : 0
12946       //
12947       // We convert it to the following to make it more convenient for SCEV:
12948       //
12949       //     ceil(max(RHS, Start) - Start) / Stride
12950       End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
12951 
12952       // See what would happen if we assume the backedge is taken. This is
12953       // used to compute MaxBECount.
12954       BECountIfBackedgeTaken = getUDivCeilSCEV(getMinusSCEV(RHS, Start), Stride);
12955     }
12956 
12957     // At this point, we know:
12958     //
12959     // 1. If IsSigned, Start <=s End; otherwise, Start <=u End
12960     // 2. The index variable doesn't overflow.
12961     //
12962     // Therefore, we know N exists such that
12963     // (Start + Stride * N) >= End, and computing "(Start + Stride * N)"
12964     // doesn't overflow.
12965     //
12966     // Using this information, try to prove whether the addition in
12967     // "(Start - End) + (Stride - 1)" has unsigned overflow.
12968     const SCEV *One = getOne(Stride->getType());
12969     bool MayAddOverflow = [&] {
12970       if (auto *StrideC = dyn_cast<SCEVConstant>(Stride)) {
12971         if (StrideC->getAPInt().isPowerOf2()) {
12972           // Suppose Stride is a power of two, and Start/End are unsigned
12973           // integers.  Let UMAX be the largest representable unsigned
12974           // integer.
12975           //
12976           // By the preconditions of this function, we know
12977           // "(Start + Stride * N) >= End", and this doesn't overflow.
12978           // As a formula:
12979           //
12980           //   End <= (Start + Stride * N) <= UMAX
12981           //
12982           // Subtracting Start from all the terms:
12983           //
12984           //   End - Start <= Stride * N <= UMAX - Start
12985           //
12986           // Since Start is unsigned, UMAX - Start <= UMAX.  Therefore:
12987           //
12988           //   End - Start <= Stride * N <= UMAX
12989           //
12990           // Stride * N is a multiple of Stride. Therefore,
12991           //
12992           //   End - Start <= Stride * N <= UMAX - (UMAX mod Stride)
12993           //
12994           // Since Stride is a power of two, UMAX + 1 is divisible by Stride.
12995           // Therefore, UMAX mod Stride == Stride - 1.  So we can write:
12996           //
12997           //   End - Start <= Stride * N <= UMAX - Stride - 1
12998           //
12999           // Dropping the middle term:
13000           //
13001           //   End - Start <= UMAX - Stride - 1
13002           //
13003           // Adding Stride - 1 to both sides:
13004           //
13005           //   (End - Start) + (Stride - 1) <= UMAX
13006           //
13007           // In other words, the addition doesn't have unsigned overflow.
13008           //
13009           // A similar proof works if we treat Start/End as signed values.
13010           // Just rewrite steps before "End - Start <= Stride * N <= UMAX" to
13011           // use signed max instead of unsigned max. Note that we're trying
13012           // to prove a lack of unsigned overflow in either case.
13013           return false;
13014         }
13015       }
13016       if (Start == Stride || Start == getMinusSCEV(Stride, One)) {
13017         // If Start is equal to Stride, (End - Start) + (Stride - 1) == End - 1.
13018         // If !IsSigned, 0 <u Stride == Start <=u End; so 0 <u End - 1 <u End.
13019         // If IsSigned, 0 <s Stride == Start <=s End; so 0 <s End - 1 <s End.
13020         //
13021         // If Start is equal to Stride - 1, (End - Start) + Stride - 1 == End.
13022         return false;
13023       }
13024       return true;
13025     }();
13026 
13027     const SCEV *Delta = getMinusSCEV(End, Start);
13028     if (!MayAddOverflow) {
13029       // floor((D + (S - 1)) / S)
13030       // We prefer this formulation if it's legal because it's fewer operations.
13031       BECount =
13032           getUDivExpr(getAddExpr(Delta, getMinusSCEV(Stride, One)), Stride);
13033     } else {
13034       BECount = getUDivCeilSCEV(Delta, Stride);
13035     }
13036   }
13037 
13038   const SCEV *ConstantMaxBECount;
13039   bool MaxOrZero = false;
13040   if (isa<SCEVConstant>(BECount)) {
13041     ConstantMaxBECount = BECount;
13042   } else if (BECountIfBackedgeTaken &&
13043              isa<SCEVConstant>(BECountIfBackedgeTaken)) {
13044     // If we know exactly how many times the backedge will be taken if it's
13045     // taken at least once, then the backedge count will either be that or
13046     // zero.
13047     ConstantMaxBECount = BECountIfBackedgeTaken;
13048     MaxOrZero = true;
13049   } else {
13050     ConstantMaxBECount = computeMaxBECountForLT(
13051         Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
13052   }
13053 
13054   if (isa<SCEVCouldNotCompute>(ConstantMaxBECount) &&
13055       !isa<SCEVCouldNotCompute>(BECount))
13056     ConstantMaxBECount = getConstant(getUnsignedRangeMax(BECount));
13057 
13058   const SCEV *SymbolicMaxBECount =
13059       isa<SCEVCouldNotCompute>(BECount) ? ConstantMaxBECount : BECount;
13060   return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount, MaxOrZero,
13061                    Predicates);
13062 }
13063 
13064 ScalarEvolution::ExitLimit ScalarEvolution::howManyGreaterThans(
13065     const SCEV *LHS, const SCEV *RHS, const Loop *L, bool IsSigned,
13066     bool ControlsOnlyExit, bool AllowPredicates) {
13067   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
13068   // We handle only IV > Invariant
13069   if (!isLoopInvariant(RHS, L))
13070     return getCouldNotCompute();
13071 
13072   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
13073   if (!IV && AllowPredicates)
13074     // Try to make this an AddRec using runtime tests, in the first X
13075     // iterations of this loop, where X is the SCEV expression found by the
13076     // algorithm below.
13077     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
13078 
13079   // Avoid weird loops
13080   if (!IV || IV->getLoop() != L || !IV->isAffine())
13081     return getCouldNotCompute();
13082 
13083   auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW;
13084   bool NoWrap = ControlsOnlyExit && IV->getNoWrapFlags(WrapType);
13085   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
13086 
13087   const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
13088 
13089   // Avoid negative or zero stride values
13090   if (!isKnownPositive(Stride))
13091     return getCouldNotCompute();
13092 
13093   // Avoid proven overflow cases: this will ensure that the backedge taken count
13094   // will not generate any unsigned overflow. Relaxed no-overflow conditions
13095   // exploit NoWrapFlags, allowing to optimize in presence of undefined
13096   // behaviors like the case of C language.
13097   if (!Stride->isOne() && !NoWrap)
13098     if (canIVOverflowOnGT(RHS, Stride, IsSigned))
13099       return getCouldNotCompute();
13100 
13101   const SCEV *Start = IV->getStart();
13102   const SCEV *End = RHS;
13103   if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) {
13104     // If we know that Start >= RHS in the context of loop, then we know that
13105     // min(RHS, Start) = RHS at this point.
13106     if (isLoopEntryGuardedByCond(
13107             L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, RHS))
13108       End = RHS;
13109     else
13110       End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
13111   }
13112 
13113   if (Start->getType()->isPointerTy()) {
13114     Start = getLosslessPtrToIntExpr(Start);
13115     if (isa<SCEVCouldNotCompute>(Start))
13116       return Start;
13117   }
13118   if (End->getType()->isPointerTy()) {
13119     End = getLosslessPtrToIntExpr(End);
13120     if (isa<SCEVCouldNotCompute>(End))
13121       return End;
13122   }
13123 
13124   // Compute ((Start - End) + (Stride - 1)) / Stride.
13125   // FIXME: This can overflow. Holding off on fixing this for now;
13126   // howManyGreaterThans will hopefully be gone soon.
13127   const SCEV *One = getOne(Stride->getType());
13128   const SCEV *BECount = getUDivExpr(
13129       getAddExpr(getMinusSCEV(Start, End), getMinusSCEV(Stride, One)), Stride);
13130 
13131   APInt MaxStart = IsSigned ? getSignedRangeMax(Start)
13132                             : getUnsignedRangeMax(Start);
13133 
13134   APInt MinStride = IsSigned ? getSignedRangeMin(Stride)
13135                              : getUnsignedRangeMin(Stride);
13136 
13137   unsigned BitWidth = getTypeSizeInBits(LHS->getType());
13138   APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
13139                          : APInt::getMinValue(BitWidth) + (MinStride - 1);
13140 
13141   // Although End can be a MIN expression we estimate MinEnd considering only
13142   // the case End = RHS. This is safe because in the other case (Start - End)
13143   // is zero, leading to a zero maximum backedge taken count.
13144   APInt MinEnd =
13145     IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit)
13146              : APIntOps::umax(getUnsignedRangeMin(RHS), Limit);
13147 
13148   const SCEV *ConstantMaxBECount =
13149       isa<SCEVConstant>(BECount)
13150           ? BECount
13151           : getUDivCeilSCEV(getConstant(MaxStart - MinEnd),
13152                             getConstant(MinStride));
13153 
13154   if (isa<SCEVCouldNotCompute>(ConstantMaxBECount))
13155     ConstantMaxBECount = BECount;
13156   const SCEV *SymbolicMaxBECount =
13157       isa<SCEVCouldNotCompute>(BECount) ? ConstantMaxBECount : BECount;
13158 
13159   return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount, false,
13160                    Predicates);
13161 }
13162 
13163 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range,
13164                                                     ScalarEvolution &SE) const {
13165   if (Range.isFullSet())  // Infinite loop.
13166     return SE.getCouldNotCompute();
13167 
13168   // If the start is a non-zero constant, shift the range to simplify things.
13169   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
13170     if (!SC->getValue()->isZero()) {
13171       SmallVector<const SCEV *, 4> Operands(operands());
13172       Operands[0] = SE.getZero(SC->getType());
13173       const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
13174                                              getNoWrapFlags(FlagNW));
13175       if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
13176         return ShiftedAddRec->getNumIterationsInRange(
13177             Range.subtract(SC->getAPInt()), SE);
13178       // This is strange and shouldn't happen.
13179       return SE.getCouldNotCompute();
13180     }
13181 
13182   // The only time we can solve this is when we have all constant indices.
13183   // Otherwise, we cannot determine the overflow conditions.
13184   if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
13185     return SE.getCouldNotCompute();
13186 
13187   // Okay at this point we know that all elements of the chrec are constants and
13188   // that the start element is zero.
13189 
13190   // First check to see if the range contains zero.  If not, the first
13191   // iteration exits.
13192   unsigned BitWidth = SE.getTypeSizeInBits(getType());
13193   if (!Range.contains(APInt(BitWidth, 0)))
13194     return SE.getZero(getType());
13195 
13196   if (isAffine()) {
13197     // If this is an affine expression then we have this situation:
13198     //   Solve {0,+,A} in Range  ===  Ax in Range
13199 
13200     // We know that zero is in the range.  If A is positive then we know that
13201     // the upper value of the range must be the first possible exit value.
13202     // If A is negative then the lower of the range is the last possible loop
13203     // value.  Also note that we already checked for a full range.
13204     APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
13205     APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower();
13206 
13207     // The exit value should be (End+A)/A.
13208     APInt ExitVal = (End + A).udiv(A);
13209     ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
13210 
13211     // Evaluate at the exit value.  If we really did fall out of the valid
13212     // range, then we computed our trip count, otherwise wrap around or other
13213     // things must have happened.
13214     ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
13215     if (Range.contains(Val->getValue()))
13216       return SE.getCouldNotCompute();  // Something strange happened
13217 
13218     // Ensure that the previous value is in the range.
13219     assert(Range.contains(
13220            EvaluateConstantChrecAtConstant(this,
13221            ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&
13222            "Linear scev computation is off in a bad way!");
13223     return SE.getConstant(ExitValue);
13224   }
13225 
13226   if (isQuadratic()) {
13227     if (auto S = SolveQuadraticAddRecRange(this, Range, SE))
13228       return SE.getConstant(*S);
13229   }
13230 
13231   return SE.getCouldNotCompute();
13232 }
13233 
13234 const SCEVAddRecExpr *
13235 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const {
13236   assert(getNumOperands() > 1 && "AddRec with zero step?");
13237   // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)),
13238   // but in this case we cannot guarantee that the value returned will be an
13239   // AddRec because SCEV does not have a fixed point where it stops
13240   // simplification: it is legal to return ({rec1} + {rec2}). For example, it
13241   // may happen if we reach arithmetic depth limit while simplifying. So we
13242   // construct the returned value explicitly.
13243   SmallVector<const SCEV *, 3> Ops;
13244   // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and
13245   // (this + Step) is {A+B,+,B+C,+...,+,N}.
13246   for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i)
13247     Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1)));
13248   // We know that the last operand is not a constant zero (otherwise it would
13249   // have been popped out earlier). This guarantees us that if the result has
13250   // the same last operand, then it will also not be popped out, meaning that
13251   // the returned value will be an AddRec.
13252   const SCEV *Last = getOperand(getNumOperands() - 1);
13253   assert(!Last->isZero() && "Recurrency with zero step?");
13254   Ops.push_back(Last);
13255   return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(),
13256                                                SCEV::FlagAnyWrap));
13257 }
13258 
13259 // Return true when S contains at least an undef value.
13260 bool ScalarEvolution::containsUndefs(const SCEV *S) const {
13261   return SCEVExprContains(S, [](const SCEV *S) {
13262     if (const auto *SU = dyn_cast<SCEVUnknown>(S))
13263       return isa<UndefValue>(SU->getValue());
13264     return false;
13265   });
13266 }
13267 
13268 // Return true when S contains a value that is a nullptr.
13269 bool ScalarEvolution::containsErasedValue(const SCEV *S) const {
13270   return SCEVExprContains(S, [](const SCEV *S) {
13271     if (const auto *SU = dyn_cast<SCEVUnknown>(S))
13272       return SU->getValue() == nullptr;
13273     return false;
13274   });
13275 }
13276 
13277 /// Return the size of an element read or written by Inst.
13278 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
13279   Type *Ty;
13280   if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
13281     Ty = Store->getValueOperand()->getType();
13282   else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
13283     Ty = Load->getType();
13284   else
13285     return nullptr;
13286 
13287   Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
13288   return getSizeOfExpr(ETy, Ty);
13289 }
13290 
13291 //===----------------------------------------------------------------------===//
13292 //                   SCEVCallbackVH Class Implementation
13293 //===----------------------------------------------------------------------===//
13294 
13295 void ScalarEvolution::SCEVCallbackVH::deleted() {
13296   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
13297   if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
13298     SE->ConstantEvolutionLoopExitValue.erase(PN);
13299   SE->eraseValueFromMap(getValPtr());
13300   // this now dangles!
13301 }
13302 
13303 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
13304   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
13305 
13306   // Forget all the expressions associated with users of the old value,
13307   // so that future queries will recompute the expressions using the new
13308   // value.
13309   SE->forgetValue(getValPtr());
13310   // this now dangles!
13311 }
13312 
13313 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
13314   : CallbackVH(V), SE(se) {}
13315 
13316 //===----------------------------------------------------------------------===//
13317 //                   ScalarEvolution Class Implementation
13318 //===----------------------------------------------------------------------===//
13319 
13320 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
13321                                  AssumptionCache &AC, DominatorTree &DT,
13322                                  LoopInfo &LI)
13323     : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
13324       CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64),
13325       LoopDispositions(64), BlockDispositions(64) {
13326   // To use guards for proving predicates, we need to scan every instruction in
13327   // relevant basic blocks, and not just terminators.  Doing this is a waste of
13328   // time if the IR does not actually contain any calls to
13329   // @llvm.experimental.guard, so do a quick check and remember this beforehand.
13330   //
13331   // This pessimizes the case where a pass that preserves ScalarEvolution wants
13332   // to _add_ guards to the module when there weren't any before, and wants
13333   // ScalarEvolution to optimize based on those guards.  For now we prefer to be
13334   // efficient in lieu of being smart in that rather obscure case.
13335 
13336   auto *GuardDecl = F.getParent()->getFunction(
13337       Intrinsic::getName(Intrinsic::experimental_guard));
13338   HasGuards = GuardDecl && !GuardDecl->use_empty();
13339 }
13340 
13341 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
13342     : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT),
13343       LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
13344       ValueExprMap(std::move(Arg.ValueExprMap)),
13345       PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
13346       PendingPhiRanges(std::move(Arg.PendingPhiRanges)),
13347       PendingMerges(std::move(Arg.PendingMerges)),
13348       ConstantMultipleCache(std::move(Arg.ConstantMultipleCache)),
13349       BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
13350       PredicatedBackedgeTakenCounts(
13351           std::move(Arg.PredicatedBackedgeTakenCounts)),
13352       BECountUsers(std::move(Arg.BECountUsers)),
13353       ConstantEvolutionLoopExitValue(
13354           std::move(Arg.ConstantEvolutionLoopExitValue)),
13355       ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
13356       ValuesAtScopesUsers(std::move(Arg.ValuesAtScopesUsers)),
13357       LoopDispositions(std::move(Arg.LoopDispositions)),
13358       LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
13359       BlockDispositions(std::move(Arg.BlockDispositions)),
13360       SCEVUsers(std::move(Arg.SCEVUsers)),
13361       UnsignedRanges(std::move(Arg.UnsignedRanges)),
13362       SignedRanges(std::move(Arg.SignedRanges)),
13363       UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
13364       UniquePreds(std::move(Arg.UniquePreds)),
13365       SCEVAllocator(std::move(Arg.SCEVAllocator)),
13366       LoopUsers(std::move(Arg.LoopUsers)),
13367       PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)),
13368       FirstUnknown(Arg.FirstUnknown) {
13369   Arg.FirstUnknown = nullptr;
13370 }
13371 
13372 ScalarEvolution::~ScalarEvolution() {
13373   // Iterate through all the SCEVUnknown instances and call their
13374   // destructors, so that they release their references to their values.
13375   for (SCEVUnknown *U = FirstUnknown; U;) {
13376     SCEVUnknown *Tmp = U;
13377     U = U->Next;
13378     Tmp->~SCEVUnknown();
13379   }
13380   FirstUnknown = nullptr;
13381 
13382   ExprValueMap.clear();
13383   ValueExprMap.clear();
13384   HasRecMap.clear();
13385   BackedgeTakenCounts.clear();
13386   PredicatedBackedgeTakenCounts.clear();
13387 
13388   assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
13389   assert(PendingPhiRanges.empty() && "getRangeRef garbage");
13390   assert(PendingMerges.empty() && "isImpliedViaMerge garbage");
13391   assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
13392   assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
13393 }
13394 
13395 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
13396   return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
13397 }
13398 
13399 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
13400                           const Loop *L) {
13401   // Print all inner loops first
13402   for (Loop *I : *L)
13403     PrintLoopInfo(OS, SE, I);
13404 
13405   OS << "Loop ";
13406   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
13407   OS << ": ";
13408 
13409   SmallVector<BasicBlock *, 8> ExitingBlocks;
13410   L->getExitingBlocks(ExitingBlocks);
13411   if (ExitingBlocks.size() != 1)
13412     OS << "<multiple exits> ";
13413 
13414   if (SE->hasLoopInvariantBackedgeTakenCount(L))
13415     OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L) << "\n";
13416   else
13417     OS << "Unpredictable backedge-taken count.\n";
13418 
13419   if (ExitingBlocks.size() > 1)
13420     for (BasicBlock *ExitingBlock : ExitingBlocks) {
13421       OS << "  exit count for " << ExitingBlock->getName() << ": "
13422          << *SE->getExitCount(L, ExitingBlock) << "\n";
13423     }
13424 
13425   OS << "Loop ";
13426   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
13427   OS << ": ";
13428 
13429   auto *ConstantBTC = SE->getConstantMaxBackedgeTakenCount(L);
13430   if (!isa<SCEVCouldNotCompute>(ConstantBTC)) {
13431     OS << "constant max backedge-taken count is " << *ConstantBTC;
13432     if (SE->isBackedgeTakenCountMaxOrZero(L))
13433       OS << ", actual taken count either this or zero.";
13434   } else {
13435     OS << "Unpredictable constant max backedge-taken count. ";
13436   }
13437 
13438   OS << "\n"
13439         "Loop ";
13440   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
13441   OS << ": ";
13442 
13443   auto *SymbolicBTC = SE->getSymbolicMaxBackedgeTakenCount(L);
13444   if (!isa<SCEVCouldNotCompute>(SymbolicBTC)) {
13445     OS << "symbolic max backedge-taken count is " << *SymbolicBTC;
13446     if (SE->isBackedgeTakenCountMaxOrZero(L))
13447       OS << ", actual taken count either this or zero.";
13448   } else {
13449     OS << "Unpredictable symbolic max backedge-taken count. ";
13450   }
13451 
13452   OS << "\n";
13453   if (ExitingBlocks.size() > 1)
13454     for (BasicBlock *ExitingBlock : ExitingBlocks) {
13455       OS << "  symbolic max exit count for " << ExitingBlock->getName() << ": "
13456          << *SE->getExitCount(L, ExitingBlock, ScalarEvolution::SymbolicMaximum)
13457          << "\n";
13458     }
13459 
13460   OS << "Loop ";
13461   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
13462   OS << ": ";
13463 
13464   SmallVector<const SCEVPredicate *, 4> Preds;
13465   auto PBT = SE->getPredicatedBackedgeTakenCount(L, Preds);
13466   if (!isa<SCEVCouldNotCompute>(PBT)) {
13467     OS << "Predicated backedge-taken count is " << *PBT << "\n";
13468     OS << " Predicates:\n";
13469     for (const auto *P : Preds)
13470       P->print(OS, 4);
13471   } else {
13472     OS << "Unpredictable predicated backedge-taken count.\n";
13473   }
13474 
13475   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
13476     OS << "Loop ";
13477     L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
13478     OS << ": ";
13479     OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
13480   }
13481 }
13482 
13483 namespace llvm {
13484 raw_ostream &operator<<(raw_ostream &OS, ScalarEvolution::LoopDisposition LD) {
13485   switch (LD) {
13486   case ScalarEvolution::LoopVariant:
13487     OS << "Variant";
13488     break;
13489   case ScalarEvolution::LoopInvariant:
13490     OS << "Invariant";
13491     break;
13492   case ScalarEvolution::LoopComputable:
13493     OS << "Computable";
13494     break;
13495   }
13496   return OS;
13497 }
13498 
13499 raw_ostream &operator<<(raw_ostream &OS, ScalarEvolution::BlockDisposition BD) {
13500   switch (BD) {
13501   case ScalarEvolution::DoesNotDominateBlock:
13502     OS << "DoesNotDominate";
13503     break;
13504   case ScalarEvolution::DominatesBlock:
13505     OS << "Dominates";
13506     break;
13507   case ScalarEvolution::ProperlyDominatesBlock:
13508     OS << "ProperlyDominates";
13509     break;
13510   }
13511   return OS;
13512 }
13513 }
13514 
13515 void ScalarEvolution::print(raw_ostream &OS) const {
13516   // ScalarEvolution's implementation of the print method is to print
13517   // out SCEV values of all instructions that are interesting. Doing
13518   // this potentially causes it to create new SCEV objects though,
13519   // which technically conflicts with the const qualifier. This isn't
13520   // observable from outside the class though, so casting away the
13521   // const isn't dangerous.
13522   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
13523 
13524   if (ClassifyExpressions) {
13525     OS << "Classifying expressions for: ";
13526     F.printAsOperand(OS, /*PrintType=*/false);
13527     OS << "\n";
13528     for (Instruction &I : instructions(F))
13529       if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
13530         OS << I << '\n';
13531         OS << "  -->  ";
13532         const SCEV *SV = SE.getSCEV(&I);
13533         SV->print(OS);
13534         if (!isa<SCEVCouldNotCompute>(SV)) {
13535           OS << " U: ";
13536           SE.getUnsignedRange(SV).print(OS);
13537           OS << " S: ";
13538           SE.getSignedRange(SV).print(OS);
13539         }
13540 
13541         const Loop *L = LI.getLoopFor(I.getParent());
13542 
13543         const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
13544         if (AtUse != SV) {
13545           OS << "  -->  ";
13546           AtUse->print(OS);
13547           if (!isa<SCEVCouldNotCompute>(AtUse)) {
13548             OS << " U: ";
13549             SE.getUnsignedRange(AtUse).print(OS);
13550             OS << " S: ";
13551             SE.getSignedRange(AtUse).print(OS);
13552           }
13553         }
13554 
13555         if (L) {
13556           OS << "\t\t" "Exits: ";
13557           const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
13558           if (!SE.isLoopInvariant(ExitValue, L)) {
13559             OS << "<<Unknown>>";
13560           } else {
13561             OS << *ExitValue;
13562           }
13563 
13564           bool First = true;
13565           for (const auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
13566             if (First) {
13567               OS << "\t\t" "LoopDispositions: { ";
13568               First = false;
13569             } else {
13570               OS << ", ";
13571             }
13572 
13573             Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
13574             OS << ": " << SE.getLoopDisposition(SV, Iter);
13575           }
13576 
13577           for (const auto *InnerL : depth_first(L)) {
13578             if (InnerL == L)
13579               continue;
13580             if (First) {
13581               OS << "\t\t" "LoopDispositions: { ";
13582               First = false;
13583             } else {
13584               OS << ", ";
13585             }
13586 
13587             InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
13588             OS << ": " << SE.getLoopDisposition(SV, InnerL);
13589           }
13590 
13591           OS << " }";
13592         }
13593 
13594         OS << "\n";
13595       }
13596   }
13597 
13598   OS << "Determining loop execution counts for: ";
13599   F.printAsOperand(OS, /*PrintType=*/false);
13600   OS << "\n";
13601   for (Loop *I : LI)
13602     PrintLoopInfo(OS, &SE, I);
13603 }
13604 
13605 ScalarEvolution::LoopDisposition
13606 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
13607   auto &Values = LoopDispositions[S];
13608   for (auto &V : Values) {
13609     if (V.getPointer() == L)
13610       return V.getInt();
13611   }
13612   Values.emplace_back(L, LoopVariant);
13613   LoopDisposition D = computeLoopDisposition(S, L);
13614   auto &Values2 = LoopDispositions[S];
13615   for (auto &V : llvm::reverse(Values2)) {
13616     if (V.getPointer() == L) {
13617       V.setInt(D);
13618       break;
13619     }
13620   }
13621   return D;
13622 }
13623 
13624 ScalarEvolution::LoopDisposition
13625 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
13626   switch (S->getSCEVType()) {
13627   case scConstant:
13628   case scVScale:
13629     return LoopInvariant;
13630   case scAddRecExpr: {
13631     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
13632 
13633     // If L is the addrec's loop, it's computable.
13634     if (AR->getLoop() == L)
13635       return LoopComputable;
13636 
13637     // Add recurrences are never invariant in the function-body (null loop).
13638     if (!L)
13639       return LoopVariant;
13640 
13641     // Everything that is not defined at loop entry is variant.
13642     if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader()))
13643       return LoopVariant;
13644     assert(!L->contains(AR->getLoop()) && "Containing loop's header does not"
13645            " dominate the contained loop's header?");
13646 
13647     // This recurrence is invariant w.r.t. L if AR's loop contains L.
13648     if (AR->getLoop()->contains(L))
13649       return LoopInvariant;
13650 
13651     // This recurrence is variant w.r.t. L if any of its operands
13652     // are variant.
13653     for (const auto *Op : AR->operands())
13654       if (!isLoopInvariant(Op, L))
13655         return LoopVariant;
13656 
13657     // Otherwise it's loop-invariant.
13658     return LoopInvariant;
13659   }
13660   case scTruncate:
13661   case scZeroExtend:
13662   case scSignExtend:
13663   case scPtrToInt:
13664   case scAddExpr:
13665   case scMulExpr:
13666   case scUDivExpr:
13667   case scUMaxExpr:
13668   case scSMaxExpr:
13669   case scUMinExpr:
13670   case scSMinExpr:
13671   case scSequentialUMinExpr: {
13672     bool HasVarying = false;
13673     for (const auto *Op : S->operands()) {
13674       LoopDisposition D = getLoopDisposition(Op, L);
13675       if (D == LoopVariant)
13676         return LoopVariant;
13677       if (D == LoopComputable)
13678         HasVarying = true;
13679     }
13680     return HasVarying ? LoopComputable : LoopInvariant;
13681   }
13682   case scUnknown:
13683     // All non-instruction values are loop invariant.  All instructions are loop
13684     // invariant if they are not contained in the specified loop.
13685     // Instructions are never considered invariant in the function body
13686     // (null loop) because they are defined within the "loop".
13687     if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
13688       return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
13689     return LoopInvariant;
13690   case scCouldNotCompute:
13691     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
13692   }
13693   llvm_unreachable("Unknown SCEV kind!");
13694 }
13695 
13696 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
13697   return getLoopDisposition(S, L) == LoopInvariant;
13698 }
13699 
13700 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
13701   return getLoopDisposition(S, L) == LoopComputable;
13702 }
13703 
13704 ScalarEvolution::BlockDisposition
13705 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
13706   auto &Values = BlockDispositions[S];
13707   for (auto &V : Values) {
13708     if (V.getPointer() == BB)
13709       return V.getInt();
13710   }
13711   Values.emplace_back(BB, DoesNotDominateBlock);
13712   BlockDisposition D = computeBlockDisposition(S, BB);
13713   auto &Values2 = BlockDispositions[S];
13714   for (auto &V : llvm::reverse(Values2)) {
13715     if (V.getPointer() == BB) {
13716       V.setInt(D);
13717       break;
13718     }
13719   }
13720   return D;
13721 }
13722 
13723 ScalarEvolution::BlockDisposition
13724 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
13725   switch (S->getSCEVType()) {
13726   case scConstant:
13727   case scVScale:
13728     return ProperlyDominatesBlock;
13729   case scAddRecExpr: {
13730     // This uses a "dominates" query instead of "properly dominates" query
13731     // to test for proper dominance too, because the instruction which
13732     // produces the addrec's value is a PHI, and a PHI effectively properly
13733     // dominates its entire containing block.
13734     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
13735     if (!DT.dominates(AR->getLoop()->getHeader(), BB))
13736       return DoesNotDominateBlock;
13737 
13738     // Fall through into SCEVNAryExpr handling.
13739     [[fallthrough]];
13740   }
13741   case scTruncate:
13742   case scZeroExtend:
13743   case scSignExtend:
13744   case scPtrToInt:
13745   case scAddExpr:
13746   case scMulExpr:
13747   case scUDivExpr:
13748   case scUMaxExpr:
13749   case scSMaxExpr:
13750   case scUMinExpr:
13751   case scSMinExpr:
13752   case scSequentialUMinExpr: {
13753     bool Proper = true;
13754     for (const SCEV *NAryOp : S->operands()) {
13755       BlockDisposition D = getBlockDisposition(NAryOp, BB);
13756       if (D == DoesNotDominateBlock)
13757         return DoesNotDominateBlock;
13758       if (D == DominatesBlock)
13759         Proper = false;
13760     }
13761     return Proper ? ProperlyDominatesBlock : DominatesBlock;
13762   }
13763   case scUnknown:
13764     if (Instruction *I =
13765           dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
13766       if (I->getParent() == BB)
13767         return DominatesBlock;
13768       if (DT.properlyDominates(I->getParent(), BB))
13769         return ProperlyDominatesBlock;
13770       return DoesNotDominateBlock;
13771     }
13772     return ProperlyDominatesBlock;
13773   case scCouldNotCompute:
13774     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
13775   }
13776   llvm_unreachable("Unknown SCEV kind!");
13777 }
13778 
13779 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
13780   return getBlockDisposition(S, BB) >= DominatesBlock;
13781 }
13782 
13783 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
13784   return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
13785 }
13786 
13787 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
13788   return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; });
13789 }
13790 
13791 void ScalarEvolution::forgetBackedgeTakenCounts(const Loop *L,
13792                                                 bool Predicated) {
13793   auto &BECounts =
13794       Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts;
13795   auto It = BECounts.find(L);
13796   if (It != BECounts.end()) {
13797     for (const ExitNotTakenInfo &ENT : It->second.ExitNotTaken) {
13798       for (const SCEV *S : {ENT.ExactNotTaken, ENT.SymbolicMaxNotTaken}) {
13799         if (!isa<SCEVConstant>(S)) {
13800           auto UserIt = BECountUsers.find(S);
13801           assert(UserIt != BECountUsers.end());
13802           UserIt->second.erase({L, Predicated});
13803         }
13804       }
13805     }
13806     BECounts.erase(It);
13807   }
13808 }
13809 
13810 void ScalarEvolution::forgetMemoizedResults(ArrayRef<const SCEV *> SCEVs) {
13811   SmallPtrSet<const SCEV *, 8> ToForget(SCEVs.begin(), SCEVs.end());
13812   SmallVector<const SCEV *, 8> Worklist(ToForget.begin(), ToForget.end());
13813 
13814   while (!Worklist.empty()) {
13815     const SCEV *Curr = Worklist.pop_back_val();
13816     auto Users = SCEVUsers.find(Curr);
13817     if (Users != SCEVUsers.end())
13818       for (const auto *User : Users->second)
13819         if (ToForget.insert(User).second)
13820           Worklist.push_back(User);
13821   }
13822 
13823   for (const auto *S : ToForget)
13824     forgetMemoizedResultsImpl(S);
13825 
13826   for (auto I = PredicatedSCEVRewrites.begin();
13827        I != PredicatedSCEVRewrites.end();) {
13828     std::pair<const SCEV *, const Loop *> Entry = I->first;
13829     if (ToForget.count(Entry.first))
13830       PredicatedSCEVRewrites.erase(I++);
13831     else
13832       ++I;
13833   }
13834 }
13835 
13836 void ScalarEvolution::forgetMemoizedResultsImpl(const SCEV *S) {
13837   LoopDispositions.erase(S);
13838   BlockDispositions.erase(S);
13839   UnsignedRanges.erase(S);
13840   SignedRanges.erase(S);
13841   HasRecMap.erase(S);
13842   ConstantMultipleCache.erase(S);
13843 
13844   if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) {
13845     UnsignedWrapViaInductionTried.erase(AR);
13846     SignedWrapViaInductionTried.erase(AR);
13847   }
13848 
13849   auto ExprIt = ExprValueMap.find(S);
13850   if (ExprIt != ExprValueMap.end()) {
13851     for (Value *V : ExprIt->second) {
13852       auto ValueIt = ValueExprMap.find_as(V);
13853       if (ValueIt != ValueExprMap.end())
13854         ValueExprMap.erase(ValueIt);
13855     }
13856     ExprValueMap.erase(ExprIt);
13857   }
13858 
13859   auto ScopeIt = ValuesAtScopes.find(S);
13860   if (ScopeIt != ValuesAtScopes.end()) {
13861     for (const auto &Pair : ScopeIt->second)
13862       if (!isa_and_nonnull<SCEVConstant>(Pair.second))
13863         llvm::erase(ValuesAtScopesUsers[Pair.second],
13864                     std::make_pair(Pair.first, S));
13865     ValuesAtScopes.erase(ScopeIt);
13866   }
13867 
13868   auto ScopeUserIt = ValuesAtScopesUsers.find(S);
13869   if (ScopeUserIt != ValuesAtScopesUsers.end()) {
13870     for (const auto &Pair : ScopeUserIt->second)
13871       llvm::erase(ValuesAtScopes[Pair.second], std::make_pair(Pair.first, S));
13872     ValuesAtScopesUsers.erase(ScopeUserIt);
13873   }
13874 
13875   auto BEUsersIt = BECountUsers.find(S);
13876   if (BEUsersIt != BECountUsers.end()) {
13877     // Work on a copy, as forgetBackedgeTakenCounts() will modify the original.
13878     auto Copy = BEUsersIt->second;
13879     for (const auto &Pair : Copy)
13880       forgetBackedgeTakenCounts(Pair.getPointer(), Pair.getInt());
13881     BECountUsers.erase(BEUsersIt);
13882   }
13883 
13884   auto FoldUser = FoldCacheUser.find(S);
13885   if (FoldUser != FoldCacheUser.end())
13886     for (auto &KV : FoldUser->second)
13887       FoldCache.erase(KV);
13888   FoldCacheUser.erase(S);
13889 }
13890 
13891 void
13892 ScalarEvolution::getUsedLoops(const SCEV *S,
13893                               SmallPtrSetImpl<const Loop *> &LoopsUsed) {
13894   struct FindUsedLoops {
13895     FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed)
13896         : LoopsUsed(LoopsUsed) {}
13897     SmallPtrSetImpl<const Loop *> &LoopsUsed;
13898     bool follow(const SCEV *S) {
13899       if (auto *AR = dyn_cast<SCEVAddRecExpr>(S))
13900         LoopsUsed.insert(AR->getLoop());
13901       return true;
13902     }
13903 
13904     bool isDone() const { return false; }
13905   };
13906 
13907   FindUsedLoops F(LoopsUsed);
13908   SCEVTraversal<FindUsedLoops>(F).visitAll(S);
13909 }
13910 
13911 void ScalarEvolution::getReachableBlocks(
13912     SmallPtrSetImpl<BasicBlock *> &Reachable, Function &F) {
13913   SmallVector<BasicBlock *> Worklist;
13914   Worklist.push_back(&F.getEntryBlock());
13915   while (!Worklist.empty()) {
13916     BasicBlock *BB = Worklist.pop_back_val();
13917     if (!Reachable.insert(BB).second)
13918       continue;
13919 
13920     Value *Cond;
13921     BasicBlock *TrueBB, *FalseBB;
13922     if (match(BB->getTerminator(), m_Br(m_Value(Cond), m_BasicBlock(TrueBB),
13923                                         m_BasicBlock(FalseBB)))) {
13924       if (auto *C = dyn_cast<ConstantInt>(Cond)) {
13925         Worklist.push_back(C->isOne() ? TrueBB : FalseBB);
13926         continue;
13927       }
13928 
13929       if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
13930         const SCEV *L = getSCEV(Cmp->getOperand(0));
13931         const SCEV *R = getSCEV(Cmp->getOperand(1));
13932         if (isKnownPredicateViaConstantRanges(Cmp->getPredicate(), L, R)) {
13933           Worklist.push_back(TrueBB);
13934           continue;
13935         }
13936         if (isKnownPredicateViaConstantRanges(Cmp->getInversePredicate(), L,
13937                                               R)) {
13938           Worklist.push_back(FalseBB);
13939           continue;
13940         }
13941       }
13942     }
13943 
13944     append_range(Worklist, successors(BB));
13945   }
13946 }
13947 
13948 void ScalarEvolution::verify() const {
13949   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
13950   ScalarEvolution SE2(F, TLI, AC, DT, LI);
13951 
13952   SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end());
13953 
13954   // Map's SCEV expressions from one ScalarEvolution "universe" to another.
13955   struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> {
13956     SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {}
13957 
13958     const SCEV *visitConstant(const SCEVConstant *Constant) {
13959       return SE.getConstant(Constant->getAPInt());
13960     }
13961 
13962     const SCEV *visitUnknown(const SCEVUnknown *Expr) {
13963       return SE.getUnknown(Expr->getValue());
13964     }
13965 
13966     const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
13967       return SE.getCouldNotCompute();
13968     }
13969   };
13970 
13971   SCEVMapper SCM(SE2);
13972   SmallPtrSet<BasicBlock *, 16> ReachableBlocks;
13973   SE2.getReachableBlocks(ReachableBlocks, F);
13974 
13975   auto GetDelta = [&](const SCEV *Old, const SCEV *New) -> const SCEV * {
13976     if (containsUndefs(Old) || containsUndefs(New)) {
13977       // SCEV treats "undef" as an unknown but consistent value (i.e. it does
13978       // not propagate undef aggressively).  This means we can (and do) fail
13979       // verification in cases where a transform makes a value go from "undef"
13980       // to "undef+1" (say).  The transform is fine, since in both cases the
13981       // result is "undef", but SCEV thinks the value increased by 1.
13982       return nullptr;
13983     }
13984 
13985     // Unless VerifySCEVStrict is set, we only compare constant deltas.
13986     const SCEV *Delta = SE2.getMinusSCEV(Old, New);
13987     if (!VerifySCEVStrict && !isa<SCEVConstant>(Delta))
13988       return nullptr;
13989 
13990     return Delta;
13991   };
13992 
13993   while (!LoopStack.empty()) {
13994     auto *L = LoopStack.pop_back_val();
13995     llvm::append_range(LoopStack, *L);
13996 
13997     // Only verify BECounts in reachable loops. For an unreachable loop,
13998     // any BECount is legal.
13999     if (!ReachableBlocks.contains(L->getHeader()))
14000       continue;
14001 
14002     // Only verify cached BECounts. Computing new BECounts may change the
14003     // results of subsequent SCEV uses.
14004     auto It = BackedgeTakenCounts.find(L);
14005     if (It == BackedgeTakenCounts.end())
14006       continue;
14007 
14008     auto *CurBECount =
14009         SCM.visit(It->second.getExact(L, const_cast<ScalarEvolution *>(this)));
14010     auto *NewBECount = SE2.getBackedgeTakenCount(L);
14011 
14012     if (CurBECount == SE2.getCouldNotCompute() ||
14013         NewBECount == SE2.getCouldNotCompute()) {
14014       // NB! This situation is legal, but is very suspicious -- whatever pass
14015       // change the loop to make a trip count go from could not compute to
14016       // computable or vice-versa *should have* invalidated SCEV.  However, we
14017       // choose not to assert here (for now) since we don't want false
14018       // positives.
14019       continue;
14020     }
14021 
14022     if (SE.getTypeSizeInBits(CurBECount->getType()) >
14023         SE.getTypeSizeInBits(NewBECount->getType()))
14024       NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType());
14025     else if (SE.getTypeSizeInBits(CurBECount->getType()) <
14026              SE.getTypeSizeInBits(NewBECount->getType()))
14027       CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType());
14028 
14029     const SCEV *Delta = GetDelta(CurBECount, NewBECount);
14030     if (Delta && !Delta->isZero()) {
14031       dbgs() << "Trip Count for " << *L << " Changed!\n";
14032       dbgs() << "Old: " << *CurBECount << "\n";
14033       dbgs() << "New: " << *NewBECount << "\n";
14034       dbgs() << "Delta: " << *Delta << "\n";
14035       std::abort();
14036     }
14037   }
14038 
14039   // Collect all valid loops currently in LoopInfo.
14040   SmallPtrSet<Loop *, 32> ValidLoops;
14041   SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end());
14042   while (!Worklist.empty()) {
14043     Loop *L = Worklist.pop_back_val();
14044     if (ValidLoops.insert(L).second)
14045       Worklist.append(L->begin(), L->end());
14046   }
14047   for (const auto &KV : ValueExprMap) {
14048 #ifndef NDEBUG
14049     // Check for SCEV expressions referencing invalid/deleted loops.
14050     if (auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second)) {
14051       assert(ValidLoops.contains(AR->getLoop()) &&
14052              "AddRec references invalid loop");
14053     }
14054 #endif
14055 
14056     // Check that the value is also part of the reverse map.
14057     auto It = ExprValueMap.find(KV.second);
14058     if (It == ExprValueMap.end() || !It->second.contains(KV.first)) {
14059       dbgs() << "Value " << *KV.first
14060              << " is in ValueExprMap but not in ExprValueMap\n";
14061       std::abort();
14062     }
14063 
14064     if (auto *I = dyn_cast<Instruction>(&*KV.first)) {
14065       if (!ReachableBlocks.contains(I->getParent()))
14066         continue;
14067       const SCEV *OldSCEV = SCM.visit(KV.second);
14068       const SCEV *NewSCEV = SE2.getSCEV(I);
14069       const SCEV *Delta = GetDelta(OldSCEV, NewSCEV);
14070       if (Delta && !Delta->isZero()) {
14071         dbgs() << "SCEV for value " << *I << " changed!\n"
14072                << "Old: " << *OldSCEV << "\n"
14073                << "New: " << *NewSCEV << "\n"
14074                << "Delta: " << *Delta << "\n";
14075         std::abort();
14076       }
14077     }
14078   }
14079 
14080   for (const auto &KV : ExprValueMap) {
14081     for (Value *V : KV.second) {
14082       auto It = ValueExprMap.find_as(V);
14083       if (It == ValueExprMap.end()) {
14084         dbgs() << "Value " << *V
14085                << " is in ExprValueMap but not in ValueExprMap\n";
14086         std::abort();
14087       }
14088       if (It->second != KV.first) {
14089         dbgs() << "Value " << *V << " mapped to " << *It->second
14090                << " rather than " << *KV.first << "\n";
14091         std::abort();
14092       }
14093     }
14094   }
14095 
14096   // Verify integrity of SCEV users.
14097   for (const auto &S : UniqueSCEVs) {
14098     for (const auto *Op : S.operands()) {
14099       // We do not store dependencies of constants.
14100       if (isa<SCEVConstant>(Op))
14101         continue;
14102       auto It = SCEVUsers.find(Op);
14103       if (It != SCEVUsers.end() && It->second.count(&S))
14104         continue;
14105       dbgs() << "Use of operand  " << *Op << " by user " << S
14106              << " is not being tracked!\n";
14107       std::abort();
14108     }
14109   }
14110 
14111   // Verify integrity of ValuesAtScopes users.
14112   for (const auto &ValueAndVec : ValuesAtScopes) {
14113     const SCEV *Value = ValueAndVec.first;
14114     for (const auto &LoopAndValueAtScope : ValueAndVec.second) {
14115       const Loop *L = LoopAndValueAtScope.first;
14116       const SCEV *ValueAtScope = LoopAndValueAtScope.second;
14117       if (!isa<SCEVConstant>(ValueAtScope)) {
14118         auto It = ValuesAtScopesUsers.find(ValueAtScope);
14119         if (It != ValuesAtScopesUsers.end() &&
14120             is_contained(It->second, std::make_pair(L, Value)))
14121           continue;
14122         dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: "
14123                << *ValueAtScope << " missing in ValuesAtScopesUsers\n";
14124         std::abort();
14125       }
14126     }
14127   }
14128 
14129   for (const auto &ValueAtScopeAndVec : ValuesAtScopesUsers) {
14130     const SCEV *ValueAtScope = ValueAtScopeAndVec.first;
14131     for (const auto &LoopAndValue : ValueAtScopeAndVec.second) {
14132       const Loop *L = LoopAndValue.first;
14133       const SCEV *Value = LoopAndValue.second;
14134       assert(!isa<SCEVConstant>(Value));
14135       auto It = ValuesAtScopes.find(Value);
14136       if (It != ValuesAtScopes.end() &&
14137           is_contained(It->second, std::make_pair(L, ValueAtScope)))
14138         continue;
14139       dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: "
14140              << *ValueAtScope << " missing in ValuesAtScopes\n";
14141       std::abort();
14142     }
14143   }
14144 
14145   // Verify integrity of BECountUsers.
14146   auto VerifyBECountUsers = [&](bool Predicated) {
14147     auto &BECounts =
14148         Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts;
14149     for (const auto &LoopAndBEInfo : BECounts) {
14150       for (const ExitNotTakenInfo &ENT : LoopAndBEInfo.second.ExitNotTaken) {
14151         for (const SCEV *S : {ENT.ExactNotTaken, ENT.SymbolicMaxNotTaken}) {
14152           if (!isa<SCEVConstant>(S)) {
14153             auto UserIt = BECountUsers.find(S);
14154             if (UserIt != BECountUsers.end() &&
14155                 UserIt->second.contains({ LoopAndBEInfo.first, Predicated }))
14156               continue;
14157             dbgs() << "Value " << *S << " for loop " << *LoopAndBEInfo.first
14158                    << " missing from BECountUsers\n";
14159             std::abort();
14160           }
14161         }
14162       }
14163     }
14164   };
14165   VerifyBECountUsers(/* Predicated */ false);
14166   VerifyBECountUsers(/* Predicated */ true);
14167 
14168   // Verify intergity of loop disposition cache.
14169   for (auto &[S, Values] : LoopDispositions) {
14170     for (auto [Loop, CachedDisposition] : Values) {
14171       const auto RecomputedDisposition = SE2.getLoopDisposition(S, Loop);
14172       if (CachedDisposition != RecomputedDisposition) {
14173         dbgs() << "Cached disposition of " << *S << " for loop " << *Loop
14174                << " is incorrect: cached " << CachedDisposition << ", actual "
14175                << RecomputedDisposition << "\n";
14176         std::abort();
14177       }
14178     }
14179   }
14180 
14181   // Verify integrity of the block disposition cache.
14182   for (auto &[S, Values] : BlockDispositions) {
14183     for (auto [BB, CachedDisposition] : Values) {
14184       const auto RecomputedDisposition = SE2.getBlockDisposition(S, BB);
14185       if (CachedDisposition != RecomputedDisposition) {
14186         dbgs() << "Cached disposition of " << *S << " for block %"
14187                << BB->getName() << " is incorrect: cached " << CachedDisposition
14188                << ", actual " << RecomputedDisposition << "\n";
14189         std::abort();
14190       }
14191     }
14192   }
14193 
14194   // Verify FoldCache/FoldCacheUser caches.
14195   for (auto [FoldID, Expr] : FoldCache) {
14196     auto I = FoldCacheUser.find(Expr);
14197     if (I == FoldCacheUser.end()) {
14198       dbgs() << "Missing entry in FoldCacheUser for cached expression " << *Expr
14199              << "!\n";
14200       std::abort();
14201     }
14202     if (!is_contained(I->second, FoldID)) {
14203       dbgs() << "Missing FoldID in cached users of " << *Expr << "!\n";
14204       std::abort();
14205     }
14206   }
14207   for (auto [Expr, IDs] : FoldCacheUser) {
14208     for (auto &FoldID : IDs) {
14209       auto I = FoldCache.find(FoldID);
14210       if (I == FoldCache.end()) {
14211         dbgs() << "Missing entry in FoldCache for expression " << *Expr
14212                << "!\n";
14213         std::abort();
14214       }
14215       if (I->second != Expr) {
14216         dbgs() << "Entry in FoldCache doesn't match FoldCacheUser: "
14217                << *I->second << " != " << *Expr << "!\n";
14218         std::abort();
14219       }
14220     }
14221   }
14222 
14223   // Verify that ConstantMultipleCache computations are correct. We check that
14224   // cached multiples and recomputed multiples are multiples of each other to
14225   // verify correctness. It is possible that a recomputed multiple is different
14226   // from the cached multiple due to strengthened no wrap flags or changes in
14227   // KnownBits computations.
14228   for (auto [S, Multiple] : ConstantMultipleCache) {
14229     APInt RecomputedMultiple = SE2.getConstantMultiple(S);
14230     if ((Multiple != 0 && RecomputedMultiple != 0 &&
14231          Multiple.urem(RecomputedMultiple) != 0 &&
14232          RecomputedMultiple.urem(Multiple) != 0)) {
14233       dbgs() << "Incorrect cached computation in ConstantMultipleCache for "
14234              << *S << " : Computed " << RecomputedMultiple
14235              << " but cache contains " << Multiple << "!\n";
14236       std::abort();
14237     }
14238   }
14239 }
14240 
14241 bool ScalarEvolution::invalidate(
14242     Function &F, const PreservedAnalyses &PA,
14243     FunctionAnalysisManager::Invalidator &Inv) {
14244   // Invalidate the ScalarEvolution object whenever it isn't preserved or one
14245   // of its dependencies is invalidated.
14246   auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
14247   return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
14248          Inv.invalidate<AssumptionAnalysis>(F, PA) ||
14249          Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
14250          Inv.invalidate<LoopAnalysis>(F, PA);
14251 }
14252 
14253 AnalysisKey ScalarEvolutionAnalysis::Key;
14254 
14255 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
14256                                              FunctionAnalysisManager &AM) {
14257   auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
14258   auto &AC = AM.getResult<AssumptionAnalysis>(F);
14259   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
14260   auto &LI = AM.getResult<LoopAnalysis>(F);
14261   return ScalarEvolution(F, TLI, AC, DT, LI);
14262 }
14263 
14264 PreservedAnalyses
14265 ScalarEvolutionVerifierPass::run(Function &F, FunctionAnalysisManager &AM) {
14266   AM.getResult<ScalarEvolutionAnalysis>(F).verify();
14267   return PreservedAnalyses::all();
14268 }
14269 
14270 PreservedAnalyses
14271 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
14272   // For compatibility with opt's -analyze feature under legacy pass manager
14273   // which was not ported to NPM. This keeps tests using
14274   // update_analyze_test_checks.py working.
14275   OS << "Printing analysis 'Scalar Evolution Analysis' for function '"
14276      << F.getName() << "':\n";
14277   AM.getResult<ScalarEvolutionAnalysis>(F).print(OS);
14278   return PreservedAnalyses::all();
14279 }
14280 
14281 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
14282                       "Scalar Evolution Analysis", false, true)
14283 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
14284 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
14285 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
14286 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
14287 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
14288                     "Scalar Evolution Analysis", false, true)
14289 
14290 char ScalarEvolutionWrapperPass::ID = 0;
14291 
14292 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
14293   initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
14294 }
14295 
14296 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
14297   SE.reset(new ScalarEvolution(
14298       F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F),
14299       getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
14300       getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
14301       getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
14302   return false;
14303 }
14304 
14305 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
14306 
14307 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
14308   SE->print(OS);
14309 }
14310 
14311 void ScalarEvolutionWrapperPass::verifyAnalysis() const {
14312   if (!VerifySCEV)
14313     return;
14314 
14315   SE->verify();
14316 }
14317 
14318 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
14319   AU.setPreservesAll();
14320   AU.addRequiredTransitive<AssumptionCacheTracker>();
14321   AU.addRequiredTransitive<LoopInfoWrapperPass>();
14322   AU.addRequiredTransitive<DominatorTreeWrapperPass>();
14323   AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
14324 }
14325 
14326 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS,
14327                                                         const SCEV *RHS) {
14328   return getComparePredicate(ICmpInst::ICMP_EQ, LHS, RHS);
14329 }
14330 
14331 const SCEVPredicate *
14332 ScalarEvolution::getComparePredicate(const ICmpInst::Predicate Pred,
14333                                      const SCEV *LHS, const SCEV *RHS) {
14334   FoldingSetNodeID ID;
14335   assert(LHS->getType() == RHS->getType() &&
14336          "Type mismatch between LHS and RHS");
14337   // Unique this node based on the arguments
14338   ID.AddInteger(SCEVPredicate::P_Compare);
14339   ID.AddInteger(Pred);
14340   ID.AddPointer(LHS);
14341   ID.AddPointer(RHS);
14342   void *IP = nullptr;
14343   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
14344     return S;
14345   SCEVComparePredicate *Eq = new (SCEVAllocator)
14346     SCEVComparePredicate(ID.Intern(SCEVAllocator), Pred, LHS, RHS);
14347   UniquePreds.InsertNode(Eq, IP);
14348   return Eq;
14349 }
14350 
14351 const SCEVPredicate *ScalarEvolution::getWrapPredicate(
14352     const SCEVAddRecExpr *AR,
14353     SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
14354   FoldingSetNodeID ID;
14355   // Unique this node based on the arguments
14356   ID.AddInteger(SCEVPredicate::P_Wrap);
14357   ID.AddPointer(AR);
14358   ID.AddInteger(AddedFlags);
14359   void *IP = nullptr;
14360   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
14361     return S;
14362   auto *OF = new (SCEVAllocator)
14363       SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
14364   UniquePreds.InsertNode(OF, IP);
14365   return OF;
14366 }
14367 
14368 namespace {
14369 
14370 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
14371 public:
14372 
14373   /// Rewrites \p S in the context of a loop L and the SCEV predication
14374   /// infrastructure.
14375   ///
14376   /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
14377   /// equivalences present in \p Pred.
14378   ///
14379   /// If \p NewPreds is non-null, rewrite is free to add further predicates to
14380   /// \p NewPreds such that the result will be an AddRecExpr.
14381   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
14382                              SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
14383                              const SCEVPredicate *Pred) {
14384     SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
14385     return Rewriter.visit(S);
14386   }
14387 
14388   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
14389     if (Pred) {
14390       if (auto *U = dyn_cast<SCEVUnionPredicate>(Pred)) {
14391         for (const auto *Pred : U->getPredicates())
14392           if (const auto *IPred = dyn_cast<SCEVComparePredicate>(Pred))
14393             if (IPred->getLHS() == Expr &&
14394                 IPred->getPredicate() == ICmpInst::ICMP_EQ)
14395               return IPred->getRHS();
14396       } else if (const auto *IPred = dyn_cast<SCEVComparePredicate>(Pred)) {
14397         if (IPred->getLHS() == Expr &&
14398             IPred->getPredicate() == ICmpInst::ICMP_EQ)
14399           return IPred->getRHS();
14400       }
14401     }
14402     return convertToAddRecWithPreds(Expr);
14403   }
14404 
14405   const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
14406     const SCEV *Operand = visit(Expr->getOperand());
14407     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
14408     if (AR && AR->getLoop() == L && AR->isAffine()) {
14409       // This couldn't be folded because the operand didn't have the nuw
14410       // flag. Add the nusw flag as an assumption that we could make.
14411       const SCEV *Step = AR->getStepRecurrence(SE);
14412       Type *Ty = Expr->getType();
14413       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
14414         return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
14415                                 SE.getSignExtendExpr(Step, Ty), L,
14416                                 AR->getNoWrapFlags());
14417     }
14418     return SE.getZeroExtendExpr(Operand, Expr->getType());
14419   }
14420 
14421   const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
14422     const SCEV *Operand = visit(Expr->getOperand());
14423     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
14424     if (AR && AR->getLoop() == L && AR->isAffine()) {
14425       // This couldn't be folded because the operand didn't have the nsw
14426       // flag. Add the nssw flag as an assumption that we could make.
14427       const SCEV *Step = AR->getStepRecurrence(SE);
14428       Type *Ty = Expr->getType();
14429       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
14430         return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
14431                                 SE.getSignExtendExpr(Step, Ty), L,
14432                                 AR->getNoWrapFlags());
14433     }
14434     return SE.getSignExtendExpr(Operand, Expr->getType());
14435   }
14436 
14437 private:
14438   explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE,
14439                         SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
14440                         const SCEVPredicate *Pred)
14441       : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
14442 
14443   bool addOverflowAssumption(const SCEVPredicate *P) {
14444     if (!NewPreds) {
14445       // Check if we've already made this assumption.
14446       return Pred && Pred->implies(P);
14447     }
14448     NewPreds->insert(P);
14449     return true;
14450   }
14451 
14452   bool addOverflowAssumption(const SCEVAddRecExpr *AR,
14453                              SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
14454     auto *A = SE.getWrapPredicate(AR, AddedFlags);
14455     return addOverflowAssumption(A);
14456   }
14457 
14458   // If \p Expr represents a PHINode, we try to see if it can be represented
14459   // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible
14460   // to add this predicate as a runtime overflow check, we return the AddRec.
14461   // If \p Expr does not meet these conditions (is not a PHI node, or we
14462   // couldn't create an AddRec for it, or couldn't add the predicate), we just
14463   // return \p Expr.
14464   const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) {
14465     if (!isa<PHINode>(Expr->getValue()))
14466       return Expr;
14467     std::optional<
14468         std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
14469         PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr);
14470     if (!PredicatedRewrite)
14471       return Expr;
14472     for (const auto *P : PredicatedRewrite->second){
14473       // Wrap predicates from outer loops are not supported.
14474       if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) {
14475         if (L != WP->getExpr()->getLoop())
14476           return Expr;
14477       }
14478       if (!addOverflowAssumption(P))
14479         return Expr;
14480     }
14481     return PredicatedRewrite->first;
14482   }
14483 
14484   SmallPtrSetImpl<const SCEVPredicate *> *NewPreds;
14485   const SCEVPredicate *Pred;
14486   const Loop *L;
14487 };
14488 
14489 } // end anonymous namespace
14490 
14491 const SCEV *
14492 ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
14493                                        const SCEVPredicate &Preds) {
14494   return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
14495 }
14496 
14497 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates(
14498     const SCEV *S, const Loop *L,
14499     SmallPtrSetImpl<const SCEVPredicate *> &Preds) {
14500   SmallPtrSet<const SCEVPredicate *, 4> TransformPreds;
14501   S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
14502   auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
14503 
14504   if (!AddRec)
14505     return nullptr;
14506 
14507   // Since the transformation was successful, we can now transfer the SCEV
14508   // predicates.
14509   for (const auto *P : TransformPreds)
14510     Preds.insert(P);
14511 
14512   return AddRec;
14513 }
14514 
14515 /// SCEV predicates
14516 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
14517                              SCEVPredicateKind Kind)
14518     : FastID(ID), Kind(Kind) {}
14519 
14520 SCEVComparePredicate::SCEVComparePredicate(const FoldingSetNodeIDRef ID,
14521                                    const ICmpInst::Predicate Pred,
14522                                    const SCEV *LHS, const SCEV *RHS)
14523   : SCEVPredicate(ID, P_Compare), Pred(Pred), LHS(LHS), RHS(RHS) {
14524   assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match");
14525   assert(LHS != RHS && "LHS and RHS are the same SCEV");
14526 }
14527 
14528 bool SCEVComparePredicate::implies(const SCEVPredicate *N) const {
14529   const auto *Op = dyn_cast<SCEVComparePredicate>(N);
14530 
14531   if (!Op)
14532     return false;
14533 
14534   if (Pred != ICmpInst::ICMP_EQ)
14535     return false;
14536 
14537   return Op->LHS == LHS && Op->RHS == RHS;
14538 }
14539 
14540 bool SCEVComparePredicate::isAlwaysTrue() const { return false; }
14541 
14542 void SCEVComparePredicate::print(raw_ostream &OS, unsigned Depth) const {
14543   if (Pred == ICmpInst::ICMP_EQ)
14544     OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
14545   else
14546     OS.indent(Depth) << "Compare predicate: " << *LHS << " " << Pred << ") "
14547                      << *RHS << "\n";
14548 
14549 }
14550 
14551 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
14552                                      const SCEVAddRecExpr *AR,
14553                                      IncrementWrapFlags Flags)
14554     : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
14555 
14556 const SCEVAddRecExpr *SCEVWrapPredicate::getExpr() const { return AR; }
14557 
14558 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const {
14559   const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
14560 
14561   return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags;
14562 }
14563 
14564 bool SCEVWrapPredicate::isAlwaysTrue() const {
14565   SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
14566   IncrementWrapFlags IFlags = Flags;
14567 
14568   if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
14569     IFlags = clearFlags(IFlags, IncrementNSSW);
14570 
14571   return IFlags == IncrementAnyWrap;
14572 }
14573 
14574 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
14575   OS.indent(Depth) << *getExpr() << " Added Flags: ";
14576   if (SCEVWrapPredicate::IncrementNUSW & getFlags())
14577     OS << "<nusw>";
14578   if (SCEVWrapPredicate::IncrementNSSW & getFlags())
14579     OS << "<nssw>";
14580   OS << "\n";
14581 }
14582 
14583 SCEVWrapPredicate::IncrementWrapFlags
14584 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR,
14585                                    ScalarEvolution &SE) {
14586   IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
14587   SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
14588 
14589   // We can safely transfer the NSW flag as NSSW.
14590   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
14591     ImpliedFlags = IncrementNSSW;
14592 
14593   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
14594     // If the increment is positive, the SCEV NUW flag will also imply the
14595     // WrapPredicate NUSW flag.
14596     if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
14597       if (Step->getValue()->getValue().isNonNegative())
14598         ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
14599   }
14600 
14601   return ImpliedFlags;
14602 }
14603 
14604 /// Union predicates don't get cached so create a dummy set ID for it.
14605 SCEVUnionPredicate::SCEVUnionPredicate(ArrayRef<const SCEVPredicate *> Preds)
14606   : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {
14607   for (const auto *P : Preds)
14608     add(P);
14609 }
14610 
14611 bool SCEVUnionPredicate::isAlwaysTrue() const {
14612   return all_of(Preds,
14613                 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
14614 }
14615 
14616 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
14617   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
14618     return all_of(Set->Preds,
14619                   [this](const SCEVPredicate *I) { return this->implies(I); });
14620 
14621   return any_of(Preds,
14622                 [N](const SCEVPredicate *I) { return I->implies(N); });
14623 }
14624 
14625 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
14626   for (const auto *Pred : Preds)
14627     Pred->print(OS, Depth);
14628 }
14629 
14630 void SCEVUnionPredicate::add(const SCEVPredicate *N) {
14631   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
14632     for (const auto *Pred : Set->Preds)
14633       add(Pred);
14634     return;
14635   }
14636 
14637   Preds.push_back(N);
14638 }
14639 
14640 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
14641                                                      Loop &L)
14642     : SE(SE), L(L) {
14643   SmallVector<const SCEVPredicate*, 4> Empty;
14644   Preds = std::make_unique<SCEVUnionPredicate>(Empty);
14645 }
14646 
14647 void ScalarEvolution::registerUser(const SCEV *User,
14648                                    ArrayRef<const SCEV *> Ops) {
14649   for (const auto *Op : Ops)
14650     // We do not expect that forgetting cached data for SCEVConstants will ever
14651     // open any prospects for sharpening or introduce any correctness issues,
14652     // so we don't bother storing their dependencies.
14653     if (!isa<SCEVConstant>(Op))
14654       SCEVUsers[Op].insert(User);
14655 }
14656 
14657 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
14658   const SCEV *Expr = SE.getSCEV(V);
14659   RewriteEntry &Entry = RewriteMap[Expr];
14660 
14661   // If we already have an entry and the version matches, return it.
14662   if (Entry.second && Generation == Entry.first)
14663     return Entry.second;
14664 
14665   // We found an entry but it's stale. Rewrite the stale entry
14666   // according to the current predicate.
14667   if (Entry.second)
14668     Expr = Entry.second;
14669 
14670   const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, *Preds);
14671   Entry = {Generation, NewSCEV};
14672 
14673   return NewSCEV;
14674 }
14675 
14676 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() {
14677   if (!BackedgeCount) {
14678     SmallVector<const SCEVPredicate *, 4> Preds;
14679     BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, Preds);
14680     for (const auto *P : Preds)
14681       addPredicate(*P);
14682   }
14683   return BackedgeCount;
14684 }
14685 
14686 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
14687   if (Preds->implies(&Pred))
14688     return;
14689 
14690   auto &OldPreds = Preds->getPredicates();
14691   SmallVector<const SCEVPredicate*, 4> NewPreds(OldPreds.begin(), OldPreds.end());
14692   NewPreds.push_back(&Pred);
14693   Preds = std::make_unique<SCEVUnionPredicate>(NewPreds);
14694   updateGeneration();
14695 }
14696 
14697 const SCEVPredicate &PredicatedScalarEvolution::getPredicate() const {
14698   return *Preds;
14699 }
14700 
14701 void PredicatedScalarEvolution::updateGeneration() {
14702   // If the generation number wrapped recompute everything.
14703   if (++Generation == 0) {
14704     for (auto &II : RewriteMap) {
14705       const SCEV *Rewritten = II.second.second;
14706       II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, *Preds)};
14707     }
14708   }
14709 }
14710 
14711 void PredicatedScalarEvolution::setNoOverflow(
14712     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
14713   const SCEV *Expr = getSCEV(V);
14714   const auto *AR = cast<SCEVAddRecExpr>(Expr);
14715 
14716   auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE);
14717 
14718   // Clear the statically implied flags.
14719   Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags);
14720   addPredicate(*SE.getWrapPredicate(AR, Flags));
14721 
14722   auto II = FlagsMap.insert({V, Flags});
14723   if (!II.second)
14724     II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second);
14725 }
14726 
14727 bool PredicatedScalarEvolution::hasNoOverflow(
14728     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
14729   const SCEV *Expr = getSCEV(V);
14730   const auto *AR = cast<SCEVAddRecExpr>(Expr);
14731 
14732   Flags = SCEVWrapPredicate::clearFlags(
14733       Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
14734 
14735   auto II = FlagsMap.find(V);
14736 
14737   if (II != FlagsMap.end())
14738     Flags = SCEVWrapPredicate::clearFlags(Flags, II->second);
14739 
14740   return Flags == SCEVWrapPredicate::IncrementAnyWrap;
14741 }
14742 
14743 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) {
14744   const SCEV *Expr = this->getSCEV(V);
14745   SmallPtrSet<const SCEVPredicate *, 4> NewPreds;
14746   auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
14747 
14748   if (!New)
14749     return nullptr;
14750 
14751   for (const auto *P : NewPreds)
14752     addPredicate(*P);
14753 
14754   RewriteMap[SE.getSCEV(V)] = {Generation, New};
14755   return New;
14756 }
14757 
14758 PredicatedScalarEvolution::PredicatedScalarEvolution(
14759     const PredicatedScalarEvolution &Init)
14760   : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L),
14761     Preds(std::make_unique<SCEVUnionPredicate>(Init.Preds->getPredicates())),
14762     Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
14763   for (auto I : Init.FlagsMap)
14764     FlagsMap.insert(I);
14765 }
14766 
14767 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const {
14768   // For each block.
14769   for (auto *BB : L.getBlocks())
14770     for (auto &I : *BB) {
14771       if (!SE.isSCEVable(I.getType()))
14772         continue;
14773 
14774       auto *Expr = SE.getSCEV(&I);
14775       auto II = RewriteMap.find(Expr);
14776 
14777       if (II == RewriteMap.end())
14778         continue;
14779 
14780       // Don't print things that are not interesting.
14781       if (II->second.second == Expr)
14782         continue;
14783 
14784       OS.indent(Depth) << "[PSE]" << I << ":\n";
14785       OS.indent(Depth + 2) << *Expr << "\n";
14786       OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
14787     }
14788 }
14789 
14790 // Match the mathematical pattern A - (A / B) * B, where A and B can be
14791 // arbitrary expressions. Also match zext (trunc A to iB) to iY, which is used
14792 // for URem with constant power-of-2 second operands.
14793 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is
14794 // 4, A / B becomes X / 8).
14795 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS,
14796                                 const SCEV *&RHS) {
14797   // Try to match 'zext (trunc A to iB) to iY', which is used
14798   // for URem with constant power-of-2 second operands. Make sure the size of
14799   // the operand A matches the size of the whole expressions.
14800   if (const auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(Expr))
14801     if (const auto *Trunc = dyn_cast<SCEVTruncateExpr>(ZExt->getOperand(0))) {
14802       LHS = Trunc->getOperand();
14803       // Bail out if the type of the LHS is larger than the type of the
14804       // expression for now.
14805       if (getTypeSizeInBits(LHS->getType()) >
14806           getTypeSizeInBits(Expr->getType()))
14807         return false;
14808       if (LHS->getType() != Expr->getType())
14809         LHS = getZeroExtendExpr(LHS, Expr->getType());
14810       RHS = getConstant(APInt(getTypeSizeInBits(Expr->getType()), 1)
14811                         << getTypeSizeInBits(Trunc->getType()));
14812       return true;
14813     }
14814   const auto *Add = dyn_cast<SCEVAddExpr>(Expr);
14815   if (Add == nullptr || Add->getNumOperands() != 2)
14816     return false;
14817 
14818   const SCEV *A = Add->getOperand(1);
14819   const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0));
14820 
14821   if (Mul == nullptr)
14822     return false;
14823 
14824   const auto MatchURemWithDivisor = [&](const SCEV *B) {
14825     // (SomeExpr + (-(SomeExpr / B) * B)).
14826     if (Expr == getURemExpr(A, B)) {
14827       LHS = A;
14828       RHS = B;
14829       return true;
14830     }
14831     return false;
14832   };
14833 
14834   // (SomeExpr + (-1 * (SomeExpr / B) * B)).
14835   if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0)))
14836     return MatchURemWithDivisor(Mul->getOperand(1)) ||
14837            MatchURemWithDivisor(Mul->getOperand(2));
14838 
14839   // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)).
14840   if (Mul->getNumOperands() == 2)
14841     return MatchURemWithDivisor(Mul->getOperand(1)) ||
14842            MatchURemWithDivisor(Mul->getOperand(0)) ||
14843            MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) ||
14844            MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0)));
14845   return false;
14846 }
14847 
14848 const SCEV *
14849 ScalarEvolution::computeSymbolicMaxBackedgeTakenCount(const Loop *L) {
14850   SmallVector<BasicBlock*, 16> ExitingBlocks;
14851   L->getExitingBlocks(ExitingBlocks);
14852 
14853   // Form an expression for the maximum exit count possible for this loop. We
14854   // merge the max and exact information to approximate a version of
14855   // getConstantMaxBackedgeTakenCount which isn't restricted to just constants.
14856   SmallVector<const SCEV*, 4> ExitCounts;
14857   for (BasicBlock *ExitingBB : ExitingBlocks) {
14858     const SCEV *ExitCount =
14859         getExitCount(L, ExitingBB, ScalarEvolution::SymbolicMaximum);
14860     if (!isa<SCEVCouldNotCompute>(ExitCount)) {
14861       assert(DT.dominates(ExitingBB, L->getLoopLatch()) &&
14862              "We should only have known counts for exiting blocks that "
14863              "dominate latch!");
14864       ExitCounts.push_back(ExitCount);
14865     }
14866   }
14867   if (ExitCounts.empty())
14868     return getCouldNotCompute();
14869   return getUMinFromMismatchedTypes(ExitCounts, /*Sequential*/ true);
14870 }
14871 
14872 /// A rewriter to replace SCEV expressions in Map with the corresponding entry
14873 /// in the map. It skips AddRecExpr because we cannot guarantee that the
14874 /// replacement is loop invariant in the loop of the AddRec.
14875 class SCEVLoopGuardRewriter : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> {
14876   const DenseMap<const SCEV *, const SCEV *> &Map;
14877 
14878 public:
14879   SCEVLoopGuardRewriter(ScalarEvolution &SE,
14880                         DenseMap<const SCEV *, const SCEV *> &M)
14881       : SCEVRewriteVisitor(SE), Map(M) {}
14882 
14883   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; }
14884 
14885   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
14886     auto I = Map.find(Expr);
14887     if (I == Map.end())
14888       return Expr;
14889     return I->second;
14890   }
14891 
14892   const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
14893     auto I = Map.find(Expr);
14894     if (I == Map.end()) {
14895       // If we didn't find the extact ZExt expr in the map, check if there's an
14896       // entry for a smaller ZExt we can use instead.
14897       Type *Ty = Expr->getType();
14898       const SCEV *Op = Expr->getOperand(0);
14899       unsigned Bitwidth = Ty->getScalarSizeInBits() / 2;
14900       while (Bitwidth % 8 == 0 && Bitwidth >= 8 &&
14901              Bitwidth > Op->getType()->getScalarSizeInBits()) {
14902         Type *NarrowTy = IntegerType::get(SE.getContext(), Bitwidth);
14903         auto *NarrowExt = SE.getZeroExtendExpr(Op, NarrowTy);
14904         auto I = Map.find(NarrowExt);
14905         if (I != Map.end())
14906           return SE.getZeroExtendExpr(I->second, Ty);
14907         Bitwidth = Bitwidth / 2;
14908       }
14909 
14910       return SCEVRewriteVisitor<SCEVLoopGuardRewriter>::visitZeroExtendExpr(
14911           Expr);
14912     }
14913     return I->second;
14914   }
14915 
14916   const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
14917     auto I = Map.find(Expr);
14918     if (I == Map.end())
14919       return SCEVRewriteVisitor<SCEVLoopGuardRewriter>::visitSignExtendExpr(
14920           Expr);
14921     return I->second;
14922   }
14923 
14924   const SCEV *visitUMinExpr(const SCEVUMinExpr *Expr) {
14925     auto I = Map.find(Expr);
14926     if (I == Map.end())
14927       return SCEVRewriteVisitor<SCEVLoopGuardRewriter>::visitUMinExpr(Expr);
14928     return I->second;
14929   }
14930 
14931   const SCEV *visitSMinExpr(const SCEVSMinExpr *Expr) {
14932     auto I = Map.find(Expr);
14933     if (I == Map.end())
14934       return SCEVRewriteVisitor<SCEVLoopGuardRewriter>::visitSMinExpr(Expr);
14935     return I->second;
14936   }
14937 };
14938 
14939 const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) {
14940   SmallVector<const SCEV *> ExprsToRewrite;
14941   auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS,
14942                               const SCEV *RHS,
14943                               DenseMap<const SCEV *, const SCEV *>
14944                                   &RewriteMap) {
14945     // WARNING: It is generally unsound to apply any wrap flags to the proposed
14946     // replacement SCEV which isn't directly implied by the structure of that
14947     // SCEV.  In particular, using contextual facts to imply flags is *NOT*
14948     // legal.  See the scoping rules for flags in the header to understand why.
14949 
14950     // If LHS is a constant, apply information to the other expression.
14951     if (isa<SCEVConstant>(LHS)) {
14952       std::swap(LHS, RHS);
14953       Predicate = CmpInst::getSwappedPredicate(Predicate);
14954     }
14955 
14956     // Check for a condition of the form (-C1 + X < C2).  InstCombine will
14957     // create this form when combining two checks of the form (X u< C2 + C1) and
14958     // (X >=u C1).
14959     auto MatchRangeCheckIdiom = [this, Predicate, LHS, RHS, &RewriteMap,
14960                                  &ExprsToRewrite]() {
14961       auto *AddExpr = dyn_cast<SCEVAddExpr>(LHS);
14962       if (!AddExpr || AddExpr->getNumOperands() != 2)
14963         return false;
14964 
14965       auto *C1 = dyn_cast<SCEVConstant>(AddExpr->getOperand(0));
14966       auto *LHSUnknown = dyn_cast<SCEVUnknown>(AddExpr->getOperand(1));
14967       auto *C2 = dyn_cast<SCEVConstant>(RHS);
14968       if (!C1 || !C2 || !LHSUnknown)
14969         return false;
14970 
14971       auto ExactRegion =
14972           ConstantRange::makeExactICmpRegion(Predicate, C2->getAPInt())
14973               .sub(C1->getAPInt());
14974 
14975       // Bail out, unless we have a non-wrapping, monotonic range.
14976       if (ExactRegion.isWrappedSet() || ExactRegion.isFullSet())
14977         return false;
14978       auto I = RewriteMap.find(LHSUnknown);
14979       const SCEV *RewrittenLHS = I != RewriteMap.end() ? I->second : LHSUnknown;
14980       RewriteMap[LHSUnknown] = getUMaxExpr(
14981           getConstant(ExactRegion.getUnsignedMin()),
14982           getUMinExpr(RewrittenLHS, getConstant(ExactRegion.getUnsignedMax())));
14983       ExprsToRewrite.push_back(LHSUnknown);
14984       return true;
14985     };
14986     if (MatchRangeCheckIdiom())
14987       return;
14988 
14989     // Return true if \p Expr is a MinMax SCEV expression with a non-negative
14990     // constant operand. If so, return in \p SCTy the SCEV type and in \p RHS
14991     // the non-constant operand and in \p LHS the constant operand.
14992     auto IsMinMaxSCEVWithNonNegativeConstant =
14993         [&](const SCEV *Expr, SCEVTypes &SCTy, const SCEV *&LHS,
14994             const SCEV *&RHS) {
14995           if (auto *MinMax = dyn_cast<SCEVMinMaxExpr>(Expr)) {
14996             if (MinMax->getNumOperands() != 2)
14997               return false;
14998             if (auto *C = dyn_cast<SCEVConstant>(MinMax->getOperand(0))) {
14999               if (C->getAPInt().isNegative())
15000                 return false;
15001               SCTy = MinMax->getSCEVType();
15002               LHS = MinMax->getOperand(0);
15003               RHS = MinMax->getOperand(1);
15004               return true;
15005             }
15006           }
15007           return false;
15008         };
15009 
15010     // Checks whether Expr is a non-negative constant, and Divisor is a positive
15011     // constant, and returns their APInt in ExprVal and in DivisorVal.
15012     auto GetNonNegExprAndPosDivisor = [&](const SCEV *Expr, const SCEV *Divisor,
15013                                           APInt &ExprVal, APInt &DivisorVal) {
15014       auto *ConstExpr = dyn_cast<SCEVConstant>(Expr);
15015       auto *ConstDivisor = dyn_cast<SCEVConstant>(Divisor);
15016       if (!ConstExpr || !ConstDivisor)
15017         return false;
15018       ExprVal = ConstExpr->getAPInt();
15019       DivisorVal = ConstDivisor->getAPInt();
15020       return ExprVal.isNonNegative() && !DivisorVal.isNonPositive();
15021     };
15022 
15023     // Return a new SCEV that modifies \p Expr to the closest number divides by
15024     // \p Divisor and greater or equal than Expr.
15025     // For now, only handle constant Expr and Divisor.
15026     auto GetNextSCEVDividesByDivisor = [&](const SCEV *Expr,
15027                                            const SCEV *Divisor) {
15028       APInt ExprVal;
15029       APInt DivisorVal;
15030       if (!GetNonNegExprAndPosDivisor(Expr, Divisor, ExprVal, DivisorVal))
15031         return Expr;
15032       APInt Rem = ExprVal.urem(DivisorVal);
15033       if (!Rem.isZero())
15034         // return the SCEV: Expr + Divisor - Expr % Divisor
15035         return getConstant(ExprVal + DivisorVal - Rem);
15036       return Expr;
15037     };
15038 
15039     // Return a new SCEV that modifies \p Expr to the closest number divides by
15040     // \p Divisor and less or equal than Expr.
15041     // For now, only handle constant Expr and Divisor.
15042     auto GetPreviousSCEVDividesByDivisor = [&](const SCEV *Expr,
15043                                                const SCEV *Divisor) {
15044       APInt ExprVal;
15045       APInt DivisorVal;
15046       if (!GetNonNegExprAndPosDivisor(Expr, Divisor, ExprVal, DivisorVal))
15047         return Expr;
15048       APInt Rem = ExprVal.urem(DivisorVal);
15049       // return the SCEV: Expr - Expr % Divisor
15050       return getConstant(ExprVal - Rem);
15051     };
15052 
15053     // Apply divisibilty by \p Divisor on MinMaxExpr with constant values,
15054     // recursively. This is done by aligning up/down the constant value to the
15055     // Divisor.
15056     std::function<const SCEV *(const SCEV *, const SCEV *)>
15057         ApplyDivisibiltyOnMinMaxExpr = [&](const SCEV *MinMaxExpr,
15058                                            const SCEV *Divisor) {
15059           const SCEV *MinMaxLHS = nullptr, *MinMaxRHS = nullptr;
15060           SCEVTypes SCTy;
15061           if (!IsMinMaxSCEVWithNonNegativeConstant(MinMaxExpr, SCTy, MinMaxLHS,
15062                                                    MinMaxRHS))
15063             return MinMaxExpr;
15064           auto IsMin =
15065               isa<SCEVSMinExpr>(MinMaxExpr) || isa<SCEVUMinExpr>(MinMaxExpr);
15066           assert(isKnownNonNegative(MinMaxLHS) &&
15067                  "Expected non-negative operand!");
15068           auto *DivisibleExpr =
15069               IsMin ? GetPreviousSCEVDividesByDivisor(MinMaxLHS, Divisor)
15070                     : GetNextSCEVDividesByDivisor(MinMaxLHS, Divisor);
15071           SmallVector<const SCEV *> Ops = {
15072               ApplyDivisibiltyOnMinMaxExpr(MinMaxRHS, Divisor), DivisibleExpr};
15073           return getMinMaxExpr(SCTy, Ops);
15074         };
15075 
15076     // If we have LHS == 0, check if LHS is computing a property of some unknown
15077     // SCEV %v which we can rewrite %v to express explicitly.
15078     const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS);
15079     if (Predicate == CmpInst::ICMP_EQ && RHSC &&
15080         RHSC->getValue()->isNullValue()) {
15081       // If LHS is A % B, i.e. A % B == 0, rewrite A to (A /u B) * B to
15082       // explicitly express that.
15083       const SCEV *URemLHS = nullptr;
15084       const SCEV *URemRHS = nullptr;
15085       if (matchURem(LHS, URemLHS, URemRHS)) {
15086         if (const SCEVUnknown *LHSUnknown = dyn_cast<SCEVUnknown>(URemLHS)) {
15087           auto I = RewriteMap.find(LHSUnknown);
15088           const SCEV *RewrittenLHS =
15089               I != RewriteMap.end() ? I->second : LHSUnknown;
15090           RewrittenLHS = ApplyDivisibiltyOnMinMaxExpr(RewrittenLHS, URemRHS);
15091           const auto *Multiple =
15092               getMulExpr(getUDivExpr(RewrittenLHS, URemRHS), URemRHS);
15093           RewriteMap[LHSUnknown] = Multiple;
15094           ExprsToRewrite.push_back(LHSUnknown);
15095           return;
15096         }
15097       }
15098     }
15099 
15100     // Do not apply information for constants or if RHS contains an AddRec.
15101     if (isa<SCEVConstant>(LHS) || containsAddRecurrence(RHS))
15102       return;
15103 
15104     // If RHS is SCEVUnknown, make sure the information is applied to it.
15105     if (!isa<SCEVUnknown>(LHS) && isa<SCEVUnknown>(RHS)) {
15106       std::swap(LHS, RHS);
15107       Predicate = CmpInst::getSwappedPredicate(Predicate);
15108     }
15109 
15110     // Puts rewrite rule \p From -> \p To into the rewrite map. Also if \p From
15111     // and \p FromRewritten are the same (i.e. there has been no rewrite
15112     // registered for \p From), then puts this value in the list of rewritten
15113     // expressions.
15114     auto AddRewrite = [&](const SCEV *From, const SCEV *FromRewritten,
15115                           const SCEV *To) {
15116       if (From == FromRewritten)
15117         ExprsToRewrite.push_back(From);
15118       RewriteMap[From] = To;
15119     };
15120 
15121     // Checks whether \p S has already been rewritten. In that case returns the
15122     // existing rewrite because we want to chain further rewrites onto the
15123     // already rewritten value. Otherwise returns \p S.
15124     auto GetMaybeRewritten = [&](const SCEV *S) {
15125       auto I = RewriteMap.find(S);
15126       return I != RewriteMap.end() ? I->second : S;
15127     };
15128 
15129     // Check for the SCEV expression (A /u B) * B while B is a constant, inside
15130     // \p Expr. The check is done recuresively on \p Expr, which is assumed to
15131     // be a composition of Min/Max SCEVs. Return whether the SCEV expression (A
15132     // /u B) * B was found, and return the divisor B in \p DividesBy. For
15133     // example, if Expr = umin (umax ((A /u 8) * 8, 16), 64), return true since
15134     // (A /u 8) * 8 matched the pattern, and return the constant SCEV 8 in \p
15135     // DividesBy.
15136     std::function<bool(const SCEV *, const SCEV *&)> HasDivisibiltyInfo =
15137         [&](const SCEV *Expr, const SCEV *&DividesBy) {
15138           if (auto *Mul = dyn_cast<SCEVMulExpr>(Expr)) {
15139             if (Mul->getNumOperands() != 2)
15140               return false;
15141             auto *MulLHS = Mul->getOperand(0);
15142             auto *MulRHS = Mul->getOperand(1);
15143             if (isa<SCEVConstant>(MulLHS))
15144               std::swap(MulLHS, MulRHS);
15145             if (auto *Div = dyn_cast<SCEVUDivExpr>(MulLHS))
15146               if (Div->getOperand(1) == MulRHS) {
15147                 DividesBy = MulRHS;
15148                 return true;
15149               }
15150           }
15151           if (auto *MinMax = dyn_cast<SCEVMinMaxExpr>(Expr))
15152             return HasDivisibiltyInfo(MinMax->getOperand(0), DividesBy) ||
15153                    HasDivisibiltyInfo(MinMax->getOperand(1), DividesBy);
15154           return false;
15155         };
15156 
15157     // Return true if Expr known to divide by \p DividesBy.
15158     std::function<bool(const SCEV *, const SCEV *&)> IsKnownToDivideBy =
15159         [&](const SCEV *Expr, const SCEV *DividesBy) {
15160           if (getURemExpr(Expr, DividesBy)->isZero())
15161             return true;
15162           if (auto *MinMax = dyn_cast<SCEVMinMaxExpr>(Expr))
15163             return IsKnownToDivideBy(MinMax->getOperand(0), DividesBy) &&
15164                    IsKnownToDivideBy(MinMax->getOperand(1), DividesBy);
15165           return false;
15166         };
15167 
15168     const SCEV *RewrittenLHS = GetMaybeRewritten(LHS);
15169     const SCEV *DividesBy = nullptr;
15170     if (HasDivisibiltyInfo(RewrittenLHS, DividesBy))
15171       // Check that the whole expression is divided by DividesBy
15172       DividesBy =
15173           IsKnownToDivideBy(RewrittenLHS, DividesBy) ? DividesBy : nullptr;
15174 
15175     // Collect rewrites for LHS and its transitive operands based on the
15176     // condition.
15177     // For min/max expressions, also apply the guard to its operands:
15178     //  'min(a, b) >= c'   ->   '(a >= c) and (b >= c)',
15179     //  'min(a, b) >  c'   ->   '(a >  c) and (b >  c)',
15180     //  'max(a, b) <= c'   ->   '(a <= c) and (b <= c)',
15181     //  'max(a, b) <  c'   ->   '(a <  c) and (b <  c)'.
15182 
15183     // We cannot express strict predicates in SCEV, so instead we replace them
15184     // with non-strict ones against plus or minus one of RHS depending on the
15185     // predicate.
15186     const SCEV *One = getOne(RHS->getType());
15187     switch (Predicate) {
15188       case CmpInst::ICMP_ULT:
15189         if (RHS->getType()->isPointerTy())
15190           return;
15191         RHS = getUMaxExpr(RHS, One);
15192         [[fallthrough]];
15193       case CmpInst::ICMP_SLT: {
15194         RHS = getMinusSCEV(RHS, One);
15195         RHS = DividesBy ? GetPreviousSCEVDividesByDivisor(RHS, DividesBy) : RHS;
15196         break;
15197       }
15198       case CmpInst::ICMP_UGT:
15199       case CmpInst::ICMP_SGT:
15200         RHS = getAddExpr(RHS, One);
15201         RHS = DividesBy ? GetNextSCEVDividesByDivisor(RHS, DividesBy) : RHS;
15202         break;
15203       case CmpInst::ICMP_ULE:
15204       case CmpInst::ICMP_SLE:
15205         RHS = DividesBy ? GetPreviousSCEVDividesByDivisor(RHS, DividesBy) : RHS;
15206         break;
15207       case CmpInst::ICMP_UGE:
15208       case CmpInst::ICMP_SGE:
15209         RHS = DividesBy ? GetNextSCEVDividesByDivisor(RHS, DividesBy) : RHS;
15210         break;
15211       default:
15212         break;
15213     }
15214 
15215     SmallVector<const SCEV *, 16> Worklist(1, LHS);
15216     SmallPtrSet<const SCEV *, 16> Visited;
15217 
15218     auto EnqueueOperands = [&Worklist](const SCEVNAryExpr *S) {
15219       append_range(Worklist, S->operands());
15220     };
15221 
15222     while (!Worklist.empty()) {
15223       const SCEV *From = Worklist.pop_back_val();
15224       if (isa<SCEVConstant>(From))
15225         continue;
15226       if (!Visited.insert(From).second)
15227         continue;
15228       const SCEV *FromRewritten = GetMaybeRewritten(From);
15229       const SCEV *To = nullptr;
15230 
15231       switch (Predicate) {
15232       case CmpInst::ICMP_ULT:
15233       case CmpInst::ICMP_ULE:
15234         To = getUMinExpr(FromRewritten, RHS);
15235         if (auto *UMax = dyn_cast<SCEVUMaxExpr>(FromRewritten))
15236           EnqueueOperands(UMax);
15237         break;
15238       case CmpInst::ICMP_SLT:
15239       case CmpInst::ICMP_SLE:
15240         To = getSMinExpr(FromRewritten, RHS);
15241         if (auto *SMax = dyn_cast<SCEVSMaxExpr>(FromRewritten))
15242           EnqueueOperands(SMax);
15243         break;
15244       case CmpInst::ICMP_UGT:
15245       case CmpInst::ICMP_UGE:
15246         To = getUMaxExpr(FromRewritten, RHS);
15247         if (auto *UMin = dyn_cast<SCEVUMinExpr>(FromRewritten))
15248           EnqueueOperands(UMin);
15249         break;
15250       case CmpInst::ICMP_SGT:
15251       case CmpInst::ICMP_SGE:
15252         To = getSMaxExpr(FromRewritten, RHS);
15253         if (auto *SMin = dyn_cast<SCEVSMinExpr>(FromRewritten))
15254           EnqueueOperands(SMin);
15255         break;
15256       case CmpInst::ICMP_EQ:
15257         if (isa<SCEVConstant>(RHS))
15258           To = RHS;
15259         break;
15260       case CmpInst::ICMP_NE:
15261         if (isa<SCEVConstant>(RHS) &&
15262             cast<SCEVConstant>(RHS)->getValue()->isNullValue()) {
15263           const SCEV *OneAlignedUp =
15264               DividesBy ? GetNextSCEVDividesByDivisor(One, DividesBy) : One;
15265           To = getUMaxExpr(FromRewritten, OneAlignedUp);
15266         }
15267         break;
15268       default:
15269         break;
15270       }
15271 
15272       if (To)
15273         AddRewrite(From, FromRewritten, To);
15274     }
15275   };
15276 
15277   BasicBlock *Header = L->getHeader();
15278   SmallVector<PointerIntPair<Value *, 1, bool>> Terms;
15279   // First, collect information from assumptions dominating the loop.
15280   for (auto &AssumeVH : AC.assumptions()) {
15281     if (!AssumeVH)
15282       continue;
15283     auto *AssumeI = cast<CallInst>(AssumeVH);
15284     if (!DT.dominates(AssumeI, Header))
15285       continue;
15286     Terms.emplace_back(AssumeI->getOperand(0), true);
15287   }
15288 
15289   // Second, collect information from llvm.experimental.guards dominating the loop.
15290   auto *GuardDecl = F.getParent()->getFunction(
15291       Intrinsic::getName(Intrinsic::experimental_guard));
15292   if (GuardDecl)
15293     for (const auto *GU : GuardDecl->users())
15294       if (const auto *Guard = dyn_cast<IntrinsicInst>(GU))
15295         if (Guard->getFunction() == Header->getParent() && DT.dominates(Guard, Header))
15296           Terms.emplace_back(Guard->getArgOperand(0), true);
15297 
15298   // Third, collect conditions from dominating branches. Starting at the loop
15299   // predecessor, climb up the predecessor chain, as long as there are
15300   // predecessors that can be found that have unique successors leading to the
15301   // original header.
15302   // TODO: share this logic with isLoopEntryGuardedByCond.
15303   for (std::pair<const BasicBlock *, const BasicBlock *> Pair(
15304            L->getLoopPredecessor(), Header);
15305        Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
15306 
15307     const BranchInst *LoopEntryPredicate =
15308         dyn_cast<BranchInst>(Pair.first->getTerminator());
15309     if (!LoopEntryPredicate || LoopEntryPredicate->isUnconditional())
15310       continue;
15311 
15312     Terms.emplace_back(LoopEntryPredicate->getCondition(),
15313                        LoopEntryPredicate->getSuccessor(0) == Pair.second);
15314   }
15315 
15316   // Now apply the information from the collected conditions to RewriteMap.
15317   // Conditions are processed in reverse order, so the earliest conditions is
15318   // processed first. This ensures the SCEVs with the shortest dependency chains
15319   // are constructed first.
15320   DenseMap<const SCEV *, const SCEV *> RewriteMap;
15321   for (auto [Term, EnterIfTrue] : reverse(Terms)) {
15322     SmallVector<Value *, 8> Worklist;
15323     SmallPtrSet<Value *, 8> Visited;
15324     Worklist.push_back(Term);
15325     while (!Worklist.empty()) {
15326       Value *Cond = Worklist.pop_back_val();
15327       if (!Visited.insert(Cond).second)
15328         continue;
15329 
15330       if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
15331         auto Predicate =
15332             EnterIfTrue ? Cmp->getPredicate() : Cmp->getInversePredicate();
15333         const auto *LHS = getSCEV(Cmp->getOperand(0));
15334         const auto *RHS = getSCEV(Cmp->getOperand(1));
15335         CollectCondition(Predicate, LHS, RHS, RewriteMap);
15336         continue;
15337       }
15338 
15339       Value *L, *R;
15340       if (EnterIfTrue ? match(Cond, m_LogicalAnd(m_Value(L), m_Value(R)))
15341                       : match(Cond, m_LogicalOr(m_Value(L), m_Value(R)))) {
15342         Worklist.push_back(L);
15343         Worklist.push_back(R);
15344       }
15345     }
15346   }
15347 
15348   if (RewriteMap.empty())
15349     return Expr;
15350 
15351   // Now that all rewrite information is collect, rewrite the collected
15352   // expressions with the information in the map. This applies information to
15353   // sub-expressions.
15354   if (ExprsToRewrite.size() > 1) {
15355     for (const SCEV *Expr : ExprsToRewrite) {
15356       const SCEV *RewriteTo = RewriteMap[Expr];
15357       RewriteMap.erase(Expr);
15358       SCEVLoopGuardRewriter Rewriter(*this, RewriteMap);
15359       RewriteMap.insert({Expr, Rewriter.visit(RewriteTo)});
15360     }
15361   }
15362 
15363   SCEVLoopGuardRewriter Rewriter(*this, RewriteMap);
15364   return Rewriter.visit(Expr);
15365 }
15366