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/None.h"
68 #include "llvm/ADT/Optional.h"
69 #include "llvm/ADT/STLExtras.h"
70 #include "llvm/ADT/ScopeExit.h"
71 #include "llvm/ADT/Sequence.h"
72 #include "llvm/ADT/SetVector.h"
73 #include "llvm/ADT/SmallPtrSet.h"
74 #include "llvm/ADT/SmallSet.h"
75 #include "llvm/ADT/SmallVector.h"
76 #include "llvm/ADT/Statistic.h"
77 #include "llvm/ADT/StringRef.h"
78 #include "llvm/Analysis/AssumptionCache.h"
79 #include "llvm/Analysis/ConstantFolding.h"
80 #include "llvm/Analysis/InstructionSimplify.h"
81 #include "llvm/Analysis/LoopInfo.h"
82 #include "llvm/Analysis/ScalarEvolutionDivision.h"
83 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
84 #include "llvm/Analysis/TargetLibraryInfo.h"
85 #include "llvm/Analysis/ValueTracking.h"
86 #include "llvm/Config/llvm-config.h"
87 #include "llvm/IR/Argument.h"
88 #include "llvm/IR/BasicBlock.h"
89 #include "llvm/IR/CFG.h"
90 #include "llvm/IR/Constant.h"
91 #include "llvm/IR/ConstantRange.h"
92 #include "llvm/IR/Constants.h"
93 #include "llvm/IR/DataLayout.h"
94 #include "llvm/IR/DerivedTypes.h"
95 #include "llvm/IR/Dominators.h"
96 #include "llvm/IR/Function.h"
97 #include "llvm/IR/GlobalAlias.h"
98 #include "llvm/IR/GlobalValue.h"
99 #include "llvm/IR/GlobalVariable.h"
100 #include "llvm/IR/InstIterator.h"
101 #include "llvm/IR/InstrTypes.h"
102 #include "llvm/IR/Instruction.h"
103 #include "llvm/IR/Instructions.h"
104 #include "llvm/IR/IntrinsicInst.h"
105 #include "llvm/IR/Intrinsics.h"
106 #include "llvm/IR/LLVMContext.h"
107 #include "llvm/IR/Metadata.h"
108 #include "llvm/IR/Operator.h"
109 #include "llvm/IR/PatternMatch.h"
110 #include "llvm/IR/Type.h"
111 #include "llvm/IR/Use.h"
112 #include "llvm/IR/User.h"
113 #include "llvm/IR/Value.h"
114 #include "llvm/IR/Verifier.h"
115 #include "llvm/InitializePasses.h"
116 #include "llvm/Pass.h"
117 #include "llvm/Support/Casting.h"
118 #include "llvm/Support/CommandLine.h"
119 #include "llvm/Support/Compiler.h"
120 #include "llvm/Support/Debug.h"
121 #include "llvm/Support/ErrorHandling.h"
122 #include "llvm/Support/KnownBits.h"
123 #include "llvm/Support/SaveAndRestore.h"
124 #include "llvm/Support/raw_ostream.h"
125 #include <algorithm>
126 #include <cassert>
127 #include <climits>
128 #include <cstddef>
129 #include <cstdint>
130 #include <cstdlib>
131 #include <map>
132 #include <memory>
133 #include <tuple>
134 #include <utility>
135 #include <vector>
136 
137 using namespace llvm;
138 using namespace PatternMatch;
139 
140 #define DEBUG_TYPE "scalar-evolution"
141 
142 STATISTIC(NumArrayLenItCounts,
143           "Number of trip counts computed with array length");
144 STATISTIC(NumTripCountsComputed,
145           "Number of loops with predictable loop counts");
146 STATISTIC(NumTripCountsNotComputed,
147           "Number of loops without predictable loop counts");
148 STATISTIC(NumBruteForceTripCountsComputed,
149           "Number of loops with trip counts computed by force");
150 
151 static cl::opt<unsigned>
152 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
153                         cl::ZeroOrMore,
154                         cl::desc("Maximum number of iterations SCEV will "
155                                  "symbolically execute a constant "
156                                  "derived loop"),
157                         cl::init(100));
158 
159 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean.
160 static cl::opt<bool> VerifySCEV(
161     "verify-scev", cl::Hidden,
162     cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
163 static cl::opt<bool> VerifySCEVStrict(
164     "verify-scev-strict", cl::Hidden,
165     cl::desc("Enable stricter verification with -verify-scev is passed"));
166 static cl::opt<bool>
167     VerifySCEVMap("verify-scev-maps", cl::Hidden,
168                   cl::desc("Verify no dangling value in ScalarEvolution's "
169                            "ExprValueMap (slow)"));
170 
171 static cl::opt<bool> VerifyIR(
172     "scev-verify-ir", cl::Hidden,
173     cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"),
174     cl::init(false));
175 
176 static cl::opt<unsigned> MulOpsInlineThreshold(
177     "scev-mulops-inline-threshold", cl::Hidden,
178     cl::desc("Threshold for inlining multiplication operands into a SCEV"),
179     cl::init(32));
180 
181 static cl::opt<unsigned> AddOpsInlineThreshold(
182     "scev-addops-inline-threshold", cl::Hidden,
183     cl::desc("Threshold for inlining addition operands into a SCEV"),
184     cl::init(500));
185 
186 static cl::opt<unsigned> MaxSCEVCompareDepth(
187     "scalar-evolution-max-scev-compare-depth", cl::Hidden,
188     cl::desc("Maximum depth of recursive SCEV complexity comparisons"),
189     cl::init(32));
190 
191 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth(
192     "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden,
193     cl::desc("Maximum depth of recursive SCEV operations implication analysis"),
194     cl::init(2));
195 
196 static cl::opt<unsigned> MaxValueCompareDepth(
197     "scalar-evolution-max-value-compare-depth", cl::Hidden,
198     cl::desc("Maximum depth of recursive value complexity comparisons"),
199     cl::init(2));
200 
201 static cl::opt<unsigned>
202     MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden,
203                   cl::desc("Maximum depth of recursive arithmetics"),
204                   cl::init(32));
205 
206 static cl::opt<unsigned> MaxConstantEvolvingDepth(
207     "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
208     cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
209 
210 static cl::opt<unsigned>
211     MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden,
212                  cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"),
213                  cl::init(8));
214 
215 static cl::opt<unsigned>
216     MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden,
217                   cl::desc("Max coefficients in AddRec during evolving"),
218                   cl::init(8));
219 
220 static cl::opt<unsigned>
221     HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden,
222                   cl::desc("Size of the expression which is considered huge"),
223                   cl::init(4096));
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 //===----------------------------------------------------------------------===//
237 //                           SCEV class definitions
238 //===----------------------------------------------------------------------===//
239 
240 //===----------------------------------------------------------------------===//
241 // Implementation of the SCEV class.
242 //
243 
244 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
245 LLVM_DUMP_METHOD void SCEV::dump() const {
246   print(dbgs());
247   dbgs() << '\n';
248 }
249 #endif
250 
251 void SCEV::print(raw_ostream &OS) const {
252   switch (getSCEVType()) {
253   case scConstant:
254     cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
255     return;
256   case scPtrToInt: {
257     const SCEVPtrToIntExpr *PtrToInt = cast<SCEVPtrToIntExpr>(this);
258     const SCEV *Op = PtrToInt->getOperand();
259     OS << "(ptrtoint " << *Op->getType() << " " << *Op << " to "
260        << *PtrToInt->getType() << ")";
261     return;
262   }
263   case scTruncate: {
264     const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
265     const SCEV *Op = Trunc->getOperand();
266     OS << "(trunc " << *Op->getType() << " " << *Op << " to "
267        << *Trunc->getType() << ")";
268     return;
269   }
270   case scZeroExtend: {
271     const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
272     const SCEV *Op = ZExt->getOperand();
273     OS << "(zext " << *Op->getType() << " " << *Op << " to "
274        << *ZExt->getType() << ")";
275     return;
276   }
277   case scSignExtend: {
278     const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
279     const SCEV *Op = SExt->getOperand();
280     OS << "(sext " << *Op->getType() << " " << *Op << " to "
281        << *SExt->getType() << ")";
282     return;
283   }
284   case scAddRecExpr: {
285     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
286     OS << "{" << *AR->getOperand(0);
287     for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
288       OS << ",+," << *AR->getOperand(i);
289     OS << "}<";
290     if (AR->hasNoUnsignedWrap())
291       OS << "nuw><";
292     if (AR->hasNoSignedWrap())
293       OS << "nsw><";
294     if (AR->hasNoSelfWrap() &&
295         !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
296       OS << "nw><";
297     AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
298     OS << ">";
299     return;
300   }
301   case scAddExpr:
302   case scMulExpr:
303   case scUMaxExpr:
304   case scSMaxExpr:
305   case scUMinExpr:
306   case scSMinExpr: {
307     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
308     const char *OpStr = nullptr;
309     switch (NAry->getSCEVType()) {
310     case scAddExpr: OpStr = " + "; break;
311     case scMulExpr: OpStr = " * "; break;
312     case scUMaxExpr: OpStr = " umax "; break;
313     case scSMaxExpr: OpStr = " smax "; break;
314     case scUMinExpr:
315       OpStr = " umin ";
316       break;
317     case scSMinExpr:
318       OpStr = " smin ";
319       break;
320     default:
321       llvm_unreachable("There are no other nary expression types.");
322     }
323     OS << "(";
324     ListSeparator LS(OpStr);
325     for (const SCEV *Op : NAry->operands())
326       OS << LS << *Op;
327     OS << ")";
328     switch (NAry->getSCEVType()) {
329     case scAddExpr:
330     case scMulExpr:
331       if (NAry->hasNoUnsignedWrap())
332         OS << "<nuw>";
333       if (NAry->hasNoSignedWrap())
334         OS << "<nsw>";
335       break;
336     default:
337       // Nothing to print for other nary expressions.
338       break;
339     }
340     return;
341   }
342   case scUDivExpr: {
343     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
344     OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
345     return;
346   }
347   case scUnknown: {
348     const SCEVUnknown *U = cast<SCEVUnknown>(this);
349     Type *AllocTy;
350     if (U->isSizeOf(AllocTy)) {
351       OS << "sizeof(" << *AllocTy << ")";
352       return;
353     }
354     if (U->isAlignOf(AllocTy)) {
355       OS << "alignof(" << *AllocTy << ")";
356       return;
357     }
358 
359     Type *CTy;
360     Constant *FieldNo;
361     if (U->isOffsetOf(CTy, FieldNo)) {
362       OS << "offsetof(" << *CTy << ", ";
363       FieldNo->printAsOperand(OS, false);
364       OS << ")";
365       return;
366     }
367 
368     // Otherwise just print it normally.
369     U->getValue()->printAsOperand(OS, false);
370     return;
371   }
372   case scCouldNotCompute:
373     OS << "***COULDNOTCOMPUTE***";
374     return;
375   }
376   llvm_unreachable("Unknown SCEV kind!");
377 }
378 
379 Type *SCEV::getType() const {
380   switch (getSCEVType()) {
381   case scConstant:
382     return cast<SCEVConstant>(this)->getType();
383   case scPtrToInt:
384   case scTruncate:
385   case scZeroExtend:
386   case scSignExtend:
387     return cast<SCEVCastExpr>(this)->getType();
388   case scAddRecExpr:
389   case scMulExpr:
390   case scUMaxExpr:
391   case scSMaxExpr:
392   case scUMinExpr:
393   case scSMinExpr:
394     return cast<SCEVNAryExpr>(this)->getType();
395   case scAddExpr:
396     return cast<SCEVAddExpr>(this)->getType();
397   case scUDivExpr:
398     return cast<SCEVUDivExpr>(this)->getType();
399   case scUnknown:
400     return cast<SCEVUnknown>(this)->getType();
401   case scCouldNotCompute:
402     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
403   }
404   llvm_unreachable("Unknown SCEV kind!");
405 }
406 
407 bool SCEV::isZero() const {
408   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
409     return SC->getValue()->isZero();
410   return false;
411 }
412 
413 bool SCEV::isOne() const {
414   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
415     return SC->getValue()->isOne();
416   return false;
417 }
418 
419 bool SCEV::isAllOnesValue() const {
420   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
421     return SC->getValue()->isMinusOne();
422   return false;
423 }
424 
425 bool SCEV::isNonConstantNegative() const {
426   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
427   if (!Mul) return false;
428 
429   // If there is a constant factor, it will be first.
430   const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
431   if (!SC) return false;
432 
433   // Return true if the value is negative, this matches things like (-42 * V).
434   return SC->getAPInt().isNegative();
435 }
436 
437 SCEVCouldNotCompute::SCEVCouldNotCompute() :
438   SCEV(FoldingSetNodeIDRef(), scCouldNotCompute, 0) {}
439 
440 bool SCEVCouldNotCompute::classof(const SCEV *S) {
441   return S->getSCEVType() == scCouldNotCompute;
442 }
443 
444 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
445   FoldingSetNodeID ID;
446   ID.AddInteger(scConstant);
447   ID.AddPointer(V);
448   void *IP = nullptr;
449   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
450   SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
451   UniqueSCEVs.InsertNode(S, IP);
452   return S;
453 }
454 
455 const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
456   return getConstant(ConstantInt::get(getContext(), Val));
457 }
458 
459 const SCEV *
460 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
461   IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
462   return getConstant(ConstantInt::get(ITy, V, isSigned));
463 }
464 
465 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy,
466                            const SCEV *op, Type *ty)
467     : SCEV(ID, SCEVTy, computeExpressionSize(op)), Ty(ty) {
468   Operands[0] = op;
469 }
470 
471 SCEVPtrToIntExpr::SCEVPtrToIntExpr(const FoldingSetNodeIDRef ID, const SCEV *Op,
472                                    Type *ITy)
473     : SCEVCastExpr(ID, scPtrToInt, Op, ITy) {
474   assert(getOperand()->getType()->isPointerTy() && Ty->isIntegerTy() &&
475          "Must be a non-bit-width-changing pointer-to-integer cast!");
476 }
477 
478 SCEVIntegralCastExpr::SCEVIntegralCastExpr(const FoldingSetNodeIDRef ID,
479                                            SCEVTypes SCEVTy, const SCEV *op,
480                                            Type *ty)
481     : SCEVCastExpr(ID, SCEVTy, op, ty) {}
482 
483 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, const SCEV *op,
484                                    Type *ty)
485     : SCEVIntegralCastExpr(ID, scTruncate, op, ty) {
486   assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
487          "Cannot truncate non-integer value!");
488 }
489 
490 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
491                                        const SCEV *op, Type *ty)
492     : SCEVIntegralCastExpr(ID, scZeroExtend, op, ty) {
493   assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
494          "Cannot zero extend non-integer value!");
495 }
496 
497 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
498                                        const SCEV *op, Type *ty)
499     : SCEVIntegralCastExpr(ID, scSignExtend, op, ty) {
500   assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
501          "Cannot sign extend non-integer value!");
502 }
503 
504 void SCEVUnknown::deleted() {
505   // Clear this SCEVUnknown from various maps.
506   SE->forgetMemoizedResults(this);
507 
508   // Remove this SCEVUnknown from the uniquing map.
509   SE->UniqueSCEVs.RemoveNode(this);
510 
511   // Release the value.
512   setValPtr(nullptr);
513 }
514 
515 void SCEVUnknown::allUsesReplacedWith(Value *New) {
516   // Remove this SCEVUnknown from the uniquing map.
517   SE->UniqueSCEVs.RemoveNode(this);
518 
519   // Update this SCEVUnknown to point to the new value. This is needed
520   // because there may still be outstanding SCEVs which still point to
521   // this SCEVUnknown.
522   setValPtr(New);
523 }
524 
525 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
526   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
527     if (VCE->getOpcode() == Instruction::PtrToInt)
528       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
529         if (CE->getOpcode() == Instruction::GetElementPtr &&
530             CE->getOperand(0)->isNullValue() &&
531             CE->getNumOperands() == 2)
532           if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
533             if (CI->isOne()) {
534               AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
535                                  ->getElementType();
536               return true;
537             }
538 
539   return false;
540 }
541 
542 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
543   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
544     if (VCE->getOpcode() == Instruction::PtrToInt)
545       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
546         if (CE->getOpcode() == Instruction::GetElementPtr &&
547             CE->getOperand(0)->isNullValue()) {
548           Type *Ty =
549             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
550           if (StructType *STy = dyn_cast<StructType>(Ty))
551             if (!STy->isPacked() &&
552                 CE->getNumOperands() == 3 &&
553                 CE->getOperand(1)->isNullValue()) {
554               if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
555                 if (CI->isOne() &&
556                     STy->getNumElements() == 2 &&
557                     STy->getElementType(0)->isIntegerTy(1)) {
558                   AllocTy = STy->getElementType(1);
559                   return true;
560                 }
561             }
562         }
563 
564   return false;
565 }
566 
567 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
568   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
569     if (VCE->getOpcode() == Instruction::PtrToInt)
570       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
571         if (CE->getOpcode() == Instruction::GetElementPtr &&
572             CE->getNumOperands() == 3 &&
573             CE->getOperand(0)->isNullValue() &&
574             CE->getOperand(1)->isNullValue()) {
575           Type *Ty =
576             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
577           // Ignore vector types here so that ScalarEvolutionExpander doesn't
578           // emit getelementptrs that index into vectors.
579           if (Ty->isStructTy() || Ty->isArrayTy()) {
580             CTy = Ty;
581             FieldNo = CE->getOperand(2);
582             return true;
583           }
584         }
585 
586   return false;
587 }
588 
589 //===----------------------------------------------------------------------===//
590 //                               SCEV Utilities
591 //===----------------------------------------------------------------------===//
592 
593 /// Compare the two values \p LV and \p RV in terms of their "complexity" where
594 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order
595 /// operands in SCEV expressions.  \p EqCache is a set of pairs of values that
596 /// have been previously deemed to be "equally complex" by this routine.  It is
597 /// intended to avoid exponential time complexity in cases like:
598 ///
599 ///   %a = f(%x, %y)
600 ///   %b = f(%a, %a)
601 ///   %c = f(%b, %b)
602 ///
603 ///   %d = f(%x, %y)
604 ///   %e = f(%d, %d)
605 ///   %f = f(%e, %e)
606 ///
607 ///   CompareValueComplexity(%f, %c)
608 ///
609 /// Since we do not continue running this routine on expression trees once we
610 /// have seen unequal values, there is no need to track them in the cache.
611 static int
612 CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue,
613                        const LoopInfo *const LI, Value *LV, Value *RV,
614                        unsigned Depth) {
615   if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV))
616     return 0;
617 
618   // Order pointer values after integer values. This helps SCEVExpander form
619   // GEPs.
620   bool LIsPointer = LV->getType()->isPointerTy(),
621        RIsPointer = RV->getType()->isPointerTy();
622   if (LIsPointer != RIsPointer)
623     return (int)LIsPointer - (int)RIsPointer;
624 
625   // Compare getValueID values.
626   unsigned LID = LV->getValueID(), RID = RV->getValueID();
627   if (LID != RID)
628     return (int)LID - (int)RID;
629 
630   // Sort arguments by their position.
631   if (const auto *LA = dyn_cast<Argument>(LV)) {
632     const auto *RA = cast<Argument>(RV);
633     unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
634     return (int)LArgNo - (int)RArgNo;
635   }
636 
637   if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
638     const auto *RGV = cast<GlobalValue>(RV);
639 
640     const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
641       auto LT = GV->getLinkage();
642       return !(GlobalValue::isPrivateLinkage(LT) ||
643                GlobalValue::isInternalLinkage(LT));
644     };
645 
646     // Use the names to distinguish the two values, but only if the
647     // names are semantically important.
648     if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
649       return LGV->getName().compare(RGV->getName());
650   }
651 
652   // For instructions, compare their loop depth, and their operand count.  This
653   // is pretty loose.
654   if (const auto *LInst = dyn_cast<Instruction>(LV)) {
655     const auto *RInst = cast<Instruction>(RV);
656 
657     // Compare loop depths.
658     const BasicBlock *LParent = LInst->getParent(),
659                      *RParent = RInst->getParent();
660     if (LParent != RParent) {
661       unsigned LDepth = LI->getLoopDepth(LParent),
662                RDepth = LI->getLoopDepth(RParent);
663       if (LDepth != RDepth)
664         return (int)LDepth - (int)RDepth;
665     }
666 
667     // Compare the number of operands.
668     unsigned LNumOps = LInst->getNumOperands(),
669              RNumOps = RInst->getNumOperands();
670     if (LNumOps != RNumOps)
671       return (int)LNumOps - (int)RNumOps;
672 
673     for (unsigned Idx : seq(0u, LNumOps)) {
674       int Result =
675           CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx),
676                                  RInst->getOperand(Idx), Depth + 1);
677       if (Result != 0)
678         return Result;
679     }
680   }
681 
682   EqCacheValue.unionSets(LV, RV);
683   return 0;
684 }
685 
686 // Return negative, zero, or positive, if LHS is less than, equal to, or greater
687 // than RHS, respectively. A three-way result allows recursive comparisons to be
688 // more efficient.
689 // If the max analysis depth was reached, return None, assuming we do not know
690 // if they are equivalent for sure.
691 static Optional<int>
692 CompareSCEVComplexity(EquivalenceClasses<const SCEV *> &EqCacheSCEV,
693                       EquivalenceClasses<const Value *> &EqCacheValue,
694                       const LoopInfo *const LI, const SCEV *LHS,
695                       const SCEV *RHS, DominatorTree &DT, unsigned Depth = 0) {
696   // Fast-path: SCEVs are uniqued so we can do a quick equality check.
697   if (LHS == RHS)
698     return 0;
699 
700   // Primarily, sort the SCEVs by their getSCEVType().
701   SCEVTypes LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
702   if (LType != RType)
703     return (int)LType - (int)RType;
704 
705   if (EqCacheSCEV.isEquivalent(LHS, RHS))
706     return 0;
707 
708   if (Depth > MaxSCEVCompareDepth)
709     return None;
710 
711   // Aside from the getSCEVType() ordering, the particular ordering
712   // isn't very important except that it's beneficial to be consistent,
713   // so that (a + b) and (b + a) don't end up as different expressions.
714   switch (LType) {
715   case scUnknown: {
716     const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
717     const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
718 
719     int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(),
720                                    RU->getValue(), Depth + 1);
721     if (X == 0)
722       EqCacheSCEV.unionSets(LHS, RHS);
723     return X;
724   }
725 
726   case scConstant: {
727     const SCEVConstant *LC = cast<SCEVConstant>(LHS);
728     const SCEVConstant *RC = cast<SCEVConstant>(RHS);
729 
730     // Compare constant values.
731     const APInt &LA = LC->getAPInt();
732     const APInt &RA = RC->getAPInt();
733     unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
734     if (LBitWidth != RBitWidth)
735       return (int)LBitWidth - (int)RBitWidth;
736     return LA.ult(RA) ? -1 : 1;
737   }
738 
739   case scAddRecExpr: {
740     const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
741     const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
742 
743     // There is always a dominance between two recs that are used by one SCEV,
744     // so we can safely sort recs by loop header dominance. We require such
745     // order in getAddExpr.
746     const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
747     if (LLoop != RLoop) {
748       const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
749       assert(LHead != RHead && "Two loops share the same header?");
750       if (DT.dominates(LHead, RHead))
751         return 1;
752       else
753         assert(DT.dominates(RHead, LHead) &&
754                "No dominance between recurrences used by one SCEV?");
755       return -1;
756     }
757 
758     // Addrec complexity grows with operand count.
759     unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
760     if (LNumOps != RNumOps)
761       return (int)LNumOps - (int)RNumOps;
762 
763     // Lexicographically compare.
764     for (unsigned i = 0; i != LNumOps; ++i) {
765       auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
766                                      LA->getOperand(i), RA->getOperand(i), DT,
767                                      Depth + 1);
768       if (X != 0)
769         return X;
770     }
771     EqCacheSCEV.unionSets(LHS, RHS);
772     return 0;
773   }
774 
775   case scAddExpr:
776   case scMulExpr:
777   case scSMaxExpr:
778   case scUMaxExpr:
779   case scSMinExpr:
780   case scUMinExpr: {
781     const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
782     const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
783 
784     // Lexicographically compare n-ary expressions.
785     unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
786     if (LNumOps != RNumOps)
787       return (int)LNumOps - (int)RNumOps;
788 
789     for (unsigned i = 0; i != LNumOps; ++i) {
790       auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
791                                      LC->getOperand(i), RC->getOperand(i), DT,
792                                      Depth + 1);
793       if (X != 0)
794         return X;
795     }
796     EqCacheSCEV.unionSets(LHS, RHS);
797     return 0;
798   }
799 
800   case scUDivExpr: {
801     const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
802     const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
803 
804     // Lexicographically compare udiv expressions.
805     auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(),
806                                    RC->getLHS(), DT, Depth + 1);
807     if (X != 0)
808       return X;
809     X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(),
810                               RC->getRHS(), DT, Depth + 1);
811     if (X == 0)
812       EqCacheSCEV.unionSets(LHS, RHS);
813     return X;
814   }
815 
816   case scPtrToInt:
817   case scTruncate:
818   case scZeroExtend:
819   case scSignExtend: {
820     const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
821     const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
822 
823     // Compare cast expressions by operand.
824     auto X =
825         CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getOperand(),
826                               RC->getOperand(), DT, Depth + 1);
827     if (X == 0)
828       EqCacheSCEV.unionSets(LHS, RHS);
829     return X;
830   }
831 
832   case scCouldNotCompute:
833     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
834   }
835   llvm_unreachable("Unknown SCEV kind!");
836 }
837 
838 /// Given a list of SCEV objects, order them by their complexity, and group
839 /// objects of the same complexity together by value.  When this routine is
840 /// finished, we know that any duplicates in the vector are consecutive and that
841 /// complexity is monotonically increasing.
842 ///
843 /// Note that we go take special precautions to ensure that we get deterministic
844 /// results from this routine.  In other words, we don't want the results of
845 /// this to depend on where the addresses of various SCEV objects happened to
846 /// land in memory.
847 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
848                               LoopInfo *LI, DominatorTree &DT) {
849   if (Ops.size() < 2) return;  // Noop
850 
851   EquivalenceClasses<const SCEV *> EqCacheSCEV;
852   EquivalenceClasses<const Value *> EqCacheValue;
853 
854   // Whether LHS has provably less complexity than RHS.
855   auto IsLessComplex = [&](const SCEV *LHS, const SCEV *RHS) {
856     auto Complexity =
857         CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LHS, RHS, DT);
858     return Complexity && *Complexity < 0;
859   };
860   if (Ops.size() == 2) {
861     // This is the common case, which also happens to be trivially simple.
862     // Special case it.
863     const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
864     if (IsLessComplex(RHS, LHS))
865       std::swap(LHS, RHS);
866     return;
867   }
868 
869   // Do the rough sort by complexity.
870   llvm::stable_sort(Ops, [&](const SCEV *LHS, const SCEV *RHS) {
871     return IsLessComplex(LHS, RHS);
872   });
873 
874   // Now that we are sorted by complexity, group elements of the same
875   // complexity.  Note that this is, at worst, N^2, but the vector is likely to
876   // be extremely short in practice.  Note that we take this approach because we
877   // do not want to depend on the addresses of the objects we are grouping.
878   for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
879     const SCEV *S = Ops[i];
880     unsigned Complexity = S->getSCEVType();
881 
882     // If there are any objects of the same complexity and same value as this
883     // one, group them.
884     for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
885       if (Ops[j] == S) { // Found a duplicate.
886         // Move it to immediately after i'th element.
887         std::swap(Ops[i+1], Ops[j]);
888         ++i;   // no need to rescan it.
889         if (i == e-2) return;  // Done!
890       }
891     }
892   }
893 }
894 
895 /// Returns true if \p Ops contains a huge SCEV (the subtree of S contains at
896 /// least HugeExprThreshold nodes).
897 static bool hasHugeExpression(ArrayRef<const SCEV *> Ops) {
898   return any_of(Ops, [](const SCEV *S) {
899     return S->getExpressionSize() >= HugeExprThreshold;
900   });
901 }
902 
903 //===----------------------------------------------------------------------===//
904 //                      Simple SCEV method implementations
905 //===----------------------------------------------------------------------===//
906 
907 /// Compute BC(It, K).  The result has width W.  Assume, K > 0.
908 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
909                                        ScalarEvolution &SE,
910                                        Type *ResultTy) {
911   // Handle the simplest case efficiently.
912   if (K == 1)
913     return SE.getTruncateOrZeroExtend(It, ResultTy);
914 
915   // We are using the following formula for BC(It, K):
916   //
917   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
918   //
919   // Suppose, W is the bitwidth of the return value.  We must be prepared for
920   // overflow.  Hence, we must assure that the result of our computation is
921   // equal to the accurate one modulo 2^W.  Unfortunately, division isn't
922   // safe in modular arithmetic.
923   //
924   // However, this code doesn't use exactly that formula; the formula it uses
925   // is something like the following, where T is the number of factors of 2 in
926   // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
927   // exponentiation:
928   //
929   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
930   //
931   // This formula is trivially equivalent to the previous formula.  However,
932   // this formula can be implemented much more efficiently.  The trick is that
933   // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
934   // arithmetic.  To do exact division in modular arithmetic, all we have
935   // to do is multiply by the inverse.  Therefore, this step can be done at
936   // width W.
937   //
938   // The next issue is how to safely do the division by 2^T.  The way this
939   // is done is by doing the multiplication step at a width of at least W + T
940   // bits.  This way, the bottom W+T bits of the product are accurate. Then,
941   // when we perform the division by 2^T (which is equivalent to a right shift
942   // by T), the bottom W bits are accurate.  Extra bits are okay; they'll get
943   // truncated out after the division by 2^T.
944   //
945   // In comparison to just directly using the first formula, this technique
946   // is much more efficient; using the first formula requires W * K bits,
947   // but this formula less than W + K bits. Also, the first formula requires
948   // a division step, whereas this formula only requires multiplies and shifts.
949   //
950   // It doesn't matter whether the subtraction step is done in the calculation
951   // width or the input iteration count's width; if the subtraction overflows,
952   // the result must be zero anyway.  We prefer here to do it in the width of
953   // the induction variable because it helps a lot for certain cases; CodeGen
954   // isn't smart enough to ignore the overflow, which leads to much less
955   // efficient code if the width of the subtraction is wider than the native
956   // register width.
957   //
958   // (It's possible to not widen at all by pulling out factors of 2 before
959   // the multiplication; for example, K=2 can be calculated as
960   // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
961   // extra arithmetic, so it's not an obvious win, and it gets
962   // much more complicated for K > 3.)
963 
964   // Protection from insane SCEVs; this bound is conservative,
965   // but it probably doesn't matter.
966   if (K > 1000)
967     return SE.getCouldNotCompute();
968 
969   unsigned W = SE.getTypeSizeInBits(ResultTy);
970 
971   // Calculate K! / 2^T and T; we divide out the factors of two before
972   // multiplying for calculating K! / 2^T to avoid overflow.
973   // Other overflow doesn't matter because we only care about the bottom
974   // W bits of the result.
975   APInt OddFactorial(W, 1);
976   unsigned T = 1;
977   for (unsigned i = 3; i <= K; ++i) {
978     APInt Mult(W, i);
979     unsigned TwoFactors = Mult.countTrailingZeros();
980     T += TwoFactors;
981     Mult.lshrInPlace(TwoFactors);
982     OddFactorial *= Mult;
983   }
984 
985   // We need at least W + T bits for the multiplication step
986   unsigned CalculationBits = W + T;
987 
988   // Calculate 2^T, at width T+W.
989   APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
990 
991   // Calculate the multiplicative inverse of K! / 2^T;
992   // this multiplication factor will perform the exact division by
993   // K! / 2^T.
994   APInt Mod = APInt::getSignedMinValue(W+1);
995   APInt MultiplyFactor = OddFactorial.zext(W+1);
996   MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
997   MultiplyFactor = MultiplyFactor.trunc(W);
998 
999   // Calculate the product, at width T+W
1000   IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
1001                                                       CalculationBits);
1002   const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
1003   for (unsigned i = 1; i != K; ++i) {
1004     const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
1005     Dividend = SE.getMulExpr(Dividend,
1006                              SE.getTruncateOrZeroExtend(S, CalculationTy));
1007   }
1008 
1009   // Divide by 2^T
1010   const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
1011 
1012   // Truncate the result, and divide by K! / 2^T.
1013 
1014   return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1015                        SE.getTruncateOrZeroExtend(DivResult, ResultTy));
1016 }
1017 
1018 /// Return the value of this chain of recurrences at the specified iteration
1019 /// number.  We can evaluate this recurrence by multiplying each element in the
1020 /// chain by the binomial coefficient corresponding to it.  In other words, we
1021 /// can evaluate {A,+,B,+,C,+,D} as:
1022 ///
1023 ///   A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
1024 ///
1025 /// where BC(It, k) stands for binomial coefficient.
1026 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
1027                                                 ScalarEvolution &SE) const {
1028   const SCEV *Result = getStart();
1029   for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1030     // The computation is correct in the face of overflow provided that the
1031     // multiplication is performed _after_ the evaluation of the binomial
1032     // coefficient.
1033     const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
1034     if (isa<SCEVCouldNotCompute>(Coeff))
1035       return Coeff;
1036 
1037     Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
1038   }
1039   return Result;
1040 }
1041 
1042 //===----------------------------------------------------------------------===//
1043 //                    SCEV Expression folder implementations
1044 //===----------------------------------------------------------------------===//
1045 
1046 const SCEV *ScalarEvolution::getPtrToIntExpr(const SCEV *Op, Type *Ty,
1047                                              unsigned Depth) {
1048   assert(Ty->isIntegerTy() && "Target type must be an integer type!");
1049   assert(Depth <= 1 && "getPtrToIntExpr() should self-recurse at most once.");
1050 
1051   // We could be called with an integer-typed operands during SCEV rewrites.
1052   // Since the operand is an integer already, just perform zext/trunc/self cast.
1053   if (!Op->getType()->isPointerTy())
1054     return getTruncateOrZeroExtend(Op, Ty);
1055 
1056   // What would be an ID for such a SCEV cast expression?
1057   FoldingSetNodeID ID;
1058   ID.AddInteger(scPtrToInt);
1059   ID.AddPointer(Op);
1060 
1061   void *IP = nullptr;
1062 
1063   // Is there already an expression for such a cast?
1064   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1065     return getTruncateOrZeroExtend(S, Ty);
1066 
1067   // If not, is this expression something we can't reduce any further?
1068   if (isa<SCEVUnknown>(Op)) {
1069     // Create an explicit cast node.
1070     // We can reuse the existing insert position since if we get here,
1071     // we won't have made any changes which would invalidate it.
1072     Type *IntPtrTy = getDataLayout().getIntPtrType(Op->getType());
1073     assert(getDataLayout().getTypeSizeInBits(getEffectiveSCEVType(
1074                Op->getType())) == getDataLayout().getTypeSizeInBits(IntPtrTy) &&
1075            "We can only model ptrtoint if SCEV's effective (integer) type is "
1076            "sufficiently wide to represent all possible pointer values.");
1077     SCEV *S = new (SCEVAllocator)
1078         SCEVPtrToIntExpr(ID.Intern(SCEVAllocator), Op, IntPtrTy);
1079     UniqueSCEVs.InsertNode(S, IP);
1080     addToLoopUseLists(S);
1081     return getTruncateOrZeroExtend(S, Ty);
1082   }
1083 
1084   assert(Depth == 0 &&
1085          "getPtrToIntExpr() should not self-recurse for non-SCEVUnknown's.");
1086 
1087   // Otherwise, we've got some expression that is more complex than just a
1088   // single SCEVUnknown. But we don't want to have a SCEVPtrToIntExpr of an
1089   // arbitrary expression, we want to have SCEVPtrToIntExpr of an SCEVUnknown
1090   // only, and the expressions must otherwise be integer-typed.
1091   // So sink the cast down to the SCEVUnknown's.
1092 
1093   /// The SCEVPtrToIntSinkingRewriter takes a scalar evolution expression,
1094   /// which computes a pointer-typed value, and rewrites the whole expression
1095   /// tree so that *all* the computations are done on integers, and the only
1096   /// pointer-typed operands in the expression are SCEVUnknown.
1097   class SCEVPtrToIntSinkingRewriter
1098       : public SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter> {
1099     using Base = SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter>;
1100 
1101   public:
1102     SCEVPtrToIntSinkingRewriter(ScalarEvolution &SE) : SCEVRewriteVisitor(SE) {}
1103 
1104     static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE) {
1105       SCEVPtrToIntSinkingRewriter Rewriter(SE);
1106       return Rewriter.visit(Scev);
1107     }
1108 
1109     const SCEV *visit(const SCEV *S) {
1110       Type *STy = S->getType();
1111       // If the expression is not pointer-typed, just keep it as-is.
1112       if (!STy->isPointerTy())
1113         return S;
1114       // Else, recursively sink the cast down into it.
1115       return Base::visit(S);
1116     }
1117 
1118     const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
1119       SmallVector<const SCEV *, 2> Operands;
1120       bool Changed = false;
1121       for (auto *Op : Expr->operands()) {
1122         Operands.push_back(visit(Op));
1123         Changed |= Op != Operands.back();
1124       }
1125       return !Changed ? Expr : SE.getAddExpr(Operands, Expr->getNoWrapFlags());
1126     }
1127 
1128     const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
1129       SmallVector<const SCEV *, 2> Operands;
1130       bool Changed = false;
1131       for (auto *Op : Expr->operands()) {
1132         Operands.push_back(visit(Op));
1133         Changed |= Op != Operands.back();
1134       }
1135       return !Changed ? Expr : SE.getMulExpr(Operands, Expr->getNoWrapFlags());
1136     }
1137 
1138     const SCEV *visitUnknown(const SCEVUnknown *Expr) {
1139       Type *ExprPtrTy = Expr->getType();
1140       assert(ExprPtrTy->isPointerTy() &&
1141              "Should only reach pointer-typed SCEVUnknown's.");
1142       Type *ExprIntPtrTy = SE.getDataLayout().getIntPtrType(ExprPtrTy);
1143       return SE.getPtrToIntExpr(Expr, ExprIntPtrTy, /*Depth=*/1);
1144     }
1145   };
1146 
1147   // And actually perform the cast sinking.
1148   const SCEV *IntOp = SCEVPtrToIntSinkingRewriter::rewrite(Op, *this);
1149   assert(IntOp->getType()->isIntegerTy() &&
1150          "We must have succeeded in sinking the cast, "
1151          "and ending up with an integer-typed expression!");
1152   return getTruncateOrZeroExtend(IntOp, Ty);
1153 }
1154 
1155 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, Type *Ty,
1156                                              unsigned Depth) {
1157   assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1158          "This is not a truncating conversion!");
1159   assert(isSCEVable(Ty) &&
1160          "This is not a conversion to a SCEVable type!");
1161   Ty = getEffectiveSCEVType(Ty);
1162 
1163   FoldingSetNodeID ID;
1164   ID.AddInteger(scTruncate);
1165   ID.AddPointer(Op);
1166   ID.AddPointer(Ty);
1167   void *IP = nullptr;
1168   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1169 
1170   // Fold if the operand is constant.
1171   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1172     return getConstant(
1173       cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1174 
1175   // trunc(trunc(x)) --> trunc(x)
1176   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
1177     return getTruncateExpr(ST->getOperand(), Ty, Depth + 1);
1178 
1179   // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1180   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1181     return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1);
1182 
1183   // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1184   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1185     return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1);
1186 
1187   if (Depth > MaxCastDepth) {
1188     SCEV *S =
1189         new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty);
1190     UniqueSCEVs.InsertNode(S, IP);
1191     addToLoopUseLists(S);
1192     return S;
1193   }
1194 
1195   // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and
1196   // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN),
1197   // if after transforming we have at most one truncate, not counting truncates
1198   // that replace other casts.
1199   if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) {
1200     auto *CommOp = cast<SCEVCommutativeExpr>(Op);
1201     SmallVector<const SCEV *, 4> Operands;
1202     unsigned numTruncs = 0;
1203     for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2;
1204          ++i) {
1205       const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1);
1206       if (!isa<SCEVIntegralCastExpr>(CommOp->getOperand(i)) &&
1207           isa<SCEVTruncateExpr>(S))
1208         numTruncs++;
1209       Operands.push_back(S);
1210     }
1211     if (numTruncs < 2) {
1212       if (isa<SCEVAddExpr>(Op))
1213         return getAddExpr(Operands);
1214       else if (isa<SCEVMulExpr>(Op))
1215         return getMulExpr(Operands);
1216       else
1217         llvm_unreachable("Unexpected SCEV type for Op.");
1218     }
1219     // Although we checked in the beginning that ID is not in the cache, it is
1220     // possible that during recursion and different modification ID was inserted
1221     // into the cache. So if we find it, just return it.
1222     if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1223       return S;
1224   }
1225 
1226   // If the input value is a chrec scev, truncate the chrec's operands.
1227   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1228     SmallVector<const SCEV *, 4> Operands;
1229     for (const SCEV *Op : AddRec->operands())
1230       Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1));
1231     return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1232   }
1233 
1234   // Return zero if truncating to known zeros.
1235   uint32_t MinTrailingZeros = GetMinTrailingZeros(Op);
1236   if (MinTrailingZeros >= getTypeSizeInBits(Ty))
1237     return getZero(Ty);
1238 
1239   // The cast wasn't folded; create an explicit cast node. We can reuse
1240   // the existing insert position since if we get here, we won't have
1241   // made any changes which would invalidate it.
1242   SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1243                                                  Op, Ty);
1244   UniqueSCEVs.InsertNode(S, IP);
1245   addToLoopUseLists(S);
1246   return S;
1247 }
1248 
1249 // Get the limit of a recurrence such that incrementing by Step cannot cause
1250 // signed overflow as long as the value of the recurrence within the
1251 // loop does not exceed this limit before incrementing.
1252 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1253                                                  ICmpInst::Predicate *Pred,
1254                                                  ScalarEvolution *SE) {
1255   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1256   if (SE->isKnownPositive(Step)) {
1257     *Pred = ICmpInst::ICMP_SLT;
1258     return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1259                            SE->getSignedRangeMax(Step));
1260   }
1261   if (SE->isKnownNegative(Step)) {
1262     *Pred = ICmpInst::ICMP_SGT;
1263     return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1264                            SE->getSignedRangeMin(Step));
1265   }
1266   return nullptr;
1267 }
1268 
1269 // Get the limit of a recurrence such that incrementing by Step cannot cause
1270 // unsigned overflow as long as the value of the recurrence within the loop does
1271 // not exceed this limit before incrementing.
1272 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1273                                                    ICmpInst::Predicate *Pred,
1274                                                    ScalarEvolution *SE) {
1275   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1276   *Pred = ICmpInst::ICMP_ULT;
1277 
1278   return SE->getConstant(APInt::getMinValue(BitWidth) -
1279                          SE->getUnsignedRangeMax(Step));
1280 }
1281 
1282 namespace {
1283 
1284 struct ExtendOpTraitsBase {
1285   typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *,
1286                                                           unsigned);
1287 };
1288 
1289 // Used to make code generic over signed and unsigned overflow.
1290 template <typename ExtendOp> struct ExtendOpTraits {
1291   // Members present:
1292   //
1293   // static const SCEV::NoWrapFlags WrapType;
1294   //
1295   // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1296   //
1297   // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1298   //                                           ICmpInst::Predicate *Pred,
1299   //                                           ScalarEvolution *SE);
1300 };
1301 
1302 template <>
1303 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1304   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1305 
1306   static const GetExtendExprTy GetExtendExpr;
1307 
1308   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1309                                              ICmpInst::Predicate *Pred,
1310                                              ScalarEvolution *SE) {
1311     return getSignedOverflowLimitForStep(Step, Pred, SE);
1312   }
1313 };
1314 
1315 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1316     SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr;
1317 
1318 template <>
1319 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1320   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1321 
1322   static const GetExtendExprTy GetExtendExpr;
1323 
1324   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1325                                              ICmpInst::Predicate *Pred,
1326                                              ScalarEvolution *SE) {
1327     return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1328   }
1329 };
1330 
1331 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1332     SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr;
1333 
1334 } // end anonymous namespace
1335 
1336 // The recurrence AR has been shown to have no signed/unsigned wrap or something
1337 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1338 // easily prove NSW/NUW for its preincrement or postincrement sibling. This
1339 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1340 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1341 // expression "Step + sext/zext(PreIncAR)" is congruent with
1342 // "sext/zext(PostIncAR)"
1343 template <typename ExtendOpTy>
1344 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1345                                         ScalarEvolution *SE, unsigned Depth) {
1346   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1347   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1348 
1349   const Loop *L = AR->getLoop();
1350   const SCEV *Start = AR->getStart();
1351   const SCEV *Step = AR->getStepRecurrence(*SE);
1352 
1353   // Check for a simple looking step prior to loop entry.
1354   const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1355   if (!SA)
1356     return nullptr;
1357 
1358   // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1359   // subtraction is expensive. For this purpose, perform a quick and dirty
1360   // difference, by checking for Step in the operand list.
1361   SmallVector<const SCEV *, 4> DiffOps;
1362   for (const SCEV *Op : SA->operands())
1363     if (Op != Step)
1364       DiffOps.push_back(Op);
1365 
1366   if (DiffOps.size() == SA->getNumOperands())
1367     return nullptr;
1368 
1369   // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1370   // `Step`:
1371 
1372   // 1. NSW/NUW flags on the step increment.
1373   auto PreStartFlags =
1374     ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
1375   const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1376   const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1377       SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1378 
1379   // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1380   // "S+X does not sign/unsign-overflow".
1381   //
1382 
1383   const SCEV *BECount = SE->getBackedgeTakenCount(L);
1384   if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1385       !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1386     return PreStart;
1387 
1388   // 2. Direct overflow check on the step operation's expression.
1389   unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1390   Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1391   const SCEV *OperandExtendedStart =
1392       SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
1393                      (SE->*GetExtendExpr)(Step, WideTy, Depth));
1394   if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
1395     if (PreAR && AR->getNoWrapFlags(WrapType)) {
1396       // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1397       // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1398       // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`.  Cache this fact.
1399       SE->setNoWrapFlags(const_cast<SCEVAddRecExpr *>(PreAR), WrapType);
1400     }
1401     return PreStart;
1402   }
1403 
1404   // 3. Loop precondition.
1405   ICmpInst::Predicate Pred;
1406   const SCEV *OverflowLimit =
1407       ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1408 
1409   if (OverflowLimit &&
1410       SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1411     return PreStart;
1412 
1413   return nullptr;
1414 }
1415 
1416 // Get the normalized zero or sign extended expression for this AddRec's Start.
1417 template <typename ExtendOpTy>
1418 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1419                                         ScalarEvolution *SE,
1420                                         unsigned Depth) {
1421   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1422 
1423   const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth);
1424   if (!PreStart)
1425     return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth);
1426 
1427   return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty,
1428                                              Depth),
1429                         (SE->*GetExtendExpr)(PreStart, Ty, Depth));
1430 }
1431 
1432 // Try to prove away overflow by looking at "nearby" add recurrences.  A
1433 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1434 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1435 //
1436 // Formally:
1437 //
1438 //     {S,+,X} == {S-T,+,X} + T
1439 //  => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1440 //
1441 // If ({S-T,+,X} + T) does not overflow  ... (1)
1442 //
1443 //  RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1444 //
1445 // If {S-T,+,X} does not overflow  ... (2)
1446 //
1447 //  RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1448 //      == {Ext(S-T)+Ext(T),+,Ext(X)}
1449 //
1450 // If (S-T)+T does not overflow  ... (3)
1451 //
1452 //  RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1453 //      == {Ext(S),+,Ext(X)} == LHS
1454 //
1455 // Thus, if (1), (2) and (3) are true for some T, then
1456 //   Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1457 //
1458 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1459 // does not overflow" restricted to the 0th iteration.  Therefore we only need
1460 // to check for (1) and (2).
1461 //
1462 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1463 // is `Delta` (defined below).
1464 template <typename ExtendOpTy>
1465 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1466                                                 const SCEV *Step,
1467                                                 const Loop *L) {
1468   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1469 
1470   // We restrict `Start` to a constant to prevent SCEV from spending too much
1471   // time here.  It is correct (but more expensive) to continue with a
1472   // non-constant `Start` and do a general SCEV subtraction to compute
1473   // `PreStart` below.
1474   const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1475   if (!StartC)
1476     return false;
1477 
1478   APInt StartAI = StartC->getAPInt();
1479 
1480   for (unsigned Delta : {-2, -1, 1, 2}) {
1481     const SCEV *PreStart = getConstant(StartAI - Delta);
1482 
1483     FoldingSetNodeID ID;
1484     ID.AddInteger(scAddRecExpr);
1485     ID.AddPointer(PreStart);
1486     ID.AddPointer(Step);
1487     ID.AddPointer(L);
1488     void *IP = nullptr;
1489     const auto *PreAR =
1490       static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1491 
1492     // Give up if we don't already have the add recurrence we need because
1493     // actually constructing an add recurrence is relatively expensive.
1494     if (PreAR && PreAR->getNoWrapFlags(WrapType)) {  // proves (2)
1495       const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1496       ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1497       const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1498           DeltaS, &Pred, this);
1499       if (Limit && isKnownPredicate(Pred, PreAR, Limit))  // proves (1)
1500         return true;
1501     }
1502   }
1503 
1504   return false;
1505 }
1506 
1507 // Finds an integer D for an expression (C + x + y + ...) such that the top
1508 // level addition in (D + (C - D + x + y + ...)) would not wrap (signed or
1509 // unsigned) and the number of trailing zeros of (C - D + x + y + ...) is
1510 // maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and
1511 // the (C + x + y + ...) expression is \p WholeAddExpr.
1512 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE,
1513                                             const SCEVConstant *ConstantTerm,
1514                                             const SCEVAddExpr *WholeAddExpr) {
1515   const APInt &C = ConstantTerm->getAPInt();
1516   const unsigned BitWidth = C.getBitWidth();
1517   // Find number of trailing zeros of (x + y + ...) w/o the C first:
1518   uint32_t TZ = BitWidth;
1519   for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I)
1520     TZ = std::min(TZ, SE.GetMinTrailingZeros(WholeAddExpr->getOperand(I)));
1521   if (TZ) {
1522     // Set D to be as many least significant bits of C as possible while still
1523     // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap:
1524     return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C;
1525   }
1526   return APInt(BitWidth, 0);
1527 }
1528 
1529 // Finds an integer D for an affine AddRec expression {C,+,x} such that the top
1530 // level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the
1531 // number of trailing zeros of (C - D + x * n) is maximized, where C is the \p
1532 // ConstantStart, x is an arbitrary \p Step, and n is the loop trip count.
1533 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE,
1534                                             const APInt &ConstantStart,
1535                                             const SCEV *Step) {
1536   const unsigned BitWidth = ConstantStart.getBitWidth();
1537   const uint32_t TZ = SE.GetMinTrailingZeros(Step);
1538   if (TZ)
1539     return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth)
1540                          : ConstantStart;
1541   return APInt(BitWidth, 0);
1542 }
1543 
1544 const SCEV *
1545 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1546   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1547          "This is not an extending conversion!");
1548   assert(isSCEVable(Ty) &&
1549          "This is not a conversion to a SCEVable type!");
1550   Ty = getEffectiveSCEVType(Ty);
1551 
1552   // Fold if the operand is constant.
1553   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1554     return getConstant(
1555       cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
1556 
1557   // zext(zext(x)) --> zext(x)
1558   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1559     return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1560 
1561   // Before doing any expensive analysis, check to see if we've already
1562   // computed a SCEV for this Op and Ty.
1563   FoldingSetNodeID ID;
1564   ID.AddInteger(scZeroExtend);
1565   ID.AddPointer(Op);
1566   ID.AddPointer(Ty);
1567   void *IP = nullptr;
1568   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1569   if (Depth > MaxCastDepth) {
1570     SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1571                                                      Op, Ty);
1572     UniqueSCEVs.InsertNode(S, IP);
1573     addToLoopUseLists(S);
1574     return S;
1575   }
1576 
1577   // zext(trunc(x)) --> zext(x) or x or trunc(x)
1578   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1579     // It's possible the bits taken off by the truncate were all zero bits. If
1580     // so, we should be able to simplify this further.
1581     const SCEV *X = ST->getOperand();
1582     ConstantRange CR = getUnsignedRange(X);
1583     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1584     unsigned NewBits = getTypeSizeInBits(Ty);
1585     if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1586             CR.zextOrTrunc(NewBits)))
1587       return getTruncateOrZeroExtend(X, Ty, Depth);
1588   }
1589 
1590   // If the input value is a chrec scev, and we can prove that the value
1591   // did not overflow the old, smaller, value, we can zero extend all of the
1592   // operands (often constants).  This allows analysis of something like
1593   // this:  for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1594   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1595     if (AR->isAffine()) {
1596       const SCEV *Start = AR->getStart();
1597       const SCEV *Step = AR->getStepRecurrence(*this);
1598       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1599       const Loop *L = AR->getLoop();
1600 
1601       if (!AR->hasNoUnsignedWrap()) {
1602         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1603         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1604       }
1605 
1606       // If we have special knowledge that this addrec won't overflow,
1607       // we don't need to do any further analysis.
1608       if (AR->hasNoUnsignedWrap())
1609         return getAddRecExpr(
1610             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1611             getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1612 
1613       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1614       // Note that this serves two purposes: It filters out loops that are
1615       // simply not analyzable, and it covers the case where this code is
1616       // being called from within backedge-taken count analysis, such that
1617       // attempting to ask for the backedge-taken count would likely result
1618       // in infinite recursion. In the later case, the analysis code will
1619       // cope with a conservative value, and it will take care to purge
1620       // that value once it has finished.
1621       const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
1622       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1623         // Manually compute the final value for AR, checking for overflow.
1624 
1625         // Check whether the backedge-taken count can be losslessly casted to
1626         // the addrec's type. The count is always unsigned.
1627         const SCEV *CastedMaxBECount =
1628             getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
1629         const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
1630             CastedMaxBECount, MaxBECount->getType(), Depth);
1631         if (MaxBECount == RecastedMaxBECount) {
1632           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1633           // Check whether Start+Step*MaxBECount has no unsigned overflow.
1634           const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step,
1635                                         SCEV::FlagAnyWrap, Depth + 1);
1636           const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul,
1637                                                           SCEV::FlagAnyWrap,
1638                                                           Depth + 1),
1639                                                WideTy, Depth + 1);
1640           const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
1641           const SCEV *WideMaxBECount =
1642             getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1643           const SCEV *OperandExtendedAdd =
1644             getAddExpr(WideStart,
1645                        getMulExpr(WideMaxBECount,
1646                                   getZeroExtendExpr(Step, WideTy, Depth + 1),
1647                                   SCEV::FlagAnyWrap, Depth + 1),
1648                        SCEV::FlagAnyWrap, Depth + 1);
1649           if (ZAdd == OperandExtendedAdd) {
1650             // Cache knowledge of AR NUW, which is propagated to this AddRec.
1651             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1652             // Return the expression with the addrec on the outside.
1653             return getAddRecExpr(
1654                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1655                                                          Depth + 1),
1656                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1657                 AR->getNoWrapFlags());
1658           }
1659           // Similar to above, only this time treat the step value as signed.
1660           // This covers loops that count down.
1661           OperandExtendedAdd =
1662             getAddExpr(WideStart,
1663                        getMulExpr(WideMaxBECount,
1664                                   getSignExtendExpr(Step, WideTy, Depth + 1),
1665                                   SCEV::FlagAnyWrap, Depth + 1),
1666                        SCEV::FlagAnyWrap, Depth + 1);
1667           if (ZAdd == OperandExtendedAdd) {
1668             // Cache knowledge of AR NW, which is propagated to this AddRec.
1669             // Negative step causes unsigned wrap, but it still can't self-wrap.
1670             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1671             // Return the expression with the addrec on the outside.
1672             return getAddRecExpr(
1673                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1674                                                          Depth + 1),
1675                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1676                 AR->getNoWrapFlags());
1677           }
1678         }
1679       }
1680 
1681       // Normally, in the cases we can prove no-overflow via a
1682       // backedge guarding condition, we can also compute a backedge
1683       // taken count for the loop.  The exceptions are assumptions and
1684       // guards present in the loop -- SCEV is not great at exploiting
1685       // these to compute max backedge taken counts, but can still use
1686       // these to prove lack of overflow.  Use this fact to avoid
1687       // doing extra work that may not pay off.
1688       if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1689           !AC.assumptions().empty()) {
1690 
1691         auto NewFlags = proveNoUnsignedWrapViaInduction(AR);
1692         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1693         if (AR->hasNoUnsignedWrap()) {
1694           // Same as nuw case above - duplicated here to avoid a compile time
1695           // issue.  It's not clear that the order of checks does matter, but
1696           // it's one of two issue possible causes for a change which was
1697           // reverted.  Be conservative for the moment.
1698           return getAddRecExpr(
1699                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1700                                                          Depth + 1),
1701                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1702                 AR->getNoWrapFlags());
1703         }
1704 
1705         // For a negative step, we can extend the operands iff doing so only
1706         // traverses values in the range zext([0,UINT_MAX]).
1707         if (isKnownNegative(Step)) {
1708           const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1709                                       getSignedRangeMin(Step));
1710           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1711               isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) {
1712             // Cache knowledge of AR NW, which is propagated to this
1713             // AddRec.  Negative step causes unsigned wrap, but it
1714             // still can't self-wrap.
1715             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1716             // Return the expression with the addrec on the outside.
1717             return getAddRecExpr(
1718                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1719                                                          Depth + 1),
1720                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1721                 AR->getNoWrapFlags());
1722           }
1723         }
1724       }
1725 
1726       // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw>
1727       // if D + (C - D + Step * n) could be proven to not unsigned wrap
1728       // where D maximizes the number of trailing zeros of (C - D + Step * n)
1729       if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
1730         const APInt &C = SC->getAPInt();
1731         const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
1732         if (D != 0) {
1733           const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1734           const SCEV *SResidual =
1735               getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
1736           const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1737           return getAddExpr(SZExtD, SZExtR,
1738                             (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1739                             Depth + 1);
1740         }
1741       }
1742 
1743       if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1744         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1745         return getAddRecExpr(
1746             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1747             getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1748       }
1749     }
1750 
1751   // zext(A % B) --> zext(A) % zext(B)
1752   {
1753     const SCEV *LHS;
1754     const SCEV *RHS;
1755     if (matchURem(Op, LHS, RHS))
1756       return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1),
1757                          getZeroExtendExpr(RHS, Ty, Depth + 1));
1758   }
1759 
1760   // zext(A / B) --> zext(A) / zext(B).
1761   if (auto *Div = dyn_cast<SCEVUDivExpr>(Op))
1762     return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1),
1763                        getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1));
1764 
1765   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1766     // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1767     if (SA->hasNoUnsignedWrap()) {
1768       // If the addition does not unsign overflow then we can, by definition,
1769       // commute the zero extension with the addition operation.
1770       SmallVector<const SCEV *, 4> Ops;
1771       for (const auto *Op : SA->operands())
1772         Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1773       return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1);
1774     }
1775 
1776     // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...))
1777     // if D + (C - D + x + y + ...) could be proven to not unsigned wrap
1778     // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1779     //
1780     // Often address arithmetics contain expressions like
1781     // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))).
1782     // This transformation is useful while proving that such expressions are
1783     // equal or differ by a small constant amount, see LoadStoreVectorizer pass.
1784     if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1785       const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1786       if (D != 0) {
1787         const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1788         const SCEV *SResidual =
1789             getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth);
1790         const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1791         return getAddExpr(SZExtD, SZExtR,
1792                           (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1793                           Depth + 1);
1794       }
1795     }
1796   }
1797 
1798   if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) {
1799     // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw>
1800     if (SM->hasNoUnsignedWrap()) {
1801       // If the multiply does not unsign overflow then we can, by definition,
1802       // commute the zero extension with the multiply operation.
1803       SmallVector<const SCEV *, 4> Ops;
1804       for (const auto *Op : SM->operands())
1805         Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1806       return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1);
1807     }
1808 
1809     // zext(2^K * (trunc X to iN)) to iM ->
1810     // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw>
1811     //
1812     // Proof:
1813     //
1814     //     zext(2^K * (trunc X to iN)) to iM
1815     //   = zext((trunc X to iN) << K) to iM
1816     //   = zext((trunc X to i{N-K}) << K)<nuw> to iM
1817     //     (because shl removes the top K bits)
1818     //   = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM
1819     //   = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>.
1820     //
1821     if (SM->getNumOperands() == 2)
1822       if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0)))
1823         if (MulLHS->getAPInt().isPowerOf2())
1824           if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) {
1825             int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) -
1826                                MulLHS->getAPInt().logBase2();
1827             Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits);
1828             return getMulExpr(
1829                 getZeroExtendExpr(MulLHS, Ty),
1830                 getZeroExtendExpr(
1831                     getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty),
1832                 SCEV::FlagNUW, Depth + 1);
1833           }
1834   }
1835 
1836   // The cast wasn't folded; create an explicit cast node.
1837   // Recompute the insert position, as it may have been invalidated.
1838   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1839   SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1840                                                    Op, Ty);
1841   UniqueSCEVs.InsertNode(S, IP);
1842   addToLoopUseLists(S);
1843   return S;
1844 }
1845 
1846 const SCEV *
1847 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1848   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1849          "This is not an extending conversion!");
1850   assert(isSCEVable(Ty) &&
1851          "This is not a conversion to a SCEVable type!");
1852   Ty = getEffectiveSCEVType(Ty);
1853 
1854   // Fold if the operand is constant.
1855   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1856     return getConstant(
1857       cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
1858 
1859   // sext(sext(x)) --> sext(x)
1860   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1861     return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1);
1862 
1863   // sext(zext(x)) --> zext(x)
1864   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1865     return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1866 
1867   // Before doing any expensive analysis, check to see if we've already
1868   // computed a SCEV for this Op and Ty.
1869   FoldingSetNodeID ID;
1870   ID.AddInteger(scSignExtend);
1871   ID.AddPointer(Op);
1872   ID.AddPointer(Ty);
1873   void *IP = nullptr;
1874   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1875   // Limit recursion depth.
1876   if (Depth > MaxCastDepth) {
1877     SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1878                                                      Op, Ty);
1879     UniqueSCEVs.InsertNode(S, IP);
1880     addToLoopUseLists(S);
1881     return S;
1882   }
1883 
1884   // sext(trunc(x)) --> sext(x) or x or trunc(x)
1885   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1886     // It's possible the bits taken off by the truncate were all sign bits. If
1887     // so, we should be able to simplify this further.
1888     const SCEV *X = ST->getOperand();
1889     ConstantRange CR = getSignedRange(X);
1890     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1891     unsigned NewBits = getTypeSizeInBits(Ty);
1892     if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1893             CR.sextOrTrunc(NewBits)))
1894       return getTruncateOrSignExtend(X, Ty, Depth);
1895   }
1896 
1897   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1898     // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1899     if (SA->hasNoSignedWrap()) {
1900       // If the addition does not sign overflow then we can, by definition,
1901       // commute the sign extension with the addition operation.
1902       SmallVector<const SCEV *, 4> Ops;
1903       for (const auto *Op : SA->operands())
1904         Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1));
1905       return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1);
1906     }
1907 
1908     // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...))
1909     // if D + (C - D + x + y + ...) could be proven to not signed wrap
1910     // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1911     //
1912     // For instance, this will bring two seemingly different expressions:
1913     //     1 + sext(5 + 20 * %x + 24 * %y)  and
1914     //         sext(6 + 20 * %x + 24 * %y)
1915     // to the same form:
1916     //     2 + sext(4 + 20 * %x + 24 * %y)
1917     if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1918       const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1919       if (D != 0) {
1920         const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
1921         const SCEV *SResidual =
1922             getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth);
1923         const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
1924         return getAddExpr(SSExtD, SSExtR,
1925                           (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1926                           Depth + 1);
1927       }
1928     }
1929   }
1930   // If the input value is a chrec scev, and we can prove that the value
1931   // did not overflow the old, smaller, value, we can sign extend all of the
1932   // operands (often constants).  This allows analysis of something like
1933   // this:  for (signed char X = 0; X < 100; ++X) { int Y = X; }
1934   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1935     if (AR->isAffine()) {
1936       const SCEV *Start = AR->getStart();
1937       const SCEV *Step = AR->getStepRecurrence(*this);
1938       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1939       const Loop *L = AR->getLoop();
1940 
1941       if (!AR->hasNoSignedWrap()) {
1942         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1943         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1944       }
1945 
1946       // If we have special knowledge that this addrec won't overflow,
1947       // we don't need to do any further analysis.
1948       if (AR->hasNoSignedWrap())
1949         return getAddRecExpr(
1950             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
1951             getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW);
1952 
1953       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1954       // Note that this serves two purposes: It filters out loops that are
1955       // simply not analyzable, and it covers the case where this code is
1956       // being called from within backedge-taken count analysis, such that
1957       // attempting to ask for the backedge-taken count would likely result
1958       // in infinite recursion. In the later case, the analysis code will
1959       // cope with a conservative value, and it will take care to purge
1960       // that value once it has finished.
1961       const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
1962       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1963         // Manually compute the final value for AR, checking for
1964         // overflow.
1965 
1966         // Check whether the backedge-taken count can be losslessly casted to
1967         // the addrec's type. The count is always unsigned.
1968         const SCEV *CastedMaxBECount =
1969             getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
1970         const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
1971             CastedMaxBECount, MaxBECount->getType(), Depth);
1972         if (MaxBECount == RecastedMaxBECount) {
1973           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1974           // Check whether Start+Step*MaxBECount has no signed overflow.
1975           const SCEV *SMul = getMulExpr(CastedMaxBECount, Step,
1976                                         SCEV::FlagAnyWrap, Depth + 1);
1977           const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul,
1978                                                           SCEV::FlagAnyWrap,
1979                                                           Depth + 1),
1980                                                WideTy, Depth + 1);
1981           const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
1982           const SCEV *WideMaxBECount =
1983             getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1984           const SCEV *OperandExtendedAdd =
1985             getAddExpr(WideStart,
1986                        getMulExpr(WideMaxBECount,
1987                                   getSignExtendExpr(Step, WideTy, Depth + 1),
1988                                   SCEV::FlagAnyWrap, Depth + 1),
1989                        SCEV::FlagAnyWrap, Depth + 1);
1990           if (SAdd == OperandExtendedAdd) {
1991             // Cache knowledge of AR NSW, which is propagated to this AddRec.
1992             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
1993             // Return the expression with the addrec on the outside.
1994             return getAddRecExpr(
1995                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
1996                                                          Depth + 1),
1997                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1998                 AR->getNoWrapFlags());
1999           }
2000           // Similar to above, only this time treat the step value as unsigned.
2001           // This covers loops that count up with an unsigned step.
2002           OperandExtendedAdd =
2003             getAddExpr(WideStart,
2004                        getMulExpr(WideMaxBECount,
2005                                   getZeroExtendExpr(Step, WideTy, Depth + 1),
2006                                   SCEV::FlagAnyWrap, Depth + 1),
2007                        SCEV::FlagAnyWrap, Depth + 1);
2008           if (SAdd == OperandExtendedAdd) {
2009             // If AR wraps around then
2010             //
2011             //    abs(Step) * MaxBECount > unsigned-max(AR->getType())
2012             // => SAdd != OperandExtendedAdd
2013             //
2014             // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
2015             // (SAdd == OperandExtendedAdd => AR is NW)
2016 
2017             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
2018 
2019             // Return the expression with the addrec on the outside.
2020             return getAddRecExpr(
2021                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
2022                                                          Depth + 1),
2023                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
2024                 AR->getNoWrapFlags());
2025           }
2026         }
2027       }
2028 
2029       auto NewFlags = proveNoSignedWrapViaInduction(AR);
2030       setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
2031       if (AR->hasNoSignedWrap()) {
2032         // Same as nsw case above - duplicated here to avoid a compile time
2033         // issue.  It's not clear that the order of checks does matter, but
2034         // it's one of two issue possible causes for a change which was
2035         // reverted.  Be conservative for the moment.
2036         return getAddRecExpr(
2037             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2038             getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2039       }
2040 
2041       // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw>
2042       // if D + (C - D + Step * n) could be proven to not signed wrap
2043       // where D maximizes the number of trailing zeros of (C - D + Step * n)
2044       if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
2045         const APInt &C = SC->getAPInt();
2046         const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
2047         if (D != 0) {
2048           const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
2049           const SCEV *SResidual =
2050               getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
2051           const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
2052           return getAddExpr(SSExtD, SSExtR,
2053                             (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
2054                             Depth + 1);
2055         }
2056       }
2057 
2058       if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
2059         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2060         return getAddRecExpr(
2061             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2062             getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2063       }
2064     }
2065 
2066   // If the input value is provably positive and we could not simplify
2067   // away the sext build a zext instead.
2068   if (isKnownNonNegative(Op))
2069     return getZeroExtendExpr(Op, Ty, Depth + 1);
2070 
2071   // The cast wasn't folded; create an explicit cast node.
2072   // Recompute the insert position, as it may have been invalidated.
2073   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2074   SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
2075                                                    Op, Ty);
2076   UniqueSCEVs.InsertNode(S, IP);
2077   addToLoopUseLists(S);
2078   return S;
2079 }
2080 
2081 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
2082 /// unspecified bits out to the given type.
2083 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
2084                                               Type *Ty) {
2085   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
2086          "This is not an extending conversion!");
2087   assert(isSCEVable(Ty) &&
2088          "This is not a conversion to a SCEVable type!");
2089   Ty = getEffectiveSCEVType(Ty);
2090 
2091   // Sign-extend negative constants.
2092   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
2093     if (SC->getAPInt().isNegative())
2094       return getSignExtendExpr(Op, Ty);
2095 
2096   // Peel off a truncate cast.
2097   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
2098     const SCEV *NewOp = T->getOperand();
2099     if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
2100       return getAnyExtendExpr(NewOp, Ty);
2101     return getTruncateOrNoop(NewOp, Ty);
2102   }
2103 
2104   // Next try a zext cast. If the cast is folded, use it.
2105   const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2106   if (!isa<SCEVZeroExtendExpr>(ZExt))
2107     return ZExt;
2108 
2109   // Next try a sext cast. If the cast is folded, use it.
2110   const SCEV *SExt = getSignExtendExpr(Op, Ty);
2111   if (!isa<SCEVSignExtendExpr>(SExt))
2112     return SExt;
2113 
2114   // Force the cast to be folded into the operands of an addrec.
2115   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2116     SmallVector<const SCEV *, 4> Ops;
2117     for (const SCEV *Op : AR->operands())
2118       Ops.push_back(getAnyExtendExpr(Op, Ty));
2119     return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2120   }
2121 
2122   // If the expression is obviously signed, use the sext cast value.
2123   if (isa<SCEVSMaxExpr>(Op))
2124     return SExt;
2125 
2126   // Absent any other information, use the zext cast value.
2127   return ZExt;
2128 }
2129 
2130 /// Process the given Ops list, which is a list of operands to be added under
2131 /// the given scale, update the given map. This is a helper function for
2132 /// getAddRecExpr. As an example of what it does, given a sequence of operands
2133 /// that would form an add expression like this:
2134 ///
2135 ///    m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2136 ///
2137 /// where A and B are constants, update the map with these values:
2138 ///
2139 ///    (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2140 ///
2141 /// and add 13 + A*B*29 to AccumulatedConstant.
2142 /// This will allow getAddRecExpr to produce this:
2143 ///
2144 ///    13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2145 ///
2146 /// This form often exposes folding opportunities that are hidden in
2147 /// the original operand list.
2148 ///
2149 /// Return true iff it appears that any interesting folding opportunities
2150 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
2151 /// the common case where no interesting opportunities are present, and
2152 /// is also used as a check to avoid infinite recursion.
2153 static bool
2154 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
2155                              SmallVectorImpl<const SCEV *> &NewOps,
2156                              APInt &AccumulatedConstant,
2157                              const SCEV *const *Ops, size_t NumOperands,
2158                              const APInt &Scale,
2159                              ScalarEvolution &SE) {
2160   bool Interesting = false;
2161 
2162   // Iterate over the add operands. They are sorted, with constants first.
2163   unsigned i = 0;
2164   while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2165     ++i;
2166     // Pull a buried constant out to the outside.
2167     if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2168       Interesting = true;
2169     AccumulatedConstant += Scale * C->getAPInt();
2170   }
2171 
2172   // Next comes everything else. We're especially interested in multiplies
2173   // here, but they're in the middle, so just visit the rest with one loop.
2174   for (; i != NumOperands; ++i) {
2175     const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
2176     if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2177       APInt NewScale =
2178           Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2179       if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2180         // A multiplication of a constant with another add; recurse.
2181         const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2182         Interesting |=
2183           CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2184                                        Add->op_begin(), Add->getNumOperands(),
2185                                        NewScale, SE);
2186       } else {
2187         // A multiplication of a constant with some other value. Update
2188         // the map.
2189         SmallVector<const SCEV *, 4> MulOps(drop_begin(Mul->operands()));
2190         const SCEV *Key = SE.getMulExpr(MulOps);
2191         auto Pair = M.insert({Key, NewScale});
2192         if (Pair.second) {
2193           NewOps.push_back(Pair.first->first);
2194         } else {
2195           Pair.first->second += NewScale;
2196           // The map already had an entry for this value, which may indicate
2197           // a folding opportunity.
2198           Interesting = true;
2199         }
2200       }
2201     } else {
2202       // An ordinary operand. Update the map.
2203       std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
2204           M.insert({Ops[i], Scale});
2205       if (Pair.second) {
2206         NewOps.push_back(Pair.first->first);
2207       } else {
2208         Pair.first->second += Scale;
2209         // The map already had an entry for this value, which may indicate
2210         // a folding opportunity.
2211         Interesting = true;
2212       }
2213     }
2214   }
2215 
2216   return Interesting;
2217 }
2218 
2219 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2220 // `OldFlags' as can't-wrap behavior.  Infer a more aggressive set of
2221 // can't-overflow flags for the operation if possible.
2222 static SCEV::NoWrapFlags
2223 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
2224                       const ArrayRef<const SCEV *> Ops,
2225                       SCEV::NoWrapFlags Flags) {
2226   using namespace std::placeholders;
2227 
2228   using OBO = OverflowingBinaryOperator;
2229 
2230   bool CanAnalyze =
2231       Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
2232   (void)CanAnalyze;
2233   assert(CanAnalyze && "don't call from other places!");
2234 
2235   int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2236   SCEV::NoWrapFlags SignOrUnsignWrap =
2237       ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2238 
2239   // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2240   auto IsKnownNonNegative = [&](const SCEV *S) {
2241     return SE->isKnownNonNegative(S);
2242   };
2243 
2244   if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2245     Flags =
2246         ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
2247 
2248   SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2249 
2250   if (SignOrUnsignWrap != SignOrUnsignMask &&
2251       (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 &&
2252       isa<SCEVConstant>(Ops[0])) {
2253 
2254     auto Opcode = [&] {
2255       switch (Type) {
2256       case scAddExpr:
2257         return Instruction::Add;
2258       case scMulExpr:
2259         return Instruction::Mul;
2260       default:
2261         llvm_unreachable("Unexpected SCEV op.");
2262       }
2263     }();
2264 
2265     const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2266 
2267     // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow.
2268     if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2269       auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2270           Opcode, C, OBO::NoSignedWrap);
2271       if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2272         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2273     }
2274 
2275     // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow.
2276     if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2277       auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2278           Opcode, C, OBO::NoUnsignedWrap);
2279       if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2280         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2281     }
2282   }
2283 
2284   return Flags;
2285 }
2286 
2287 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) {
2288   return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader());
2289 }
2290 
2291 /// Get a canonical add expression, or something simpler if possible.
2292 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2293                                         SCEV::NoWrapFlags OrigFlags,
2294                                         unsigned Depth) {
2295   assert(!(OrigFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2296          "only nuw or nsw allowed");
2297   assert(!Ops.empty() && "Cannot get empty add!");
2298   if (Ops.size() == 1) return Ops[0];
2299 #ifndef NDEBUG
2300   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2301   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2302     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2303            "SCEVAddExpr operand types don't match!");
2304 #endif
2305 
2306   // Sort by complexity, this groups all similar expression types together.
2307   GroupByComplexity(Ops, &LI, DT);
2308 
2309   // If there are any constants, fold them together.
2310   unsigned Idx = 0;
2311   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2312     ++Idx;
2313     assert(Idx < Ops.size());
2314     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2315       // We found two constants, fold them together!
2316       Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
2317       if (Ops.size() == 2) return Ops[0];
2318       Ops.erase(Ops.begin()+1);  // Erase the folded element
2319       LHSC = cast<SCEVConstant>(Ops[0]);
2320     }
2321 
2322     // If we are left with a constant zero being added, strip it off.
2323     if (LHSC->getValue()->isZero()) {
2324       Ops.erase(Ops.begin());
2325       --Idx;
2326     }
2327 
2328     if (Ops.size() == 1) return Ops[0];
2329   }
2330 
2331   // Delay expensive flag strengthening until necessary.
2332   auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) {
2333     return StrengthenNoWrapFlags(this, scAddExpr, Ops, OrigFlags);
2334   };
2335 
2336   // Limit recursion calls depth.
2337   if (Depth > MaxArithDepth || hasHugeExpression(Ops))
2338     return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
2339 
2340   if (SCEV *S = std::get<0>(findExistingSCEVInCache(scAddExpr, Ops))) {
2341     // Don't strengthen flags if we have no new information.
2342     SCEVAddExpr *Add = static_cast<SCEVAddExpr *>(S);
2343     if (Add->getNoWrapFlags(OrigFlags) != OrigFlags)
2344       Add->setNoWrapFlags(ComputeFlags(Ops));
2345     return S;
2346   }
2347 
2348   // Okay, check to see if the same value occurs in the operand list more than
2349   // once.  If so, merge them together into an multiply expression.  Since we
2350   // sorted the list, these values are required to be adjacent.
2351   Type *Ty = Ops[0]->getType();
2352   bool FoundMatch = false;
2353   for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2354     if (Ops[i] == Ops[i+1]) {      //  X + Y + Y  -->  X + Y*2
2355       // Scan ahead to count how many equal operands there are.
2356       unsigned Count = 2;
2357       while (i+Count != e && Ops[i+Count] == Ops[i])
2358         ++Count;
2359       // Merge the values into a multiply.
2360       const SCEV *Scale = getConstant(Ty, Count);
2361       const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1);
2362       if (Ops.size() == Count)
2363         return Mul;
2364       Ops[i] = Mul;
2365       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2366       --i; e -= Count - 1;
2367       FoundMatch = true;
2368     }
2369   if (FoundMatch)
2370     return getAddExpr(Ops, OrigFlags, Depth + 1);
2371 
2372   // Check for truncates. If all the operands are truncated from the same
2373   // type, see if factoring out the truncate would permit the result to be
2374   // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
2375   // if the contents of the resulting outer trunc fold to something simple.
2376   auto FindTruncSrcType = [&]() -> Type * {
2377     // We're ultimately looking to fold an addrec of truncs and muls of only
2378     // constants and truncs, so if we find any other types of SCEV
2379     // as operands of the addrec then we bail and return nullptr here.
2380     // Otherwise, we return the type of the operand of a trunc that we find.
2381     if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx]))
2382       return T->getOperand()->getType();
2383     if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2384       const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1);
2385       if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp))
2386         return T->getOperand()->getType();
2387     }
2388     return nullptr;
2389   };
2390   if (auto *SrcType = FindTruncSrcType()) {
2391     SmallVector<const SCEV *, 8> LargeOps;
2392     bool Ok = true;
2393     // Check all the operands to see if they can be represented in the
2394     // source type of the truncate.
2395     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2396       if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2397         if (T->getOperand()->getType() != SrcType) {
2398           Ok = false;
2399           break;
2400         }
2401         LargeOps.push_back(T->getOperand());
2402       } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2403         LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2404       } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
2405         SmallVector<const SCEV *, 8> LargeMulOps;
2406         for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2407           if (const SCEVTruncateExpr *T =
2408                 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2409             if (T->getOperand()->getType() != SrcType) {
2410               Ok = false;
2411               break;
2412             }
2413             LargeMulOps.push_back(T->getOperand());
2414           } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2415             LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2416           } else {
2417             Ok = false;
2418             break;
2419           }
2420         }
2421         if (Ok)
2422           LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1));
2423       } else {
2424         Ok = false;
2425         break;
2426       }
2427     }
2428     if (Ok) {
2429       // Evaluate the expression in the larger type.
2430       const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1);
2431       // If it folds to something simple, use it. Otherwise, don't.
2432       if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2433         return getTruncateExpr(Fold, Ty);
2434     }
2435   }
2436 
2437   // Skip past any other cast SCEVs.
2438   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2439     ++Idx;
2440 
2441   // If there are add operands they would be next.
2442   if (Idx < Ops.size()) {
2443     bool DeletedAdd = false;
2444     while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2445       if (Ops.size() > AddOpsInlineThreshold ||
2446           Add->getNumOperands() > AddOpsInlineThreshold)
2447         break;
2448       // If we have an add, expand the add operands onto the end of the operands
2449       // list.
2450       Ops.erase(Ops.begin()+Idx);
2451       Ops.append(Add->op_begin(), Add->op_end());
2452       DeletedAdd = true;
2453     }
2454 
2455     // If we deleted at least one add, we added operands to the end of the list,
2456     // and they are not necessarily sorted.  Recurse to resort and resimplify
2457     // any operands we just acquired.
2458     if (DeletedAdd)
2459       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2460   }
2461 
2462   // Skip over the add expression until we get to a multiply.
2463   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2464     ++Idx;
2465 
2466   // Check to see if there are any folding opportunities present with
2467   // operands multiplied by constant values.
2468   if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2469     uint64_t BitWidth = getTypeSizeInBits(Ty);
2470     DenseMap<const SCEV *, APInt> M;
2471     SmallVector<const SCEV *, 8> NewOps;
2472     APInt AccumulatedConstant(BitWidth, 0);
2473     if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2474                                      Ops.data(), Ops.size(),
2475                                      APInt(BitWidth, 1), *this)) {
2476       struct APIntCompare {
2477         bool operator()(const APInt &LHS, const APInt &RHS) const {
2478           return LHS.ult(RHS);
2479         }
2480       };
2481 
2482       // Some interesting folding opportunity is present, so its worthwhile to
2483       // re-generate the operands list. Group the operands by constant scale,
2484       // to avoid multiplying by the same constant scale multiple times.
2485       std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
2486       for (const SCEV *NewOp : NewOps)
2487         MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2488       // Re-generate the operands list.
2489       Ops.clear();
2490       if (AccumulatedConstant != 0)
2491         Ops.push_back(getConstant(AccumulatedConstant));
2492       for (auto &MulOp : MulOpLists)
2493         if (MulOp.first != 0)
2494           Ops.push_back(getMulExpr(
2495               getConstant(MulOp.first),
2496               getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1),
2497               SCEV::FlagAnyWrap, Depth + 1));
2498       if (Ops.empty())
2499         return getZero(Ty);
2500       if (Ops.size() == 1)
2501         return Ops[0];
2502       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2503     }
2504   }
2505 
2506   // If we are adding something to a multiply expression, make sure the
2507   // something is not already an operand of the multiply.  If so, merge it into
2508   // the multiply.
2509   for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2510     const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2511     for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2512       const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2513       if (isa<SCEVConstant>(MulOpSCEV))
2514         continue;
2515       for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
2516         if (MulOpSCEV == Ops[AddOp]) {
2517           // Fold W + X + (X * Y * Z)  -->  W + (X * ((Y*Z)+1))
2518           const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
2519           if (Mul->getNumOperands() != 2) {
2520             // If the multiply has more than two operands, we must get the
2521             // Y*Z term.
2522             SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2523                                                 Mul->op_begin()+MulOp);
2524             MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2525             InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2526           }
2527           SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul};
2528           const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2529           const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV,
2530                                             SCEV::FlagAnyWrap, Depth + 1);
2531           if (Ops.size() == 2) return OuterMul;
2532           if (AddOp < Idx) {
2533             Ops.erase(Ops.begin()+AddOp);
2534             Ops.erase(Ops.begin()+Idx-1);
2535           } else {
2536             Ops.erase(Ops.begin()+Idx);
2537             Ops.erase(Ops.begin()+AddOp-1);
2538           }
2539           Ops.push_back(OuterMul);
2540           return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2541         }
2542 
2543       // Check this multiply against other multiplies being added together.
2544       for (unsigned OtherMulIdx = Idx+1;
2545            OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2546            ++OtherMulIdx) {
2547         const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
2548         // If MulOp occurs in OtherMul, we can fold the two multiplies
2549         // together.
2550         for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2551              OMulOp != e; ++OMulOp)
2552           if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2553             // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
2554             const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
2555             if (Mul->getNumOperands() != 2) {
2556               SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2557                                                   Mul->op_begin()+MulOp);
2558               MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2559               InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2560             }
2561             const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
2562             if (OtherMul->getNumOperands() != 2) {
2563               SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
2564                                                   OtherMul->op_begin()+OMulOp);
2565               MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
2566               InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2567             }
2568             SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2};
2569             const SCEV *InnerMulSum =
2570                 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2571             const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum,
2572                                               SCEV::FlagAnyWrap, Depth + 1);
2573             if (Ops.size() == 2) return OuterMul;
2574             Ops.erase(Ops.begin()+Idx);
2575             Ops.erase(Ops.begin()+OtherMulIdx-1);
2576             Ops.push_back(OuterMul);
2577             return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2578           }
2579       }
2580     }
2581   }
2582 
2583   // If there are any add recurrences in the operands list, see if any other
2584   // added values are loop invariant.  If so, we can fold them into the
2585   // recurrence.
2586   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2587     ++Idx;
2588 
2589   // Scan over all recurrences, trying to fold loop invariants into them.
2590   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2591     // Scan all of the other operands to this add and add them to the vector if
2592     // they are loop invariant w.r.t. the recurrence.
2593     SmallVector<const SCEV *, 8> LIOps;
2594     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2595     const Loop *AddRecLoop = AddRec->getLoop();
2596     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2597       if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2598         LIOps.push_back(Ops[i]);
2599         Ops.erase(Ops.begin()+i);
2600         --i; --e;
2601       }
2602 
2603     // If we found some loop invariants, fold them into the recurrence.
2604     if (!LIOps.empty()) {
2605       // Compute nowrap flags for the addition of the loop-invariant ops and
2606       // the addrec. Temporarily push it as an operand for that purpose.
2607       LIOps.push_back(AddRec);
2608       SCEV::NoWrapFlags Flags = ComputeFlags(LIOps);
2609       LIOps.pop_back();
2610 
2611       //  NLI + LI + {Start,+,Step}  -->  NLI + {LI+Start,+,Step}
2612       LIOps.push_back(AddRec->getStart());
2613 
2614       SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands());
2615       // This follows from the fact that the no-wrap flags on the outer add
2616       // expression are applicable on the 0th iteration, when the add recurrence
2617       // will be equal to its start value.
2618       AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1);
2619 
2620       // Build the new addrec. Propagate the NUW and NSW flags if both the
2621       // outer add and the inner addrec are guaranteed to have no overflow.
2622       // Always propagate NW.
2623       Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2624       const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2625 
2626       // If all of the other operands were loop invariant, we are done.
2627       if (Ops.size() == 1) return NewRec;
2628 
2629       // Otherwise, add the folded AddRec by the non-invariant parts.
2630       for (unsigned i = 0;; ++i)
2631         if (Ops[i] == AddRec) {
2632           Ops[i] = NewRec;
2633           break;
2634         }
2635       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2636     }
2637 
2638     // Okay, if there weren't any loop invariants to be folded, check to see if
2639     // there are multiple AddRec's with the same loop induction variable being
2640     // added together.  If so, we can fold them.
2641     for (unsigned OtherIdx = Idx+1;
2642          OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2643          ++OtherIdx) {
2644       // We expect the AddRecExpr's to be sorted in reverse dominance order,
2645       // so that the 1st found AddRecExpr is dominated by all others.
2646       assert(DT.dominates(
2647            cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
2648            AddRec->getLoop()->getHeader()) &&
2649         "AddRecExprs are not sorted in reverse dominance order?");
2650       if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2651         // Other + {A,+,B}<L> + {C,+,D}<L>  -->  Other + {A+C,+,B+D}<L>
2652         SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands());
2653         for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2654              ++OtherIdx) {
2655           const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2656           if (OtherAddRec->getLoop() == AddRecLoop) {
2657             for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2658                  i != e; ++i) {
2659               if (i >= AddRecOps.size()) {
2660                 AddRecOps.append(OtherAddRec->op_begin()+i,
2661                                  OtherAddRec->op_end());
2662                 break;
2663               }
2664               SmallVector<const SCEV *, 2> TwoOps = {
2665                   AddRecOps[i], OtherAddRec->getOperand(i)};
2666               AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2667             }
2668             Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2669           }
2670         }
2671         // Step size has changed, so we cannot guarantee no self-wraparound.
2672         Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2673         return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2674       }
2675     }
2676 
2677     // Otherwise couldn't fold anything into this recurrence.  Move onto the
2678     // next one.
2679   }
2680 
2681   // Okay, it looks like we really DO need an add expr.  Check to see if we
2682   // already have one, otherwise create a new one.
2683   return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
2684 }
2685 
2686 const SCEV *
2687 ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops,
2688                                     SCEV::NoWrapFlags Flags) {
2689   FoldingSetNodeID ID;
2690   ID.AddInteger(scAddExpr);
2691   for (const SCEV *Op : Ops)
2692     ID.AddPointer(Op);
2693   void *IP = nullptr;
2694   SCEVAddExpr *S =
2695       static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2696   if (!S) {
2697     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2698     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2699     S = new (SCEVAllocator)
2700         SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
2701     UniqueSCEVs.InsertNode(S, IP);
2702     addToLoopUseLists(S);
2703   }
2704   S->setNoWrapFlags(Flags);
2705   return S;
2706 }
2707 
2708 const SCEV *
2709 ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops,
2710                                        const Loop *L, SCEV::NoWrapFlags Flags) {
2711   FoldingSetNodeID ID;
2712   ID.AddInteger(scAddRecExpr);
2713   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2714     ID.AddPointer(Ops[i]);
2715   ID.AddPointer(L);
2716   void *IP = nullptr;
2717   SCEVAddRecExpr *S =
2718       static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2719   if (!S) {
2720     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2721     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2722     S = new (SCEVAllocator)
2723         SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L);
2724     UniqueSCEVs.InsertNode(S, IP);
2725     addToLoopUseLists(S);
2726   }
2727   setNoWrapFlags(S, Flags);
2728   return S;
2729 }
2730 
2731 const SCEV *
2732 ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops,
2733                                     SCEV::NoWrapFlags Flags) {
2734   FoldingSetNodeID ID;
2735   ID.AddInteger(scMulExpr);
2736   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2737     ID.AddPointer(Ops[i]);
2738   void *IP = nullptr;
2739   SCEVMulExpr *S =
2740     static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2741   if (!S) {
2742     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2743     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2744     S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2745                                         O, Ops.size());
2746     UniqueSCEVs.InsertNode(S, IP);
2747     addToLoopUseLists(S);
2748   }
2749   S->setNoWrapFlags(Flags);
2750   return S;
2751 }
2752 
2753 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2754   uint64_t k = i*j;
2755   if (j > 1 && k / j != i) Overflow = true;
2756   return k;
2757 }
2758 
2759 /// Compute the result of "n choose k", the binomial coefficient.  If an
2760 /// intermediate computation overflows, Overflow will be set and the return will
2761 /// be garbage. Overflow is not cleared on absence of overflow.
2762 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2763   // We use the multiplicative formula:
2764   //     n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2765   // At each iteration, we take the n-th term of the numeral and divide by the
2766   // (k-n)th term of the denominator.  This division will always produce an
2767   // integral result, and helps reduce the chance of overflow in the
2768   // intermediate computations. However, we can still overflow even when the
2769   // final result would fit.
2770 
2771   if (n == 0 || n == k) return 1;
2772   if (k > n) return 0;
2773 
2774   if (k > n/2)
2775     k = n-k;
2776 
2777   uint64_t r = 1;
2778   for (uint64_t i = 1; i <= k; ++i) {
2779     r = umul_ov(r, n-(i-1), Overflow);
2780     r /= i;
2781   }
2782   return r;
2783 }
2784 
2785 /// Determine if any of the operands in this SCEV are a constant or if
2786 /// any of the add or multiply expressions in this SCEV contain a constant.
2787 static bool containsConstantInAddMulChain(const SCEV *StartExpr) {
2788   struct FindConstantInAddMulChain {
2789     bool FoundConstant = false;
2790 
2791     bool follow(const SCEV *S) {
2792       FoundConstant |= isa<SCEVConstant>(S);
2793       return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
2794     }
2795 
2796     bool isDone() const {
2797       return FoundConstant;
2798     }
2799   };
2800 
2801   FindConstantInAddMulChain F;
2802   SCEVTraversal<FindConstantInAddMulChain> ST(F);
2803   ST.visitAll(StartExpr);
2804   return F.FoundConstant;
2805 }
2806 
2807 /// Get a canonical multiply expression, or something simpler if possible.
2808 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
2809                                         SCEV::NoWrapFlags OrigFlags,
2810                                         unsigned Depth) {
2811   assert(OrigFlags == maskFlags(OrigFlags, SCEV::FlagNUW | SCEV::FlagNSW) &&
2812          "only nuw or nsw allowed");
2813   assert(!Ops.empty() && "Cannot get empty mul!");
2814   if (Ops.size() == 1) return Ops[0];
2815 #ifndef NDEBUG
2816   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2817   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2818     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2819            "SCEVMulExpr operand types don't match!");
2820 #endif
2821 
2822   // Sort by complexity, this groups all similar expression types together.
2823   GroupByComplexity(Ops, &LI, DT);
2824 
2825   // If there are any constants, fold them together.
2826   unsigned Idx = 0;
2827   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2828     ++Idx;
2829     assert(Idx < Ops.size());
2830     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2831       // We found two constants, fold them together!
2832       Ops[0] = getConstant(LHSC->getAPInt() * RHSC->getAPInt());
2833       if (Ops.size() == 2) return Ops[0];
2834       Ops.erase(Ops.begin()+1);  // Erase the folded element
2835       LHSC = cast<SCEVConstant>(Ops[0]);
2836     }
2837 
2838     // If we have a multiply of zero, it will always be zero.
2839     if (LHSC->getValue()->isZero())
2840       return LHSC;
2841 
2842     // If we are left with a constant one being multiplied, strip it off.
2843     if (LHSC->getValue()->isOne()) {
2844       Ops.erase(Ops.begin());
2845       --Idx;
2846     }
2847 
2848     if (Ops.size() == 1)
2849       return Ops[0];
2850   }
2851 
2852   // Delay expensive flag strengthening until necessary.
2853   auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) {
2854     return StrengthenNoWrapFlags(this, scMulExpr, Ops, OrigFlags);
2855   };
2856 
2857   // Limit recursion calls depth.
2858   if (Depth > MaxArithDepth || hasHugeExpression(Ops))
2859     return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
2860 
2861   if (SCEV *S = std::get<0>(findExistingSCEVInCache(scMulExpr, Ops))) {
2862     // Don't strengthen flags if we have no new information.
2863     SCEVMulExpr *Mul = static_cast<SCEVMulExpr *>(S);
2864     if (Mul->getNoWrapFlags(OrigFlags) != OrigFlags)
2865       Mul->setNoWrapFlags(ComputeFlags(Ops));
2866     return S;
2867   }
2868 
2869   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2870     if (Ops.size() == 2) {
2871       // C1*(C2+V) -> C1*C2 + C1*V
2872       if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
2873         // If any of Add's ops are Adds or Muls with a constant, apply this
2874         // transformation as well.
2875         //
2876         // TODO: There are some cases where this transformation is not
2877         // profitable; for example, Add = (C0 + X) * Y + Z.  Maybe the scope of
2878         // this transformation should be narrowed down.
2879         if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add))
2880           return getAddExpr(getMulExpr(LHSC, Add->getOperand(0),
2881                                        SCEV::FlagAnyWrap, Depth + 1),
2882                             getMulExpr(LHSC, Add->getOperand(1),
2883                                        SCEV::FlagAnyWrap, Depth + 1),
2884                             SCEV::FlagAnyWrap, Depth + 1);
2885 
2886       if (Ops[0]->isAllOnesValue()) {
2887         // If we have a mul by -1 of an add, try distributing the -1 among the
2888         // add operands.
2889         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
2890           SmallVector<const SCEV *, 4> NewOps;
2891           bool AnyFolded = false;
2892           for (const SCEV *AddOp : Add->operands()) {
2893             const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap,
2894                                          Depth + 1);
2895             if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
2896             NewOps.push_back(Mul);
2897           }
2898           if (AnyFolded)
2899             return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1);
2900         } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
2901           // Negation preserves a recurrence's no self-wrap property.
2902           SmallVector<const SCEV *, 4> Operands;
2903           for (const SCEV *AddRecOp : AddRec->operands())
2904             Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap,
2905                                           Depth + 1));
2906 
2907           return getAddRecExpr(Operands, AddRec->getLoop(),
2908                                AddRec->getNoWrapFlags(SCEV::FlagNW));
2909         }
2910       }
2911     }
2912   }
2913 
2914   // Skip over the add expression until we get to a multiply.
2915   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2916     ++Idx;
2917 
2918   // If there are mul operands inline them all into this expression.
2919   if (Idx < Ops.size()) {
2920     bool DeletedMul = false;
2921     while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2922       if (Ops.size() > MulOpsInlineThreshold)
2923         break;
2924       // If we have an mul, expand the mul operands onto the end of the
2925       // operands list.
2926       Ops.erase(Ops.begin()+Idx);
2927       Ops.append(Mul->op_begin(), Mul->op_end());
2928       DeletedMul = true;
2929     }
2930 
2931     // If we deleted at least one mul, we added operands to the end of the
2932     // list, and they are not necessarily sorted.  Recurse to resort and
2933     // resimplify any operands we just acquired.
2934     if (DeletedMul)
2935       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2936   }
2937 
2938   // If there are any add recurrences in the operands list, see if any other
2939   // added values are loop invariant.  If so, we can fold them into the
2940   // recurrence.
2941   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2942     ++Idx;
2943 
2944   // Scan over all recurrences, trying to fold loop invariants into them.
2945   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2946     // Scan all of the other operands to this mul and add them to the vector
2947     // if they are loop invariant w.r.t. the recurrence.
2948     SmallVector<const SCEV *, 8> LIOps;
2949     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2950     const Loop *AddRecLoop = AddRec->getLoop();
2951     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2952       if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2953         LIOps.push_back(Ops[i]);
2954         Ops.erase(Ops.begin()+i);
2955         --i; --e;
2956       }
2957 
2958     // If we found some loop invariants, fold them into the recurrence.
2959     if (!LIOps.empty()) {
2960       //  NLI * LI * {Start,+,Step}  -->  NLI * {LI*Start,+,LI*Step}
2961       SmallVector<const SCEV *, 4> NewOps;
2962       NewOps.reserve(AddRec->getNumOperands());
2963       const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1);
2964       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
2965         NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
2966                                     SCEV::FlagAnyWrap, Depth + 1));
2967 
2968       // Build the new addrec. Propagate the NUW and NSW flags if both the
2969       // outer mul and the inner addrec are guaranteed to have no overflow.
2970       //
2971       // No self-wrap cannot be guaranteed after changing the step size, but
2972       // will be inferred if either NUW or NSW is true.
2973       SCEV::NoWrapFlags Flags = ComputeFlags({Scale, AddRec});
2974       const SCEV *NewRec = getAddRecExpr(
2975           NewOps, AddRecLoop, AddRec->getNoWrapFlags(Flags));
2976 
2977       // If all of the other operands were loop invariant, we are done.
2978       if (Ops.size() == 1) return NewRec;
2979 
2980       // Otherwise, multiply the folded AddRec by the non-invariant parts.
2981       for (unsigned i = 0;; ++i)
2982         if (Ops[i] == AddRec) {
2983           Ops[i] = NewRec;
2984           break;
2985         }
2986       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2987     }
2988 
2989     // Okay, if there weren't any loop invariants to be folded, check to see
2990     // if there are multiple AddRec's with the same loop induction variable
2991     // being multiplied together.  If so, we can fold them.
2992 
2993     // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
2994     // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
2995     //       choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
2996     //   ]]],+,...up to x=2n}.
2997     // Note that the arguments to choose() are always integers with values
2998     // known at compile time, never SCEV objects.
2999     //
3000     // The implementation avoids pointless extra computations when the two
3001     // addrec's are of different length (mathematically, it's equivalent to
3002     // an infinite stream of zeros on the right).
3003     bool OpsModified = false;
3004     for (unsigned OtherIdx = Idx+1;
3005          OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
3006          ++OtherIdx) {
3007       const SCEVAddRecExpr *OtherAddRec =
3008         dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
3009       if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
3010         continue;
3011 
3012       // Limit max number of arguments to avoid creation of unreasonably big
3013       // SCEVAddRecs with very complex operands.
3014       if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
3015           MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec}))
3016         continue;
3017 
3018       bool Overflow = false;
3019       Type *Ty = AddRec->getType();
3020       bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
3021       SmallVector<const SCEV*, 7> AddRecOps;
3022       for (int x = 0, xe = AddRec->getNumOperands() +
3023              OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
3024         SmallVector <const SCEV *, 7> SumOps;
3025         for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
3026           uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
3027           for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
3028                  ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
3029                z < ze && !Overflow; ++z) {
3030             uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
3031             uint64_t Coeff;
3032             if (LargerThan64Bits)
3033               Coeff = umul_ov(Coeff1, Coeff2, Overflow);
3034             else
3035               Coeff = Coeff1*Coeff2;
3036             const SCEV *CoeffTerm = getConstant(Ty, Coeff);
3037             const SCEV *Term1 = AddRec->getOperand(y-z);
3038             const SCEV *Term2 = OtherAddRec->getOperand(z);
3039             SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2,
3040                                         SCEV::FlagAnyWrap, Depth + 1));
3041           }
3042         }
3043         if (SumOps.empty())
3044           SumOps.push_back(getZero(Ty));
3045         AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1));
3046       }
3047       if (!Overflow) {
3048         const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRecLoop,
3049                                               SCEV::FlagAnyWrap);
3050         if (Ops.size() == 2) return NewAddRec;
3051         Ops[Idx] = NewAddRec;
3052         Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
3053         OpsModified = true;
3054         AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
3055         if (!AddRec)
3056           break;
3057       }
3058     }
3059     if (OpsModified)
3060       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3061 
3062     // Otherwise couldn't fold anything into this recurrence.  Move onto the
3063     // next one.
3064   }
3065 
3066   // Okay, it looks like we really DO need an mul expr.  Check to see if we
3067   // already have one, otherwise create a new one.
3068   return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
3069 }
3070 
3071 /// Represents an unsigned remainder expression based on unsigned division.
3072 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS,
3073                                          const SCEV *RHS) {
3074   assert(getEffectiveSCEVType(LHS->getType()) ==
3075          getEffectiveSCEVType(RHS->getType()) &&
3076          "SCEVURemExpr operand types don't match!");
3077 
3078   // Short-circuit easy cases
3079   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3080     // If constant is one, the result is trivial
3081     if (RHSC->getValue()->isOne())
3082       return getZero(LHS->getType()); // X urem 1 --> 0
3083 
3084     // If constant is a power of two, fold into a zext(trunc(LHS)).
3085     if (RHSC->getAPInt().isPowerOf2()) {
3086       Type *FullTy = LHS->getType();
3087       Type *TruncTy =
3088           IntegerType::get(getContext(), RHSC->getAPInt().logBase2());
3089       return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy);
3090     }
3091   }
3092 
3093   // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
3094   const SCEV *UDiv = getUDivExpr(LHS, RHS);
3095   const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW);
3096   return getMinusSCEV(LHS, Mult, SCEV::FlagNUW);
3097 }
3098 
3099 /// Get a canonical unsigned division expression, or something simpler if
3100 /// possible.
3101 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
3102                                          const SCEV *RHS) {
3103   assert(getEffectiveSCEVType(LHS->getType()) ==
3104          getEffectiveSCEVType(RHS->getType()) &&
3105          "SCEVUDivExpr operand types don't match!");
3106 
3107   FoldingSetNodeID ID;
3108   ID.AddInteger(scUDivExpr);
3109   ID.AddPointer(LHS);
3110   ID.AddPointer(RHS);
3111   void *IP = nullptr;
3112   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
3113     return S;
3114 
3115   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3116     if (RHSC->getValue()->isOne())
3117       return LHS;                               // X udiv 1 --> x
3118     // If the denominator is zero, the result of the udiv is undefined. Don't
3119     // try to analyze it, because the resolution chosen here may differ from
3120     // the resolution chosen in other parts of the compiler.
3121     if (!RHSC->getValue()->isZero()) {
3122       // Determine if the division can be folded into the operands of
3123       // its operands.
3124       // TODO: Generalize this to non-constants by using known-bits information.
3125       Type *Ty = LHS->getType();
3126       unsigned LZ = RHSC->getAPInt().countLeadingZeros();
3127       unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
3128       // For non-power-of-two values, effectively round the value up to the
3129       // nearest power of two.
3130       if (!RHSC->getAPInt().isPowerOf2())
3131         ++MaxShiftAmt;
3132       IntegerType *ExtTy =
3133         IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
3134       if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
3135         if (const SCEVConstant *Step =
3136             dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
3137           // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
3138           const APInt &StepInt = Step->getAPInt();
3139           const APInt &DivInt = RHSC->getAPInt();
3140           if (!StepInt.urem(DivInt) &&
3141               getZeroExtendExpr(AR, ExtTy) ==
3142               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3143                             getZeroExtendExpr(Step, ExtTy),
3144                             AR->getLoop(), SCEV::FlagAnyWrap)) {
3145             SmallVector<const SCEV *, 4> Operands;
3146             for (const SCEV *Op : AR->operands())
3147               Operands.push_back(getUDivExpr(Op, RHS));
3148             return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
3149           }
3150           /// Get a canonical UDivExpr for a recurrence.
3151           /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
3152           // We can currently only fold X%N if X is constant.
3153           const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
3154           if (StartC && !DivInt.urem(StepInt) &&
3155               getZeroExtendExpr(AR, ExtTy) ==
3156               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3157                             getZeroExtendExpr(Step, ExtTy),
3158                             AR->getLoop(), SCEV::FlagAnyWrap)) {
3159             const APInt &StartInt = StartC->getAPInt();
3160             const APInt &StartRem = StartInt.urem(StepInt);
3161             if (StartRem != 0) {
3162               const SCEV *NewLHS =
3163                   getAddRecExpr(getConstant(StartInt - StartRem), Step,
3164                                 AR->getLoop(), SCEV::FlagNW);
3165               if (LHS != NewLHS) {
3166                 LHS = NewLHS;
3167 
3168                 // Reset the ID to include the new LHS, and check if it is
3169                 // already cached.
3170                 ID.clear();
3171                 ID.AddInteger(scUDivExpr);
3172                 ID.AddPointer(LHS);
3173                 ID.AddPointer(RHS);
3174                 IP = nullptr;
3175                 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
3176                   return S;
3177               }
3178             }
3179           }
3180         }
3181       // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
3182       if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
3183         SmallVector<const SCEV *, 4> Operands;
3184         for (const SCEV *Op : M->operands())
3185           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3186         if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
3187           // Find an operand that's safely divisible.
3188           for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3189             const SCEV *Op = M->getOperand(i);
3190             const SCEV *Div = getUDivExpr(Op, RHSC);
3191             if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
3192               Operands = SmallVector<const SCEV *, 4>(M->operands());
3193               Operands[i] = Div;
3194               return getMulExpr(Operands);
3195             }
3196           }
3197       }
3198 
3199       // (A/B)/C --> A/(B*C) if safe and B*C can be folded.
3200       if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) {
3201         if (auto *DivisorConstant =
3202                 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) {
3203           bool Overflow = false;
3204           APInt NewRHS =
3205               DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow);
3206           if (Overflow) {
3207             return getConstant(RHSC->getType(), 0, false);
3208           }
3209           return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS));
3210         }
3211       }
3212 
3213       // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
3214       if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
3215         SmallVector<const SCEV *, 4> Operands;
3216         for (const SCEV *Op : A->operands())
3217           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3218         if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
3219           Operands.clear();
3220           for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
3221             const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
3222             if (isa<SCEVUDivExpr>(Op) ||
3223                 getMulExpr(Op, RHS) != A->getOperand(i))
3224               break;
3225             Operands.push_back(Op);
3226           }
3227           if (Operands.size() == A->getNumOperands())
3228             return getAddExpr(Operands);
3229         }
3230       }
3231 
3232       // Fold if both operands are constant.
3233       if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
3234         Constant *LHSCV = LHSC->getValue();
3235         Constant *RHSCV = RHSC->getValue();
3236         return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
3237                                                                    RHSCV)));
3238       }
3239     }
3240   }
3241 
3242   // The Insertion Point (IP) might be invalid by now (due to UniqueSCEVs
3243   // changes). Make sure we get a new one.
3244   IP = nullptr;
3245   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3246   SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
3247                                              LHS, RHS);
3248   UniqueSCEVs.InsertNode(S, IP);
3249   addToLoopUseLists(S);
3250   return S;
3251 }
3252 
3253 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
3254   APInt A = C1->getAPInt().abs();
3255   APInt B = C2->getAPInt().abs();
3256   uint32_t ABW = A.getBitWidth();
3257   uint32_t BBW = B.getBitWidth();
3258 
3259   if (ABW > BBW)
3260     B = B.zext(ABW);
3261   else if (ABW < BBW)
3262     A = A.zext(BBW);
3263 
3264   return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B));
3265 }
3266 
3267 /// Get a canonical unsigned division expression, or something simpler if
3268 /// possible. There is no representation for an exact udiv in SCEV IR, but we
3269 /// can attempt to remove factors from the LHS and RHS.  We can't do this when
3270 /// it's not exact because the udiv may be clearing bits.
3271 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
3272                                               const SCEV *RHS) {
3273   // TODO: we could try to find factors in all sorts of things, but for now we
3274   // just deal with u/exact (multiply, constant). See SCEVDivision towards the
3275   // end of this file for inspiration.
3276 
3277   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
3278   if (!Mul || !Mul->hasNoUnsignedWrap())
3279     return getUDivExpr(LHS, RHS);
3280 
3281   if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
3282     // If the mulexpr multiplies by a constant, then that constant must be the
3283     // first element of the mulexpr.
3284     if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
3285       if (LHSCst == RHSCst) {
3286         SmallVector<const SCEV *, 2> Operands(drop_begin(Mul->operands()));
3287         return getMulExpr(Operands);
3288       }
3289 
3290       // We can't just assume that LHSCst divides RHSCst cleanly, it could be
3291       // that there's a factor provided by one of the other terms. We need to
3292       // check.
3293       APInt Factor = gcd(LHSCst, RHSCst);
3294       if (!Factor.isIntN(1)) {
3295         LHSCst =
3296             cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
3297         RHSCst =
3298             cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
3299         SmallVector<const SCEV *, 2> Operands;
3300         Operands.push_back(LHSCst);
3301         Operands.append(Mul->op_begin() + 1, Mul->op_end());
3302         LHS = getMulExpr(Operands);
3303         RHS = RHSCst;
3304         Mul = dyn_cast<SCEVMulExpr>(LHS);
3305         if (!Mul)
3306           return getUDivExactExpr(LHS, RHS);
3307       }
3308     }
3309   }
3310 
3311   for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3312     if (Mul->getOperand(i) == RHS) {
3313       SmallVector<const SCEV *, 2> Operands;
3314       Operands.append(Mul->op_begin(), Mul->op_begin() + i);
3315       Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
3316       return getMulExpr(Operands);
3317     }
3318   }
3319 
3320   return getUDivExpr(LHS, RHS);
3321 }
3322 
3323 /// Get an add recurrence expression for the specified loop.  Simplify the
3324 /// expression as much as possible.
3325 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
3326                                            const Loop *L,
3327                                            SCEV::NoWrapFlags Flags) {
3328   SmallVector<const SCEV *, 4> Operands;
3329   Operands.push_back(Start);
3330   if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3331     if (StepChrec->getLoop() == L) {
3332       Operands.append(StepChrec->op_begin(), StepChrec->op_end());
3333       return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
3334     }
3335 
3336   Operands.push_back(Step);
3337   return getAddRecExpr(Operands, L, Flags);
3338 }
3339 
3340 /// Get an add recurrence expression for the specified loop.  Simplify the
3341 /// expression as much as possible.
3342 const SCEV *
3343 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
3344                                const Loop *L, SCEV::NoWrapFlags Flags) {
3345   if (Operands.size() == 1) return Operands[0];
3346 #ifndef NDEBUG
3347   Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
3348   for (unsigned i = 1, e = Operands.size(); i != e; ++i)
3349     assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
3350            "SCEVAddRecExpr operand types don't match!");
3351   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3352     assert(isLoopInvariant(Operands[i], L) &&
3353            "SCEVAddRecExpr operand is not loop-invariant!");
3354 #endif
3355 
3356   if (Operands.back()->isZero()) {
3357     Operands.pop_back();
3358     return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0}  -->  X
3359   }
3360 
3361   // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and
3362   // use that information to infer NUW and NSW flags. However, computing a
3363   // BE count requires calling getAddRecExpr, so we may not yet have a
3364   // meaningful BE count at this point (and if we don't, we'd be stuck
3365   // with a SCEVCouldNotCompute as the cached BE count).
3366 
3367   Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
3368 
3369   // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3370   if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3371     const Loop *NestedLoop = NestedAR->getLoop();
3372     if (L->contains(NestedLoop)
3373             ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3374             : (!NestedLoop->contains(L) &&
3375                DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3376       SmallVector<const SCEV *, 4> NestedOperands(NestedAR->operands());
3377       Operands[0] = NestedAR->getStart();
3378       // AddRecs require their operands be loop-invariant with respect to their
3379       // loops. Don't perform this transformation if it would break this
3380       // requirement.
3381       bool AllInvariant = all_of(
3382           Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3383 
3384       if (AllInvariant) {
3385         // Create a recurrence for the outer loop with the same step size.
3386         //
3387         // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3388         // inner recurrence has the same property.
3389         SCEV::NoWrapFlags OuterFlags =
3390           maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3391 
3392         NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3393         AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3394           return isLoopInvariant(Op, NestedLoop);
3395         });
3396 
3397         if (AllInvariant) {
3398           // Ok, both add recurrences are valid after the transformation.
3399           //
3400           // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3401           // the outer recurrence has the same property.
3402           SCEV::NoWrapFlags InnerFlags =
3403             maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
3404           return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3405         }
3406       }
3407       // Reset Operands to its original state.
3408       Operands[0] = NestedAR;
3409     }
3410   }
3411 
3412   // Okay, it looks like we really DO need an addrec expr.  Check to see if we
3413   // already have one, otherwise create a new one.
3414   return getOrCreateAddRecExpr(Operands, L, Flags);
3415 }
3416 
3417 const SCEV *
3418 ScalarEvolution::getGEPExpr(GEPOperator *GEP,
3419                             const SmallVectorImpl<const SCEV *> &IndexExprs) {
3420   const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3421   // getSCEV(Base)->getType() has the same address space as Base->getType()
3422   // because SCEV::getType() preserves the address space.
3423   Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType());
3424   // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP
3425   // instruction to its SCEV, because the Instruction may be guarded by control
3426   // flow and the no-overflow bits may not be valid for the expression in any
3427   // context. This can be fixed similarly to how these flags are handled for
3428   // adds.
3429   SCEV::NoWrapFlags OffsetWrap =
3430       GEP->isInBounds() ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3431 
3432   Type *CurTy = GEP->getType();
3433   bool FirstIter = true;
3434   SmallVector<const SCEV *, 4> Offsets;
3435   for (const SCEV *IndexExpr : IndexExprs) {
3436     // Compute the (potentially symbolic) offset in bytes for this index.
3437     if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3438       // For a struct, add the member offset.
3439       ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3440       unsigned FieldNo = Index->getZExtValue();
3441       const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo);
3442       Offsets.push_back(FieldOffset);
3443 
3444       // Update CurTy to the type of the field at Index.
3445       CurTy = STy->getTypeAtIndex(Index);
3446     } else {
3447       // Update CurTy to its element type.
3448       if (FirstIter) {
3449         assert(isa<PointerType>(CurTy) &&
3450                "The first index of a GEP indexes a pointer");
3451         CurTy = GEP->getSourceElementType();
3452         FirstIter = false;
3453       } else {
3454         CurTy = GetElementPtrInst::getTypeAtIndex(CurTy, (uint64_t)0);
3455       }
3456       // For an array, add the element offset, explicitly scaled.
3457       const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy);
3458       // Getelementptr indices are signed.
3459       IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy);
3460 
3461       // Multiply the index by the element size to compute the element offset.
3462       const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, OffsetWrap);
3463       Offsets.push_back(LocalOffset);
3464     }
3465   }
3466 
3467   // Handle degenerate case of GEP without offsets.
3468   if (Offsets.empty())
3469     return BaseExpr;
3470 
3471   // Add the offsets together, assuming nsw if inbounds.
3472   const SCEV *Offset = getAddExpr(Offsets, OffsetWrap);
3473   // Add the base address and the offset. We cannot use the nsw flag, as the
3474   // base address is unsigned. However, if we know that the offset is
3475   // non-negative, we can use nuw.
3476   SCEV::NoWrapFlags BaseWrap = GEP->isInBounds() && isKnownNonNegative(Offset)
3477                                    ? SCEV::FlagNUW : SCEV::FlagAnyWrap;
3478   return getAddExpr(BaseExpr, Offset, BaseWrap);
3479 }
3480 
3481 std::tuple<SCEV *, FoldingSetNodeID, void *>
3482 ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType,
3483                                          ArrayRef<const SCEV *> Ops) {
3484   FoldingSetNodeID ID;
3485   void *IP = nullptr;
3486   ID.AddInteger(SCEVType);
3487   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3488     ID.AddPointer(Ops[i]);
3489   return std::tuple<SCEV *, FoldingSetNodeID, void *>(
3490       UniqueSCEVs.FindNodeOrInsertPos(ID, IP), std::move(ID), IP);
3491 }
3492 
3493 const SCEV *ScalarEvolution::getAbsExpr(const SCEV *Op, bool IsNSW) {
3494   SCEV::NoWrapFlags Flags = IsNSW ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3495   return getSMaxExpr(Op, getNegativeSCEV(Op, Flags));
3496 }
3497 
3498 const SCEV *ScalarEvolution::getSignumExpr(const SCEV *Op) {
3499   Type *Ty = Op->getType();
3500   return getSMinExpr(getSMaxExpr(Op, getMinusOne(Ty)), getOne(Ty));
3501 }
3502 
3503 const SCEV *ScalarEvolution::getMinMaxExpr(SCEVTypes Kind,
3504                                            SmallVectorImpl<const SCEV *> &Ops) {
3505   assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
3506   if (Ops.size() == 1) return Ops[0];
3507 #ifndef NDEBUG
3508   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3509   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3510     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3511            "Operand types don't match!");
3512 #endif
3513 
3514   bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr;
3515   bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr;
3516 
3517   // Sort by complexity, this groups all similar expression types together.
3518   GroupByComplexity(Ops, &LI, DT);
3519 
3520   // Check if we have created the same expression before.
3521   if (const SCEV *S = std::get<0>(findExistingSCEVInCache(Kind, Ops))) {
3522     return S;
3523   }
3524 
3525   // If there are any constants, fold them together.
3526   unsigned Idx = 0;
3527   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3528     ++Idx;
3529     assert(Idx < Ops.size());
3530     auto FoldOp = [&](const APInt &LHS, const APInt &RHS) {
3531       if (Kind == scSMaxExpr)
3532         return APIntOps::smax(LHS, RHS);
3533       else if (Kind == scSMinExpr)
3534         return APIntOps::smin(LHS, RHS);
3535       else if (Kind == scUMaxExpr)
3536         return APIntOps::umax(LHS, RHS);
3537       else if (Kind == scUMinExpr)
3538         return APIntOps::umin(LHS, RHS);
3539       llvm_unreachable("Unknown SCEV min/max opcode");
3540     };
3541 
3542     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3543       // We found two constants, fold them together!
3544       ConstantInt *Fold = ConstantInt::get(
3545           getContext(), FoldOp(LHSC->getAPInt(), RHSC->getAPInt()));
3546       Ops[0] = getConstant(Fold);
3547       Ops.erase(Ops.begin()+1);  // Erase the folded element
3548       if (Ops.size() == 1) return Ops[0];
3549       LHSC = cast<SCEVConstant>(Ops[0]);
3550     }
3551 
3552     bool IsMinV = LHSC->getValue()->isMinValue(IsSigned);
3553     bool IsMaxV = LHSC->getValue()->isMaxValue(IsSigned);
3554 
3555     if (IsMax ? IsMinV : IsMaxV) {
3556       // If we are left with a constant minimum(/maximum)-int, strip it off.
3557       Ops.erase(Ops.begin());
3558       --Idx;
3559     } else if (IsMax ? IsMaxV : IsMinV) {
3560       // If we have a max(/min) with a constant maximum(/minimum)-int,
3561       // it will always be the extremum.
3562       return LHSC;
3563     }
3564 
3565     if (Ops.size() == 1) return Ops[0];
3566   }
3567 
3568   // Find the first operation of the same kind
3569   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind)
3570     ++Idx;
3571 
3572   // Check to see if one of the operands is of the same kind. If so, expand its
3573   // operands onto our operand list, and recurse to simplify.
3574   if (Idx < Ops.size()) {
3575     bool DeletedAny = false;
3576     while (Ops[Idx]->getSCEVType() == Kind) {
3577       const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]);
3578       Ops.erase(Ops.begin()+Idx);
3579       Ops.append(SMME->op_begin(), SMME->op_end());
3580       DeletedAny = true;
3581     }
3582 
3583     if (DeletedAny)
3584       return getMinMaxExpr(Kind, Ops);
3585   }
3586 
3587   // Okay, check to see if the same value occurs in the operand list twice.  If
3588   // so, delete one.  Since we sorted the list, these values are required to
3589   // be adjacent.
3590   llvm::CmpInst::Predicate GEPred =
3591       IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
3592   llvm::CmpInst::Predicate LEPred =
3593       IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
3594   llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred;
3595   llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred;
3596   for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) {
3597     if (Ops[i] == Ops[i + 1] ||
3598         isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) {
3599       //  X op Y op Y  -->  X op Y
3600       //  X op Y       -->  X, if we know X, Y are ordered appropriately
3601       Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2);
3602       --i;
3603       --e;
3604     } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i],
3605                                                Ops[i + 1])) {
3606       //  X op Y       -->  Y, if we know X, Y are ordered appropriately
3607       Ops.erase(Ops.begin() + i, Ops.begin() + i + 1);
3608       --i;
3609       --e;
3610     }
3611   }
3612 
3613   if (Ops.size() == 1) return Ops[0];
3614 
3615   assert(!Ops.empty() && "Reduced smax down to nothing!");
3616 
3617   // Okay, it looks like we really DO need an expr.  Check to see if we
3618   // already have one, otherwise create a new one.
3619   const SCEV *ExistingSCEV;
3620   FoldingSetNodeID ID;
3621   void *IP;
3622   std::tie(ExistingSCEV, ID, IP) = findExistingSCEVInCache(Kind, Ops);
3623   if (ExistingSCEV)
3624     return ExistingSCEV;
3625   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3626   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3627   SCEV *S = new (SCEVAllocator)
3628       SCEVMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
3629 
3630   UniqueSCEVs.InsertNode(S, IP);
3631   addToLoopUseLists(S);
3632   return S;
3633 }
3634 
3635 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) {
3636   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3637   return getSMaxExpr(Ops);
3638 }
3639 
3640 const SCEV *ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3641   return getMinMaxExpr(scSMaxExpr, Ops);
3642 }
3643 
3644 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) {
3645   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3646   return getUMaxExpr(Ops);
3647 }
3648 
3649 const SCEV *ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3650   return getMinMaxExpr(scUMaxExpr, Ops);
3651 }
3652 
3653 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
3654                                          const SCEV *RHS) {
3655   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
3656   return getSMinExpr(Ops);
3657 }
3658 
3659 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) {
3660   return getMinMaxExpr(scSMinExpr, Ops);
3661 }
3662 
3663 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
3664                                          const SCEV *RHS) {
3665   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
3666   return getUMinExpr(Ops);
3667 }
3668 
3669 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops) {
3670   return getMinMaxExpr(scUMinExpr, Ops);
3671 }
3672 
3673 const SCEV *
3674 ScalarEvolution::getSizeOfScalableVectorExpr(Type *IntTy,
3675                                              ScalableVectorType *ScalableTy) {
3676   Constant *NullPtr = Constant::getNullValue(ScalableTy->getPointerTo());
3677   Constant *One = ConstantInt::get(IntTy, 1);
3678   Constant *GEP = ConstantExpr::getGetElementPtr(ScalableTy, NullPtr, One);
3679   // Note that the expression we created is the final expression, we don't
3680   // want to simplify it any further Also, if we call a normal getSCEV(),
3681   // we'll end up in an endless recursion. So just create an SCEVUnknown.
3682   return getUnknown(ConstantExpr::getPtrToInt(GEP, IntTy));
3683 }
3684 
3685 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
3686   if (auto *ScalableAllocTy = dyn_cast<ScalableVectorType>(AllocTy))
3687     return getSizeOfScalableVectorExpr(IntTy, ScalableAllocTy);
3688   // We can bypass creating a target-independent constant expression and then
3689   // folding it back into a ConstantInt. This is just a compile-time
3690   // optimization.
3691   return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
3692 }
3693 
3694 const SCEV *ScalarEvolution::getStoreSizeOfExpr(Type *IntTy, Type *StoreTy) {
3695   if (auto *ScalableStoreTy = dyn_cast<ScalableVectorType>(StoreTy))
3696     return getSizeOfScalableVectorExpr(IntTy, ScalableStoreTy);
3697   // We can bypass creating a target-independent constant expression and then
3698   // folding it back into a ConstantInt. This is just a compile-time
3699   // optimization.
3700   return getConstant(IntTy, getDataLayout().getTypeStoreSize(StoreTy));
3701 }
3702 
3703 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
3704                                              StructType *STy,
3705                                              unsigned FieldNo) {
3706   // We can bypass creating a target-independent constant expression and then
3707   // folding it back into a ConstantInt. This is just a compile-time
3708   // optimization.
3709   return getConstant(
3710       IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
3711 }
3712 
3713 const SCEV *ScalarEvolution::getUnknown(Value *V) {
3714   // Don't attempt to do anything other than create a SCEVUnknown object
3715   // here.  createSCEV only calls getUnknown after checking for all other
3716   // interesting possibilities, and any other code that calls getUnknown
3717   // is doing so in order to hide a value from SCEV canonicalization.
3718 
3719   FoldingSetNodeID ID;
3720   ID.AddInteger(scUnknown);
3721   ID.AddPointer(V);
3722   void *IP = nullptr;
3723   if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3724     assert(cast<SCEVUnknown>(S)->getValue() == V &&
3725            "Stale SCEVUnknown in uniquing map!");
3726     return S;
3727   }
3728   SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3729                                             FirstUnknown);
3730   FirstUnknown = cast<SCEVUnknown>(S);
3731   UniqueSCEVs.InsertNode(S, IP);
3732   return S;
3733 }
3734 
3735 //===----------------------------------------------------------------------===//
3736 //            Basic SCEV Analysis and PHI Idiom Recognition Code
3737 //
3738 
3739 /// Test if values of the given type are analyzable within the SCEV
3740 /// framework. This primarily includes integer types, and it can optionally
3741 /// include pointer types if the ScalarEvolution class has access to
3742 /// target-specific information.
3743 bool ScalarEvolution::isSCEVable(Type *Ty) const {
3744   // Integers and pointers are always SCEVable.
3745   return Ty->isIntOrPtrTy();
3746 }
3747 
3748 /// Return the size in bits of the specified type, for which isSCEVable must
3749 /// return true.
3750 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
3751   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3752   if (Ty->isPointerTy())
3753     return getDataLayout().getIndexTypeSizeInBits(Ty);
3754   return getDataLayout().getTypeSizeInBits(Ty);
3755 }
3756 
3757 /// Return a type with the same bitwidth as the given type and which represents
3758 /// how SCEV will treat the given type, for which isSCEVable must return
3759 /// true. For pointer types, this is the pointer index sized integer type.
3760 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
3761   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3762 
3763   if (Ty->isIntegerTy())
3764     return Ty;
3765 
3766   // The only other support type is pointer.
3767   assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
3768   return getDataLayout().getIndexType(Ty);
3769 }
3770 
3771 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const {
3772   return  getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
3773 }
3774 
3775 const SCEV *ScalarEvolution::getCouldNotCompute() {
3776   return CouldNotCompute.get();
3777 }
3778 
3779 bool ScalarEvolution::checkValidity(const SCEV *S) const {
3780   bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
3781     auto *SU = dyn_cast<SCEVUnknown>(S);
3782     return SU && SU->getValue() == nullptr;
3783   });
3784 
3785   return !ContainsNulls;
3786 }
3787 
3788 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
3789   HasRecMapType::iterator I = HasRecMap.find(S);
3790   if (I != HasRecMap.end())
3791     return I->second;
3792 
3793   bool FoundAddRec =
3794       SCEVExprContains(S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); });
3795   HasRecMap.insert({S, FoundAddRec});
3796   return FoundAddRec;
3797 }
3798 
3799 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}.
3800 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an
3801 /// offset I, then return {S', I}, else return {\p S, nullptr}.
3802 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) {
3803   const auto *Add = dyn_cast<SCEVAddExpr>(S);
3804   if (!Add)
3805     return {S, nullptr};
3806 
3807   if (Add->getNumOperands() != 2)
3808     return {S, nullptr};
3809 
3810   auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0));
3811   if (!ConstOp)
3812     return {S, nullptr};
3813 
3814   return {Add->getOperand(1), ConstOp->getValue()};
3815 }
3816 
3817 /// Return the ValueOffsetPair set for \p S. \p S can be represented
3818 /// by the value and offset from any ValueOffsetPair in the set.
3819 SetVector<ScalarEvolution::ValueOffsetPair> *
3820 ScalarEvolution::getSCEVValues(const SCEV *S) {
3821   ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
3822   if (SI == ExprValueMap.end())
3823     return nullptr;
3824 #ifndef NDEBUG
3825   if (VerifySCEVMap) {
3826     // Check there is no dangling Value in the set returned.
3827     for (const auto &VE : SI->second)
3828       assert(ValueExprMap.count(VE.first));
3829   }
3830 #endif
3831   return &SI->second;
3832 }
3833 
3834 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
3835 /// cannot be used separately. eraseValueFromMap should be used to remove
3836 /// V from ValueExprMap and ExprValueMap at the same time.
3837 void ScalarEvolution::eraseValueFromMap(Value *V) {
3838   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3839   if (I != ValueExprMap.end()) {
3840     const SCEV *S = I->second;
3841     // Remove {V, 0} from the set of ExprValueMap[S]
3842     if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S))
3843       SV->remove({V, nullptr});
3844 
3845     // Remove {V, Offset} from the set of ExprValueMap[Stripped]
3846     const SCEV *Stripped;
3847     ConstantInt *Offset;
3848     std::tie(Stripped, Offset) = splitAddExpr(S);
3849     if (Offset != nullptr) {
3850       if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped))
3851         SV->remove({V, Offset});
3852     }
3853     ValueExprMap.erase(V);
3854   }
3855 }
3856 
3857 /// Check whether value has nuw/nsw/exact set but SCEV does not.
3858 /// TODO: In reality it is better to check the poison recursively
3859 /// but this is better than nothing.
3860 static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) {
3861   if (auto *I = dyn_cast<Instruction>(V)) {
3862     if (isa<OverflowingBinaryOperator>(I)) {
3863       if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) {
3864         if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap())
3865           return true;
3866         if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap())
3867           return true;
3868       }
3869     } else if (isa<PossiblyExactOperator>(I) && I->isExact())
3870       return true;
3871   }
3872   return false;
3873 }
3874 
3875 /// Return an existing SCEV if it exists, otherwise analyze the expression and
3876 /// create a new one.
3877 const SCEV *ScalarEvolution::getSCEV(Value *V) {
3878   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3879 
3880   const SCEV *S = getExistingSCEV(V);
3881   if (S == nullptr) {
3882     S = createSCEV(V);
3883     // During PHI resolution, it is possible to create two SCEVs for the same
3884     // V, so it is needed to double check whether V->S is inserted into
3885     // ValueExprMap before insert S->{V, 0} into ExprValueMap.
3886     std::pair<ValueExprMapType::iterator, bool> Pair =
3887         ValueExprMap.insert({SCEVCallbackVH(V, this), S});
3888     if (Pair.second && !SCEVLostPoisonFlags(S, V)) {
3889       ExprValueMap[S].insert({V, nullptr});
3890 
3891       // If S == Stripped + Offset, add Stripped -> {V, Offset} into
3892       // ExprValueMap.
3893       const SCEV *Stripped = S;
3894       ConstantInt *Offset = nullptr;
3895       std::tie(Stripped, Offset) = splitAddExpr(S);
3896       // If stripped is SCEVUnknown, don't bother to save
3897       // Stripped -> {V, offset}. It doesn't simplify and sometimes even
3898       // increase the complexity of the expansion code.
3899       // If V is GetElementPtrInst, don't save Stripped -> {V, offset}
3900       // because it may generate add/sub instead of GEP in SCEV expansion.
3901       if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) &&
3902           !isa<GetElementPtrInst>(V))
3903         ExprValueMap[Stripped].insert({V, Offset});
3904     }
3905   }
3906   return S;
3907 }
3908 
3909 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
3910   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3911 
3912   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3913   if (I != ValueExprMap.end()) {
3914     const SCEV *S = I->second;
3915     if (checkValidity(S))
3916       return S;
3917     eraseValueFromMap(V);
3918     forgetMemoizedResults(S);
3919   }
3920   return nullptr;
3921 }
3922 
3923 /// Return a SCEV corresponding to -V = -1*V
3924 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
3925                                              SCEV::NoWrapFlags Flags) {
3926   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3927     return getConstant(
3928                cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
3929 
3930   Type *Ty = V->getType();
3931   Ty = getEffectiveSCEVType(Ty);
3932   return getMulExpr(V, getMinusOne(Ty), Flags);
3933 }
3934 
3935 /// If Expr computes ~A, return A else return nullptr
3936 static const SCEV *MatchNotExpr(const SCEV *Expr) {
3937   const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
3938   if (!Add || Add->getNumOperands() != 2 ||
3939       !Add->getOperand(0)->isAllOnesValue())
3940     return nullptr;
3941 
3942   const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
3943   if (!AddRHS || AddRHS->getNumOperands() != 2 ||
3944       !AddRHS->getOperand(0)->isAllOnesValue())
3945     return nullptr;
3946 
3947   return AddRHS->getOperand(1);
3948 }
3949 
3950 /// Return a SCEV corresponding to ~V = -1-V
3951 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
3952   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3953     return getConstant(
3954                 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
3955 
3956   // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y)
3957   if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) {
3958     auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) {
3959       SmallVector<const SCEV *, 2> MatchedOperands;
3960       for (const SCEV *Operand : MME->operands()) {
3961         const SCEV *Matched = MatchNotExpr(Operand);
3962         if (!Matched)
3963           return (const SCEV *)nullptr;
3964         MatchedOperands.push_back(Matched);
3965       }
3966       return getMinMaxExpr(SCEVMinMaxExpr::negate(MME->getSCEVType()),
3967                            MatchedOperands);
3968     };
3969     if (const SCEV *Replaced = MatchMinMaxNegation(MME))
3970       return Replaced;
3971   }
3972 
3973   Type *Ty = V->getType();
3974   Ty = getEffectiveSCEVType(Ty);
3975   return getMinusSCEV(getMinusOne(Ty), V);
3976 }
3977 
3978 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
3979                                           SCEV::NoWrapFlags Flags,
3980                                           unsigned Depth) {
3981   // Fast path: X - X --> 0.
3982   if (LHS == RHS)
3983     return getZero(LHS->getType());
3984 
3985   // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
3986   // makes it so that we cannot make much use of NUW.
3987   auto AddFlags = SCEV::FlagAnyWrap;
3988   const bool RHSIsNotMinSigned =
3989       !getSignedRangeMin(RHS).isMinSignedValue();
3990   if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) {
3991     // Let M be the minimum representable signed value. Then (-1)*RHS
3992     // signed-wraps if and only if RHS is M. That can happen even for
3993     // a NSW subtraction because e.g. (-1)*M signed-wraps even though
3994     // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
3995     // (-1)*RHS, we need to prove that RHS != M.
3996     //
3997     // If LHS is non-negative and we know that LHS - RHS does not
3998     // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
3999     // either by proving that RHS > M or that LHS >= 0.
4000     if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
4001       AddFlags = SCEV::FlagNSW;
4002     }
4003   }
4004 
4005   // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
4006   // RHS is NSW and LHS >= 0.
4007   //
4008   // The difficulty here is that the NSW flag may have been proven
4009   // relative to a loop that is to be found in a recurrence in LHS and
4010   // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
4011   // larger scope than intended.
4012   auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
4013 
4014   return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
4015 }
4016 
4017 const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty,
4018                                                      unsigned Depth) {
4019   Type *SrcTy = V->getType();
4020   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4021          "Cannot truncate or zero extend with non-integer arguments!");
4022   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4023     return V;  // No conversion
4024   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4025     return getTruncateExpr(V, Ty, Depth);
4026   return getZeroExtendExpr(V, Ty, Depth);
4027 }
4028 
4029 const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty,
4030                                                      unsigned Depth) {
4031   Type *SrcTy = V->getType();
4032   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4033          "Cannot truncate or zero extend with non-integer arguments!");
4034   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4035     return V;  // No conversion
4036   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4037     return getTruncateExpr(V, Ty, Depth);
4038   return getSignExtendExpr(V, Ty, Depth);
4039 }
4040 
4041 const SCEV *
4042 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
4043   Type *SrcTy = V->getType();
4044   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4045          "Cannot noop or zero extend with non-integer arguments!");
4046   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4047          "getNoopOrZeroExtend cannot truncate!");
4048   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4049     return V;  // No conversion
4050   return getZeroExtendExpr(V, Ty);
4051 }
4052 
4053 const SCEV *
4054 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
4055   Type *SrcTy = V->getType();
4056   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4057          "Cannot noop or sign extend with non-integer arguments!");
4058   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4059          "getNoopOrSignExtend cannot truncate!");
4060   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4061     return V;  // No conversion
4062   return getSignExtendExpr(V, Ty);
4063 }
4064 
4065 const SCEV *
4066 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
4067   Type *SrcTy = V->getType();
4068   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4069          "Cannot noop or any extend with non-integer arguments!");
4070   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4071          "getNoopOrAnyExtend cannot truncate!");
4072   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4073     return V;  // No conversion
4074   return getAnyExtendExpr(V, Ty);
4075 }
4076 
4077 const SCEV *
4078 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
4079   Type *SrcTy = V->getType();
4080   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4081          "Cannot truncate or noop with non-integer arguments!");
4082   assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
4083          "getTruncateOrNoop cannot extend!");
4084   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4085     return V;  // No conversion
4086   return getTruncateExpr(V, Ty);
4087 }
4088 
4089 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
4090                                                         const SCEV *RHS) {
4091   const SCEV *PromotedLHS = LHS;
4092   const SCEV *PromotedRHS = RHS;
4093 
4094   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
4095     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
4096   else
4097     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
4098 
4099   return getUMaxExpr(PromotedLHS, PromotedRHS);
4100 }
4101 
4102 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
4103                                                         const SCEV *RHS) {
4104   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
4105   return getUMinFromMismatchedTypes(Ops);
4106 }
4107 
4108 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(
4109     SmallVectorImpl<const SCEV *> &Ops) {
4110   assert(!Ops.empty() && "At least one operand must be!");
4111   // Trivial case.
4112   if (Ops.size() == 1)
4113     return Ops[0];
4114 
4115   // Find the max type first.
4116   Type *MaxType = nullptr;
4117   for (auto *S : Ops)
4118     if (MaxType)
4119       MaxType = getWiderType(MaxType, S->getType());
4120     else
4121       MaxType = S->getType();
4122   assert(MaxType && "Failed to find maximum type!");
4123 
4124   // Extend all ops to max type.
4125   SmallVector<const SCEV *, 2> PromotedOps;
4126   for (auto *S : Ops)
4127     PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType));
4128 
4129   // Generate umin.
4130   return getUMinExpr(PromotedOps);
4131 }
4132 
4133 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
4134   // A pointer operand may evaluate to a nonpointer expression, such as null.
4135   if (!V->getType()->isPointerTy())
4136     return V;
4137 
4138   while (true) {
4139     if (const SCEVIntegralCastExpr *Cast = dyn_cast<SCEVIntegralCastExpr>(V)) {
4140       V = Cast->getOperand();
4141     } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
4142       const SCEV *PtrOp = nullptr;
4143       for (const SCEV *NAryOp : NAry->operands()) {
4144         if (NAryOp->getType()->isPointerTy()) {
4145           // Cannot find the base of an expression with multiple pointer ops.
4146           if (PtrOp)
4147             return V;
4148           PtrOp = NAryOp;
4149         }
4150       }
4151       if (!PtrOp) // All operands were non-pointer.
4152         return V;
4153       V = PtrOp;
4154     } else // Not something we can look further into.
4155       return V;
4156   }
4157 }
4158 
4159 /// Push users of the given Instruction onto the given Worklist.
4160 static void
4161 PushDefUseChildren(Instruction *I,
4162                    SmallVectorImpl<Instruction *> &Worklist) {
4163   // Push the def-use children onto the Worklist stack.
4164   for (User *U : I->users())
4165     Worklist.push_back(cast<Instruction>(U));
4166 }
4167 
4168 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) {
4169   SmallVector<Instruction *, 16> Worklist;
4170   PushDefUseChildren(PN, Worklist);
4171 
4172   SmallPtrSet<Instruction *, 8> Visited;
4173   Visited.insert(PN);
4174   while (!Worklist.empty()) {
4175     Instruction *I = Worklist.pop_back_val();
4176     if (!Visited.insert(I).second)
4177       continue;
4178 
4179     auto It = ValueExprMap.find_as(static_cast<Value *>(I));
4180     if (It != ValueExprMap.end()) {
4181       const SCEV *Old = It->second;
4182 
4183       // Short-circuit the def-use traversal if the symbolic name
4184       // ceases to appear in expressions.
4185       if (Old != SymName && !hasOperand(Old, SymName))
4186         continue;
4187 
4188       // SCEVUnknown for a PHI either means that it has an unrecognized
4189       // structure, it's a PHI that's in the progress of being computed
4190       // by createNodeForPHI, or it's a single-value PHI. In the first case,
4191       // additional loop trip count information isn't going to change anything.
4192       // In the second case, createNodeForPHI will perform the necessary
4193       // updates on its own when it gets to that point. In the third, we do
4194       // want to forget the SCEVUnknown.
4195       if (!isa<PHINode>(I) ||
4196           !isa<SCEVUnknown>(Old) ||
4197           (I != PN && Old == SymName)) {
4198         eraseValueFromMap(It->first);
4199         forgetMemoizedResults(Old);
4200       }
4201     }
4202 
4203     PushDefUseChildren(I, Worklist);
4204   }
4205 }
4206 
4207 namespace {
4208 
4209 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start
4210 /// expression in case its Loop is L. If it is not L then
4211 /// if IgnoreOtherLoops is true then use AddRec itself
4212 /// otherwise rewrite cannot be done.
4213 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4214 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
4215 public:
4216   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
4217                              bool IgnoreOtherLoops = true) {
4218     SCEVInitRewriter Rewriter(L, SE);
4219     const SCEV *Result = Rewriter.visit(S);
4220     if (Rewriter.hasSeenLoopVariantSCEVUnknown())
4221       return SE.getCouldNotCompute();
4222     return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops
4223                ? SE.getCouldNotCompute()
4224                : Result;
4225   }
4226 
4227   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4228     if (!SE.isLoopInvariant(Expr, L))
4229       SeenLoopVariantSCEVUnknown = true;
4230     return Expr;
4231   }
4232 
4233   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4234     // Only re-write AddRecExprs for this loop.
4235     if (Expr->getLoop() == L)
4236       return Expr->getStart();
4237     SeenOtherLoops = true;
4238     return Expr;
4239   }
4240 
4241   bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4242 
4243   bool hasSeenOtherLoops() { return SeenOtherLoops; }
4244 
4245 private:
4246   explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
4247       : SCEVRewriteVisitor(SE), L(L) {}
4248 
4249   const Loop *L;
4250   bool SeenLoopVariantSCEVUnknown = false;
4251   bool SeenOtherLoops = false;
4252 };
4253 
4254 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post
4255 /// increment expression in case its Loop is L. If it is not L then
4256 /// use AddRec itself.
4257 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4258 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> {
4259 public:
4260   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) {
4261     SCEVPostIncRewriter Rewriter(L, SE);
4262     const SCEV *Result = Rewriter.visit(S);
4263     return Rewriter.hasSeenLoopVariantSCEVUnknown()
4264         ? SE.getCouldNotCompute()
4265         : Result;
4266   }
4267 
4268   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4269     if (!SE.isLoopInvariant(Expr, L))
4270       SeenLoopVariantSCEVUnknown = true;
4271     return Expr;
4272   }
4273 
4274   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4275     // Only re-write AddRecExprs for this loop.
4276     if (Expr->getLoop() == L)
4277       return Expr->getPostIncExpr(SE);
4278     SeenOtherLoops = true;
4279     return Expr;
4280   }
4281 
4282   bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4283 
4284   bool hasSeenOtherLoops() { return SeenOtherLoops; }
4285 
4286 private:
4287   explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE)
4288       : SCEVRewriteVisitor(SE), L(L) {}
4289 
4290   const Loop *L;
4291   bool SeenLoopVariantSCEVUnknown = false;
4292   bool SeenOtherLoops = false;
4293 };
4294 
4295 /// This class evaluates the compare condition by matching it against the
4296 /// condition of loop latch. If there is a match we assume a true value
4297 /// for the condition while building SCEV nodes.
4298 class SCEVBackedgeConditionFolder
4299     : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> {
4300 public:
4301   static const SCEV *rewrite(const SCEV *S, const Loop *L,
4302                              ScalarEvolution &SE) {
4303     bool IsPosBECond = false;
4304     Value *BECond = nullptr;
4305     if (BasicBlock *Latch = L->getLoopLatch()) {
4306       BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator());
4307       if (BI && BI->isConditional()) {
4308         assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
4309                "Both outgoing branches should not target same header!");
4310         BECond = BI->getCondition();
4311         IsPosBECond = BI->getSuccessor(0) == L->getHeader();
4312       } else {
4313         return S;
4314       }
4315     }
4316     SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE);
4317     return Rewriter.visit(S);
4318   }
4319 
4320   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4321     const SCEV *Result = Expr;
4322     bool InvariantF = SE.isLoopInvariant(Expr, L);
4323 
4324     if (!InvariantF) {
4325       Instruction *I = cast<Instruction>(Expr->getValue());
4326       switch (I->getOpcode()) {
4327       case Instruction::Select: {
4328         SelectInst *SI = cast<SelectInst>(I);
4329         Optional<const SCEV *> Res =
4330             compareWithBackedgeCondition(SI->getCondition());
4331         if (Res.hasValue()) {
4332           bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne();
4333           Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue());
4334         }
4335         break;
4336       }
4337       default: {
4338         Optional<const SCEV *> Res = compareWithBackedgeCondition(I);
4339         if (Res.hasValue())
4340           Result = Res.getValue();
4341         break;
4342       }
4343       }
4344     }
4345     return Result;
4346   }
4347 
4348 private:
4349   explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond,
4350                                        bool IsPosBECond, ScalarEvolution &SE)
4351       : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond),
4352         IsPositiveBECond(IsPosBECond) {}
4353 
4354   Optional<const SCEV *> compareWithBackedgeCondition(Value *IC);
4355 
4356   const Loop *L;
4357   /// Loop back condition.
4358   Value *BackedgeCond = nullptr;
4359   /// Set to true if loop back is on positive branch condition.
4360   bool IsPositiveBECond;
4361 };
4362 
4363 Optional<const SCEV *>
4364 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) {
4365 
4366   // If value matches the backedge condition for loop latch,
4367   // then return a constant evolution node based on loopback
4368   // branch taken.
4369   if (BackedgeCond == IC)
4370     return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext()))
4371                             : SE.getZero(Type::getInt1Ty(SE.getContext()));
4372   return None;
4373 }
4374 
4375 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
4376 public:
4377   static const SCEV *rewrite(const SCEV *S, const Loop *L,
4378                              ScalarEvolution &SE) {
4379     SCEVShiftRewriter Rewriter(L, SE);
4380     const SCEV *Result = Rewriter.visit(S);
4381     return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
4382   }
4383 
4384   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4385     // Only allow AddRecExprs for this loop.
4386     if (!SE.isLoopInvariant(Expr, L))
4387       Valid = false;
4388     return Expr;
4389   }
4390 
4391   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4392     if (Expr->getLoop() == L && Expr->isAffine())
4393       return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
4394     Valid = false;
4395     return Expr;
4396   }
4397 
4398   bool isValid() { return Valid; }
4399 
4400 private:
4401   explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
4402       : SCEVRewriteVisitor(SE), L(L) {}
4403 
4404   const Loop *L;
4405   bool Valid = true;
4406 };
4407 
4408 } // end anonymous namespace
4409 
4410 SCEV::NoWrapFlags
4411 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
4412   if (!AR->isAffine())
4413     return SCEV::FlagAnyWrap;
4414 
4415   using OBO = OverflowingBinaryOperator;
4416 
4417   SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
4418 
4419   if (!AR->hasNoSignedWrap()) {
4420     ConstantRange AddRecRange = getSignedRange(AR);
4421     ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
4422 
4423     auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4424         Instruction::Add, IncRange, OBO::NoSignedWrap);
4425     if (NSWRegion.contains(AddRecRange))
4426       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
4427   }
4428 
4429   if (!AR->hasNoUnsignedWrap()) {
4430     ConstantRange AddRecRange = getUnsignedRange(AR);
4431     ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
4432 
4433     auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4434         Instruction::Add, IncRange, OBO::NoUnsignedWrap);
4435     if (NUWRegion.contains(AddRecRange))
4436       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
4437   }
4438 
4439   return Result;
4440 }
4441 
4442 SCEV::NoWrapFlags
4443 ScalarEvolution::proveNoSignedWrapViaInduction(const SCEVAddRecExpr *AR) {
4444   SCEV::NoWrapFlags Result = AR->getNoWrapFlags();
4445 
4446   if (AR->hasNoSignedWrap())
4447     return Result;
4448 
4449   if (!AR->isAffine())
4450     return Result;
4451 
4452   const SCEV *Step = AR->getStepRecurrence(*this);
4453   const Loop *L = AR->getLoop();
4454 
4455   // Check whether the backedge-taken count is SCEVCouldNotCompute.
4456   // Note that this serves two purposes: It filters out loops that are
4457   // simply not analyzable, and it covers the case where this code is
4458   // being called from within backedge-taken count analysis, such that
4459   // attempting to ask for the backedge-taken count would likely result
4460   // in infinite recursion. In the later case, the analysis code will
4461   // cope with a conservative value, and it will take care to purge
4462   // that value once it has finished.
4463   const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
4464 
4465   // Normally, in the cases we can prove no-overflow via a
4466   // backedge guarding condition, we can also compute a backedge
4467   // taken count for the loop.  The exceptions are assumptions and
4468   // guards present in the loop -- SCEV is not great at exploiting
4469   // these to compute max backedge taken counts, but can still use
4470   // these to prove lack of overflow.  Use this fact to avoid
4471   // doing extra work that may not pay off.
4472 
4473   if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
4474       AC.assumptions().empty())
4475     return Result;
4476 
4477   // If the backedge is guarded by a comparison with the pre-inc  value the
4478   // addrec is safe. Also, if the entry is guarded by a comparison with the
4479   // start value and the backedge is guarded by a comparison with the post-inc
4480   // value, the addrec is safe.
4481   ICmpInst::Predicate Pred;
4482   const SCEV *OverflowLimit =
4483     getSignedOverflowLimitForStep(Step, &Pred, this);
4484   if (OverflowLimit &&
4485       (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
4486        isKnownOnEveryIteration(Pred, AR, OverflowLimit))) {
4487     Result = setFlags(Result, SCEV::FlagNSW);
4488   }
4489   return Result;
4490 }
4491 SCEV::NoWrapFlags
4492 ScalarEvolution::proveNoUnsignedWrapViaInduction(const SCEVAddRecExpr *AR) {
4493   SCEV::NoWrapFlags Result = AR->getNoWrapFlags();
4494 
4495   if (AR->hasNoUnsignedWrap())
4496     return Result;
4497 
4498   if (!AR->isAffine())
4499     return Result;
4500 
4501   const SCEV *Step = AR->getStepRecurrence(*this);
4502   unsigned BitWidth = getTypeSizeInBits(AR->getType());
4503   const Loop *L = AR->getLoop();
4504 
4505   // Check whether the backedge-taken count is SCEVCouldNotCompute.
4506   // Note that this serves two purposes: It filters out loops that are
4507   // simply not analyzable, and it covers the case where this code is
4508   // being called from within backedge-taken count analysis, such that
4509   // attempting to ask for the backedge-taken count would likely result
4510   // in infinite recursion. In the later case, the analysis code will
4511   // cope with a conservative value, and it will take care to purge
4512   // that value once it has finished.
4513   const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
4514 
4515   // Normally, in the cases we can prove no-overflow via a
4516   // backedge guarding condition, we can also compute a backedge
4517   // taken count for the loop.  The exceptions are assumptions and
4518   // guards present in the loop -- SCEV is not great at exploiting
4519   // these to compute max backedge taken counts, but can still use
4520   // these to prove lack of overflow.  Use this fact to avoid
4521   // doing extra work that may not pay off.
4522 
4523   if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
4524       AC.assumptions().empty())
4525     return Result;
4526 
4527   // If the backedge is guarded by a comparison with the pre-inc  value the
4528   // addrec is safe. Also, if the entry is guarded by a comparison with the
4529   // start value and the backedge is guarded by a comparison with the post-inc
4530   // value, the addrec is safe.
4531   if (isKnownPositive(Step)) {
4532     const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
4533                                 getUnsignedRangeMax(Step));
4534     if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
4535         isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) {
4536       Result = setFlags(Result, SCEV::FlagNUW);
4537     }
4538   }
4539 
4540   return Result;
4541 }
4542 
4543 namespace {
4544 
4545 /// Represents an abstract binary operation.  This may exist as a
4546 /// normal instruction or constant expression, or may have been
4547 /// derived from an expression tree.
4548 struct BinaryOp {
4549   unsigned Opcode;
4550   Value *LHS;
4551   Value *RHS;
4552   bool IsNSW = false;
4553   bool IsNUW = false;
4554   bool IsExact = false;
4555 
4556   /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
4557   /// constant expression.
4558   Operator *Op = nullptr;
4559 
4560   explicit BinaryOp(Operator *Op)
4561       : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
4562         Op(Op) {
4563     if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
4564       IsNSW = OBO->hasNoSignedWrap();
4565       IsNUW = OBO->hasNoUnsignedWrap();
4566     }
4567     if (auto *PEO = dyn_cast<PossiblyExactOperator>(Op))
4568       IsExact = PEO->isExact();
4569   }
4570 
4571   explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
4572                     bool IsNUW = false, bool IsExact = false)
4573       : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW),
4574         IsExact(IsExact) {}
4575 };
4576 
4577 } // end anonymous namespace
4578 
4579 /// Try to map \p V into a BinaryOp, and return \c None on failure.
4580 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) {
4581   auto *Op = dyn_cast<Operator>(V);
4582   if (!Op)
4583     return None;
4584 
4585   // Implementation detail: all the cleverness here should happen without
4586   // creating new SCEV expressions -- our caller knowns tricks to avoid creating
4587   // SCEV expressions when possible, and we should not break that.
4588 
4589   switch (Op->getOpcode()) {
4590   case Instruction::Add:
4591   case Instruction::Sub:
4592   case Instruction::Mul:
4593   case Instruction::UDiv:
4594   case Instruction::URem:
4595   case Instruction::And:
4596   case Instruction::Or:
4597   case Instruction::AShr:
4598   case Instruction::Shl:
4599     return BinaryOp(Op);
4600 
4601   case Instruction::Xor:
4602     if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
4603       // If the RHS of the xor is a signmask, then this is just an add.
4604       // Instcombine turns add of signmask into xor as a strength reduction step.
4605       if (RHSC->getValue().isSignMask())
4606         return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
4607     return BinaryOp(Op);
4608 
4609   case Instruction::LShr:
4610     // Turn logical shift right of a constant into a unsigned divide.
4611     if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
4612       uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
4613 
4614       // If the shift count is not less than the bitwidth, the result of
4615       // the shift is undefined. Don't try to analyze it, because the
4616       // resolution chosen here may differ from the resolution chosen in
4617       // other parts of the compiler.
4618       if (SA->getValue().ult(BitWidth)) {
4619         Constant *X =
4620             ConstantInt::get(SA->getContext(),
4621                              APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
4622         return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
4623       }
4624     }
4625     return BinaryOp(Op);
4626 
4627   case Instruction::ExtractValue: {
4628     auto *EVI = cast<ExtractValueInst>(Op);
4629     if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
4630       break;
4631 
4632     auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand());
4633     if (!WO)
4634       break;
4635 
4636     Instruction::BinaryOps BinOp = WO->getBinaryOp();
4637     bool Signed = WO->isSigned();
4638     // TODO: Should add nuw/nsw flags for mul as well.
4639     if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT))
4640       return BinaryOp(BinOp, WO->getLHS(), WO->getRHS());
4641 
4642     // Now that we know that all uses of the arithmetic-result component of
4643     // CI are guarded by the overflow check, we can go ahead and pretend
4644     // that the arithmetic is non-overflowing.
4645     return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(),
4646                     /* IsNSW = */ Signed, /* IsNUW = */ !Signed);
4647   }
4648 
4649   default:
4650     break;
4651   }
4652 
4653   // Recognise intrinsic loop.decrement.reg, and as this has exactly the same
4654   // semantics as a Sub, return a binary sub expression.
4655   if (auto *II = dyn_cast<IntrinsicInst>(V))
4656     if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg)
4657       return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1));
4658 
4659   return None;
4660 }
4661 
4662 /// Helper function to createAddRecFromPHIWithCasts. We have a phi
4663 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
4664 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
4665 /// way. This function checks if \p Op, an operand of this SCEVAddExpr,
4666 /// follows one of the following patterns:
4667 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4668 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4669 /// If the SCEV expression of \p Op conforms with one of the expected patterns
4670 /// we return the type of the truncation operation, and indicate whether the
4671 /// truncated type should be treated as signed/unsigned by setting
4672 /// \p Signed to true/false, respectively.
4673 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
4674                                bool &Signed, ScalarEvolution &SE) {
4675   // The case where Op == SymbolicPHI (that is, with no type conversions on
4676   // the way) is handled by the regular add recurrence creating logic and
4677   // would have already been triggered in createAddRecForPHI. Reaching it here
4678   // means that createAddRecFromPHI had failed for this PHI before (e.g.,
4679   // because one of the other operands of the SCEVAddExpr updating this PHI is
4680   // not invariant).
4681   //
4682   // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
4683   // this case predicates that allow us to prove that Op == SymbolicPHI will
4684   // be added.
4685   if (Op == SymbolicPHI)
4686     return nullptr;
4687 
4688   unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
4689   unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
4690   if (SourceBits != NewBits)
4691     return nullptr;
4692 
4693   const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op);
4694   const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op);
4695   if (!SExt && !ZExt)
4696     return nullptr;
4697   const SCEVTruncateExpr *Trunc =
4698       SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand())
4699            : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand());
4700   if (!Trunc)
4701     return nullptr;
4702   const SCEV *X = Trunc->getOperand();
4703   if (X != SymbolicPHI)
4704     return nullptr;
4705   Signed = SExt != nullptr;
4706   return Trunc->getType();
4707 }
4708 
4709 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
4710   if (!PN->getType()->isIntegerTy())
4711     return nullptr;
4712   const Loop *L = LI.getLoopFor(PN->getParent());
4713   if (!L || L->getHeader() != PN->getParent())
4714     return nullptr;
4715   return L;
4716 }
4717 
4718 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
4719 // computation that updates the phi follows the following pattern:
4720 //   (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
4721 // which correspond to a phi->trunc->sext/zext->add->phi update chain.
4722 // If so, try to see if it can be rewritten as an AddRecExpr under some
4723 // Predicates. If successful, return them as a pair. Also cache the results
4724 // of the analysis.
4725 //
4726 // Example usage scenario:
4727 //    Say the Rewriter is called for the following SCEV:
4728 //         8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4729 //    where:
4730 //         %X = phi i64 (%Start, %BEValue)
4731 //    It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
4732 //    and call this function with %SymbolicPHI = %X.
4733 //
4734 //    The analysis will find that the value coming around the backedge has
4735 //    the following SCEV:
4736 //         BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4737 //    Upon concluding that this matches the desired pattern, the function
4738 //    will return the pair {NewAddRec, SmallPredsVec} where:
4739 //         NewAddRec = {%Start,+,%Step}
4740 //         SmallPredsVec = {P1, P2, P3} as follows:
4741 //           P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
4742 //           P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
4743 //           P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
4744 //    The returned pair means that SymbolicPHI can be rewritten into NewAddRec
4745 //    under the predicates {P1,P2,P3}.
4746 //    This predicated rewrite will be cached in PredicatedSCEVRewrites:
4747 //         PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
4748 //
4749 // TODO's:
4750 //
4751 // 1) Extend the Induction descriptor to also support inductions that involve
4752 //    casts: When needed (namely, when we are called in the context of the
4753 //    vectorizer induction analysis), a Set of cast instructions will be
4754 //    populated by this method, and provided back to isInductionPHI. This is
4755 //    needed to allow the vectorizer to properly record them to be ignored by
4756 //    the cost model and to avoid vectorizing them (otherwise these casts,
4757 //    which are redundant under the runtime overflow checks, will be
4758 //    vectorized, which can be costly).
4759 //
4760 // 2) Support additional induction/PHISCEV patterns: We also want to support
4761 //    inductions where the sext-trunc / zext-trunc operations (partly) occur
4762 //    after the induction update operation (the induction increment):
4763 //
4764 //      (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
4765 //    which correspond to a phi->add->trunc->sext/zext->phi update chain.
4766 //
4767 //      (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
4768 //    which correspond to a phi->trunc->add->sext/zext->phi update chain.
4769 //
4770 // 3) Outline common code with createAddRecFromPHI to avoid duplication.
4771 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4772 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
4773   SmallVector<const SCEVPredicate *, 3> Predicates;
4774 
4775   // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
4776   // return an AddRec expression under some predicate.
4777 
4778   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
4779   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
4780   assert(L && "Expecting an integer loop header phi");
4781 
4782   // The loop may have multiple entrances or multiple exits; we can analyze
4783   // this phi as an addrec if it has a unique entry value and a unique
4784   // backedge value.
4785   Value *BEValueV = nullptr, *StartValueV = nullptr;
4786   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4787     Value *V = PN->getIncomingValue(i);
4788     if (L->contains(PN->getIncomingBlock(i))) {
4789       if (!BEValueV) {
4790         BEValueV = V;
4791       } else if (BEValueV != V) {
4792         BEValueV = nullptr;
4793         break;
4794       }
4795     } else if (!StartValueV) {
4796       StartValueV = V;
4797     } else if (StartValueV != V) {
4798       StartValueV = nullptr;
4799       break;
4800     }
4801   }
4802   if (!BEValueV || !StartValueV)
4803     return None;
4804 
4805   const SCEV *BEValue = getSCEV(BEValueV);
4806 
4807   // If the value coming around the backedge is an add with the symbolic
4808   // value we just inserted, possibly with casts that we can ignore under
4809   // an appropriate runtime guard, then we found a simple induction variable!
4810   const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
4811   if (!Add)
4812     return None;
4813 
4814   // If there is a single occurrence of the symbolic value, possibly
4815   // casted, replace it with a recurrence.
4816   unsigned FoundIndex = Add->getNumOperands();
4817   Type *TruncTy = nullptr;
4818   bool Signed;
4819   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4820     if ((TruncTy =
4821              isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
4822       if (FoundIndex == e) {
4823         FoundIndex = i;
4824         break;
4825       }
4826 
4827   if (FoundIndex == Add->getNumOperands())
4828     return None;
4829 
4830   // Create an add with everything but the specified operand.
4831   SmallVector<const SCEV *, 8> Ops;
4832   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4833     if (i != FoundIndex)
4834       Ops.push_back(Add->getOperand(i));
4835   const SCEV *Accum = getAddExpr(Ops);
4836 
4837   // The runtime checks will not be valid if the step amount is
4838   // varying inside the loop.
4839   if (!isLoopInvariant(Accum, L))
4840     return None;
4841 
4842   // *** Part2: Create the predicates
4843 
4844   // Analysis was successful: we have a phi-with-cast pattern for which we
4845   // can return an AddRec expression under the following predicates:
4846   //
4847   // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
4848   //     fits within the truncated type (does not overflow) for i = 0 to n-1.
4849   // P2: An Equal predicate that guarantees that
4850   //     Start = (Ext ix (Trunc iy (Start) to ix) to iy)
4851   // P3: An Equal predicate that guarantees that
4852   //     Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
4853   //
4854   // As we next prove, the above predicates guarantee that:
4855   //     Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
4856   //
4857   //
4858   // More formally, we want to prove that:
4859   //     Expr(i+1) = Start + (i+1) * Accum
4860   //               = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4861   //
4862   // Given that:
4863   // 1) Expr(0) = Start
4864   // 2) Expr(1) = Start + Accum
4865   //            = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
4866   // 3) Induction hypothesis (step i):
4867   //    Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
4868   //
4869   // Proof:
4870   //  Expr(i+1) =
4871   //   = Start + (i+1)*Accum
4872   //   = (Start + i*Accum) + Accum
4873   //   = Expr(i) + Accum
4874   //   = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
4875   //                                                             :: from step i
4876   //
4877   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
4878   //
4879   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
4880   //     + (Ext ix (Trunc iy (Accum) to ix) to iy)
4881   //     + Accum                                                     :: from P3
4882   //
4883   //   = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
4884   //     + Accum                            :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
4885   //
4886   //   = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
4887   //   = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4888   //
4889   // By induction, the same applies to all iterations 1<=i<n:
4890   //
4891 
4892   // Create a truncated addrec for which we will add a no overflow check (P1).
4893   const SCEV *StartVal = getSCEV(StartValueV);
4894   const SCEV *PHISCEV =
4895       getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
4896                     getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap);
4897 
4898   // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
4899   // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
4900   // will be constant.
4901   //
4902   //  If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
4903   // add P1.
4904   if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
4905     SCEVWrapPredicate::IncrementWrapFlags AddedFlags =
4906         Signed ? SCEVWrapPredicate::IncrementNSSW
4907                : SCEVWrapPredicate::IncrementNUSW;
4908     const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
4909     Predicates.push_back(AddRecPred);
4910   }
4911 
4912   // Create the Equal Predicates P2,P3:
4913 
4914   // It is possible that the predicates P2 and/or P3 are computable at
4915   // compile time due to StartVal and/or Accum being constants.
4916   // If either one is, then we can check that now and escape if either P2
4917   // or P3 is false.
4918 
4919   // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
4920   // for each of StartVal and Accum
4921   auto getExtendedExpr = [&](const SCEV *Expr,
4922                              bool CreateSignExtend) -> const SCEV * {
4923     assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant");
4924     const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
4925     const SCEV *ExtendedExpr =
4926         CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType())
4927                          : getZeroExtendExpr(TruncatedExpr, Expr->getType());
4928     return ExtendedExpr;
4929   };
4930 
4931   // Given:
4932   //  ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
4933   //               = getExtendedExpr(Expr)
4934   // Determine whether the predicate P: Expr == ExtendedExpr
4935   // is known to be false at compile time
4936   auto PredIsKnownFalse = [&](const SCEV *Expr,
4937                               const SCEV *ExtendedExpr) -> bool {
4938     return Expr != ExtendedExpr &&
4939            isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr);
4940   };
4941 
4942   const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
4943   if (PredIsKnownFalse(StartVal, StartExtended)) {
4944     LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";);
4945     return None;
4946   }
4947 
4948   // The Step is always Signed (because the overflow checks are either
4949   // NSSW or NUSW)
4950   const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true);
4951   if (PredIsKnownFalse(Accum, AccumExtended)) {
4952     LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";);
4953     return None;
4954   }
4955 
4956   auto AppendPredicate = [&](const SCEV *Expr,
4957                              const SCEV *ExtendedExpr) -> void {
4958     if (Expr != ExtendedExpr &&
4959         !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
4960       const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
4961       LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred);
4962       Predicates.push_back(Pred);
4963     }
4964   };
4965 
4966   AppendPredicate(StartVal, StartExtended);
4967   AppendPredicate(Accum, AccumExtended);
4968 
4969   // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
4970   // which the casts had been folded away. The caller can rewrite SymbolicPHI
4971   // into NewAR if it will also add the runtime overflow checks specified in
4972   // Predicates.
4973   auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap);
4974 
4975   std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
4976       std::make_pair(NewAR, Predicates);
4977   // Remember the result of the analysis for this SCEV at this locayyytion.
4978   PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
4979   return PredRewrite;
4980 }
4981 
4982 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4983 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) {
4984   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
4985   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
4986   if (!L)
4987     return None;
4988 
4989   // Check to see if we already analyzed this PHI.
4990   auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
4991   if (I != PredicatedSCEVRewrites.end()) {
4992     std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
4993         I->second;
4994     // Analysis was done before and failed to create an AddRec:
4995     if (Rewrite.first == SymbolicPHI)
4996       return None;
4997     // Analysis was done before and succeeded to create an AddRec under
4998     // a predicate:
4999     assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec");
5000     assert(!(Rewrite.second).empty() && "Expected to find Predicates");
5001     return Rewrite;
5002   }
5003 
5004   Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5005     Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
5006 
5007   // Record in the cache that the analysis failed
5008   if (!Rewrite) {
5009     SmallVector<const SCEVPredicate *, 3> Predicates;
5010     PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
5011     return None;
5012   }
5013 
5014   return Rewrite;
5015 }
5016 
5017 // FIXME: This utility is currently required because the Rewriter currently
5018 // does not rewrite this expression:
5019 // {0, +, (sext ix (trunc iy to ix) to iy)}
5020 // into {0, +, %step},
5021 // even when the following Equal predicate exists:
5022 // "%step == (sext ix (trunc iy to ix) to iy)".
5023 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds(
5024     const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const {
5025   if (AR1 == AR2)
5026     return true;
5027 
5028   auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool {
5029     if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) &&
5030         !Preds.implies(SE.getEqualPredicate(Expr2, Expr1)))
5031       return false;
5032     return true;
5033   };
5034 
5035   if (!areExprsEqual(AR1->getStart(), AR2->getStart()) ||
5036       !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE)))
5037     return false;
5038   return true;
5039 }
5040 
5041 /// A helper function for createAddRecFromPHI to handle simple cases.
5042 ///
5043 /// This function tries to find an AddRec expression for the simplest (yet most
5044 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
5045 /// If it fails, createAddRecFromPHI will use a more general, but slow,
5046 /// technique for finding the AddRec expression.
5047 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
5048                                                       Value *BEValueV,
5049                                                       Value *StartValueV) {
5050   const Loop *L = LI.getLoopFor(PN->getParent());
5051   assert(L && L->getHeader() == PN->getParent());
5052   assert(BEValueV && StartValueV);
5053 
5054   auto BO = MatchBinaryOp(BEValueV, DT);
5055   if (!BO)
5056     return nullptr;
5057 
5058   if (BO->Opcode != Instruction::Add)
5059     return nullptr;
5060 
5061   const SCEV *Accum = nullptr;
5062   if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
5063     Accum = getSCEV(BO->RHS);
5064   else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
5065     Accum = getSCEV(BO->LHS);
5066 
5067   if (!Accum)
5068     return nullptr;
5069 
5070   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5071   if (BO->IsNUW)
5072     Flags = setFlags(Flags, SCEV::FlagNUW);
5073   if (BO->IsNSW)
5074     Flags = setFlags(Flags, SCEV::FlagNSW);
5075 
5076   const SCEV *StartVal = getSCEV(StartValueV);
5077   const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5078 
5079   ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
5080 
5081   // We can add Flags to the post-inc expression only if we
5082   // know that it is *undefined behavior* for BEValueV to
5083   // overflow.
5084   if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5085     if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5086       (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5087 
5088   return PHISCEV;
5089 }
5090 
5091 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
5092   const Loop *L = LI.getLoopFor(PN->getParent());
5093   if (!L || L->getHeader() != PN->getParent())
5094     return nullptr;
5095 
5096   // The loop may have multiple entrances or multiple exits; we can analyze
5097   // this phi as an addrec if it has a unique entry value and a unique
5098   // backedge value.
5099   Value *BEValueV = nullptr, *StartValueV = nullptr;
5100   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5101     Value *V = PN->getIncomingValue(i);
5102     if (L->contains(PN->getIncomingBlock(i))) {
5103       if (!BEValueV) {
5104         BEValueV = V;
5105       } else if (BEValueV != V) {
5106         BEValueV = nullptr;
5107         break;
5108       }
5109     } else if (!StartValueV) {
5110       StartValueV = V;
5111     } else if (StartValueV != V) {
5112       StartValueV = nullptr;
5113       break;
5114     }
5115   }
5116   if (!BEValueV || !StartValueV)
5117     return nullptr;
5118 
5119   assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
5120          "PHI node already processed?");
5121 
5122   // First, try to find AddRec expression without creating a fictituos symbolic
5123   // value for PN.
5124   if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
5125     return S;
5126 
5127   // Handle PHI node value symbolically.
5128   const SCEV *SymbolicName = getUnknown(PN);
5129   ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName});
5130 
5131   // Using this symbolic name for the PHI, analyze the value coming around
5132   // the back-edge.
5133   const SCEV *BEValue = getSCEV(BEValueV);
5134 
5135   // NOTE: If BEValue is loop invariant, we know that the PHI node just
5136   // has a special value for the first iteration of the loop.
5137 
5138   // If the value coming around the backedge is an add with the symbolic
5139   // value we just inserted, then we found a simple induction variable!
5140   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
5141     // If there is a single occurrence of the symbolic value, replace it
5142     // with a recurrence.
5143     unsigned FoundIndex = Add->getNumOperands();
5144     for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5145       if (Add->getOperand(i) == SymbolicName)
5146         if (FoundIndex == e) {
5147           FoundIndex = i;
5148           break;
5149         }
5150 
5151     if (FoundIndex != Add->getNumOperands()) {
5152       // Create an add with everything but the specified operand.
5153       SmallVector<const SCEV *, 8> Ops;
5154       for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5155         if (i != FoundIndex)
5156           Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i),
5157                                                              L, *this));
5158       const SCEV *Accum = getAddExpr(Ops);
5159 
5160       // This is not a valid addrec if the step amount is varying each
5161       // loop iteration, but is not itself an addrec in this loop.
5162       if (isLoopInvariant(Accum, L) ||
5163           (isa<SCEVAddRecExpr>(Accum) &&
5164            cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
5165         SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5166 
5167         if (auto BO = MatchBinaryOp(BEValueV, DT)) {
5168           if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
5169             if (BO->IsNUW)
5170               Flags = setFlags(Flags, SCEV::FlagNUW);
5171             if (BO->IsNSW)
5172               Flags = setFlags(Flags, SCEV::FlagNSW);
5173           }
5174         } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
5175           // If the increment is an inbounds GEP, then we know the address
5176           // space cannot be wrapped around. We cannot make any guarantee
5177           // about signed or unsigned overflow because pointers are
5178           // unsigned but we may have a negative index from the base
5179           // pointer. We can guarantee that no unsigned wrap occurs if the
5180           // indices form a positive value.
5181           if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
5182             Flags = setFlags(Flags, SCEV::FlagNW);
5183 
5184             const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
5185             if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
5186               Flags = setFlags(Flags, SCEV::FlagNUW);
5187           }
5188 
5189           // We cannot transfer nuw and nsw flags from subtraction
5190           // operations -- sub nuw X, Y is not the same as add nuw X, -Y
5191           // for instance.
5192         }
5193 
5194         const SCEV *StartVal = getSCEV(StartValueV);
5195         const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5196 
5197         // Okay, for the entire analysis of this edge we assumed the PHI
5198         // to be symbolic.  We now need to go back and purge all of the
5199         // entries for the scalars that use the symbolic expression.
5200         forgetSymbolicName(PN, SymbolicName);
5201         ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
5202 
5203         // We can add Flags to the post-inc expression only if we
5204         // know that it is *undefined behavior* for BEValueV to
5205         // overflow.
5206         if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5207           if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5208             (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5209 
5210         return PHISCEV;
5211       }
5212     }
5213   } else {
5214     // Otherwise, this could be a loop like this:
5215     //     i = 0;  for (j = 1; ..; ++j) { ....  i = j; }
5216     // In this case, j = {1,+,1}  and BEValue is j.
5217     // Because the other in-value of i (0) fits the evolution of BEValue
5218     // i really is an addrec evolution.
5219     //
5220     // We can generalize this saying that i is the shifted value of BEValue
5221     // by one iteration:
5222     //   PHI(f(0), f({1,+,1})) --> f({0,+,1})
5223     const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
5224     const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false);
5225     if (Shifted != getCouldNotCompute() &&
5226         Start != getCouldNotCompute()) {
5227       const SCEV *StartVal = getSCEV(StartValueV);
5228       if (Start == StartVal) {
5229         // Okay, for the entire analysis of this edge we assumed the PHI
5230         // to be symbolic.  We now need to go back and purge all of the
5231         // entries for the scalars that use the symbolic expression.
5232         forgetSymbolicName(PN, SymbolicName);
5233         ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted;
5234         return Shifted;
5235       }
5236     }
5237   }
5238 
5239   // Remove the temporary PHI node SCEV that has been inserted while intending
5240   // to create an AddRecExpr for this PHI node. We can not keep this temporary
5241   // as it will prevent later (possibly simpler) SCEV expressions to be added
5242   // to the ValueExprMap.
5243   eraseValueFromMap(PN);
5244 
5245   return nullptr;
5246 }
5247 
5248 // Checks if the SCEV S is available at BB.  S is considered available at BB
5249 // if S can be materialized at BB without introducing a fault.
5250 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
5251                                BasicBlock *BB) {
5252   struct CheckAvailable {
5253     bool TraversalDone = false;
5254     bool Available = true;
5255 
5256     const Loop *L = nullptr;  // The loop BB is in (can be nullptr)
5257     BasicBlock *BB = nullptr;
5258     DominatorTree &DT;
5259 
5260     CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
5261       : L(L), BB(BB), DT(DT) {}
5262 
5263     bool setUnavailable() {
5264       TraversalDone = true;
5265       Available = false;
5266       return false;
5267     }
5268 
5269     bool follow(const SCEV *S) {
5270       switch (S->getSCEVType()) {
5271       case scConstant:
5272       case scPtrToInt:
5273       case scTruncate:
5274       case scZeroExtend:
5275       case scSignExtend:
5276       case scAddExpr:
5277       case scMulExpr:
5278       case scUMaxExpr:
5279       case scSMaxExpr:
5280       case scUMinExpr:
5281       case scSMinExpr:
5282         // These expressions are available if their operand(s) is/are.
5283         return true;
5284 
5285       case scAddRecExpr: {
5286         // We allow add recurrences that are on the loop BB is in, or some
5287         // outer loop.  This guarantees availability because the value of the
5288         // add recurrence at BB is simply the "current" value of the induction
5289         // variable.  We can relax this in the future; for instance an add
5290         // recurrence on a sibling dominating loop is also available at BB.
5291         const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
5292         if (L && (ARLoop == L || ARLoop->contains(L)))
5293           return true;
5294 
5295         return setUnavailable();
5296       }
5297 
5298       case scUnknown: {
5299         // For SCEVUnknown, we check for simple dominance.
5300         const auto *SU = cast<SCEVUnknown>(S);
5301         Value *V = SU->getValue();
5302 
5303         if (isa<Argument>(V))
5304           return false;
5305 
5306         if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
5307           return false;
5308 
5309         return setUnavailable();
5310       }
5311 
5312       case scUDivExpr:
5313       case scCouldNotCompute:
5314         // We do not try to smart about these at all.
5315         return setUnavailable();
5316       }
5317       llvm_unreachable("Unknown SCEV kind!");
5318     }
5319 
5320     bool isDone() { return TraversalDone; }
5321   };
5322 
5323   CheckAvailable CA(L, BB, DT);
5324   SCEVTraversal<CheckAvailable> ST(CA);
5325 
5326   ST.visitAll(S);
5327   return CA.Available;
5328 }
5329 
5330 // Try to match a control flow sequence that branches out at BI and merges back
5331 // at Merge into a "C ? LHS : RHS" select pattern.  Return true on a successful
5332 // match.
5333 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
5334                           Value *&C, Value *&LHS, Value *&RHS) {
5335   C = BI->getCondition();
5336 
5337   BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
5338   BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
5339 
5340   if (!LeftEdge.isSingleEdge())
5341     return false;
5342 
5343   assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
5344 
5345   Use &LeftUse = Merge->getOperandUse(0);
5346   Use &RightUse = Merge->getOperandUse(1);
5347 
5348   if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
5349     LHS = LeftUse;
5350     RHS = RightUse;
5351     return true;
5352   }
5353 
5354   if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
5355     LHS = RightUse;
5356     RHS = LeftUse;
5357     return true;
5358   }
5359 
5360   return false;
5361 }
5362 
5363 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
5364   auto IsReachable =
5365       [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
5366   if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
5367     const Loop *L = LI.getLoopFor(PN->getParent());
5368 
5369     // We don't want to break LCSSA, even in a SCEV expression tree.
5370     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
5371       if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
5372         return nullptr;
5373 
5374     // Try to match
5375     //
5376     //  br %cond, label %left, label %right
5377     // left:
5378     //  br label %merge
5379     // right:
5380     //  br label %merge
5381     // merge:
5382     //  V = phi [ %x, %left ], [ %y, %right ]
5383     //
5384     // as "select %cond, %x, %y"
5385 
5386     BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
5387     assert(IDom && "At least the entry block should dominate PN");
5388 
5389     auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
5390     Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
5391 
5392     if (BI && BI->isConditional() &&
5393         BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
5394         IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
5395         IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
5396       return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
5397   }
5398 
5399   return nullptr;
5400 }
5401 
5402 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
5403   if (const SCEV *S = createAddRecFromPHI(PN))
5404     return S;
5405 
5406   if (const SCEV *S = createNodeFromSelectLikePHI(PN))
5407     return S;
5408 
5409   // If the PHI has a single incoming value, follow that value, unless the
5410   // PHI's incoming blocks are in a different loop, in which case doing so
5411   // risks breaking LCSSA form. Instcombine would normally zap these, but
5412   // it doesn't have DominatorTree information, so it may miss cases.
5413   if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC}))
5414     if (LI.replacementPreservesLCSSAForm(PN, V))
5415       return getSCEV(V);
5416 
5417   // If it's not a loop phi, we can't handle it yet.
5418   return getUnknown(PN);
5419 }
5420 
5421 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I,
5422                                                       Value *Cond,
5423                                                       Value *TrueVal,
5424                                                       Value *FalseVal) {
5425   // Handle "constant" branch or select. This can occur for instance when a
5426   // loop pass transforms an inner loop and moves on to process the outer loop.
5427   if (auto *CI = dyn_cast<ConstantInt>(Cond))
5428     return getSCEV(CI->isOne() ? TrueVal : FalseVal);
5429 
5430   // Try to match some simple smax or umax patterns.
5431   auto *ICI = dyn_cast<ICmpInst>(Cond);
5432   if (!ICI)
5433     return getUnknown(I);
5434 
5435   Value *LHS = ICI->getOperand(0);
5436   Value *RHS = ICI->getOperand(1);
5437 
5438   switch (ICI->getPredicate()) {
5439   case ICmpInst::ICMP_SLT:
5440   case ICmpInst::ICMP_SLE:
5441     std::swap(LHS, RHS);
5442     LLVM_FALLTHROUGH;
5443   case ICmpInst::ICMP_SGT:
5444   case ICmpInst::ICMP_SGE:
5445     // a >s b ? a+x : b+x  ->  smax(a, b)+x
5446     // a >s b ? b+x : a+x  ->  smin(a, b)+x
5447     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5448       const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType());
5449       const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType());
5450       const SCEV *LA = getSCEV(TrueVal);
5451       const SCEV *RA = getSCEV(FalseVal);
5452       const SCEV *LDiff = getMinusSCEV(LA, LS);
5453       const SCEV *RDiff = getMinusSCEV(RA, RS);
5454       if (LDiff == RDiff)
5455         return getAddExpr(getSMaxExpr(LS, RS), LDiff);
5456       LDiff = getMinusSCEV(LA, RS);
5457       RDiff = getMinusSCEV(RA, LS);
5458       if (LDiff == RDiff)
5459         return getAddExpr(getSMinExpr(LS, RS), LDiff);
5460     }
5461     break;
5462   case ICmpInst::ICMP_ULT:
5463   case ICmpInst::ICMP_ULE:
5464     std::swap(LHS, RHS);
5465     LLVM_FALLTHROUGH;
5466   case ICmpInst::ICMP_UGT:
5467   case ICmpInst::ICMP_UGE:
5468     // a >u b ? a+x : b+x  ->  umax(a, b)+x
5469     // a >u b ? b+x : a+x  ->  umin(a, b)+x
5470     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5471       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5472       const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType());
5473       const SCEV *LA = getSCEV(TrueVal);
5474       const SCEV *RA = getSCEV(FalseVal);
5475       const SCEV *LDiff = getMinusSCEV(LA, LS);
5476       const SCEV *RDiff = getMinusSCEV(RA, RS);
5477       if (LDiff == RDiff)
5478         return getAddExpr(getUMaxExpr(LS, RS), LDiff);
5479       LDiff = getMinusSCEV(LA, RS);
5480       RDiff = getMinusSCEV(RA, LS);
5481       if (LDiff == RDiff)
5482         return getAddExpr(getUMinExpr(LS, RS), LDiff);
5483     }
5484     break;
5485   case ICmpInst::ICMP_NE:
5486     // n != 0 ? n+x : 1+x  ->  umax(n, 1)+x
5487     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5488         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5489       const SCEV *One = getOne(I->getType());
5490       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5491       const SCEV *LA = getSCEV(TrueVal);
5492       const SCEV *RA = getSCEV(FalseVal);
5493       const SCEV *LDiff = getMinusSCEV(LA, LS);
5494       const SCEV *RDiff = getMinusSCEV(RA, One);
5495       if (LDiff == RDiff)
5496         return getAddExpr(getUMaxExpr(One, LS), LDiff);
5497     }
5498     break;
5499   case ICmpInst::ICMP_EQ:
5500     // n == 0 ? 1+x : n+x  ->  umax(n, 1)+x
5501     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5502         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5503       const SCEV *One = getOne(I->getType());
5504       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5505       const SCEV *LA = getSCEV(TrueVal);
5506       const SCEV *RA = getSCEV(FalseVal);
5507       const SCEV *LDiff = getMinusSCEV(LA, One);
5508       const SCEV *RDiff = getMinusSCEV(RA, LS);
5509       if (LDiff == RDiff)
5510         return getAddExpr(getUMaxExpr(One, LS), LDiff);
5511     }
5512     break;
5513   default:
5514     break;
5515   }
5516 
5517   return getUnknown(I);
5518 }
5519 
5520 /// Expand GEP instructions into add and multiply operations. This allows them
5521 /// to be analyzed by regular SCEV code.
5522 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
5523   // Don't attempt to analyze GEPs over unsized objects.
5524   if (!GEP->getSourceElementType()->isSized())
5525     return getUnknown(GEP);
5526 
5527   SmallVector<const SCEV *, 4> IndexExprs;
5528   for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
5529     IndexExprs.push_back(getSCEV(*Index));
5530   return getGEPExpr(GEP, IndexExprs);
5531 }
5532 
5533 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) {
5534   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5535     return C->getAPInt().countTrailingZeros();
5536 
5537   if (const SCEVPtrToIntExpr *I = dyn_cast<SCEVPtrToIntExpr>(S))
5538     return GetMinTrailingZeros(I->getOperand());
5539 
5540   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
5541     return std::min(GetMinTrailingZeros(T->getOperand()),
5542                     (uint32_t)getTypeSizeInBits(T->getType()));
5543 
5544   if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
5545     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5546     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5547                ? getTypeSizeInBits(E->getType())
5548                : OpRes;
5549   }
5550 
5551   if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
5552     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5553     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5554                ? getTypeSizeInBits(E->getType())
5555                : OpRes;
5556   }
5557 
5558   if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
5559     // The result is the min of all operands results.
5560     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5561     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5562       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5563     return MinOpRes;
5564   }
5565 
5566   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
5567     // The result is the sum of all operands results.
5568     uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
5569     uint32_t BitWidth = getTypeSizeInBits(M->getType());
5570     for (unsigned i = 1, e = M->getNumOperands();
5571          SumOpRes != BitWidth && i != e; ++i)
5572       SumOpRes =
5573           std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth);
5574     return SumOpRes;
5575   }
5576 
5577   if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
5578     // The result is the min of all operands results.
5579     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5580     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5581       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5582     return MinOpRes;
5583   }
5584 
5585   if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
5586     // The result is the min of all operands results.
5587     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5588     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5589       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5590     return MinOpRes;
5591   }
5592 
5593   if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
5594     // The result is the min of all operands results.
5595     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5596     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5597       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5598     return MinOpRes;
5599   }
5600 
5601   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5602     // For a SCEVUnknown, ask ValueTracking.
5603     KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT);
5604     return Known.countMinTrailingZeros();
5605   }
5606 
5607   // SCEVUDivExpr
5608   return 0;
5609 }
5610 
5611 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
5612   auto I = MinTrailingZerosCache.find(S);
5613   if (I != MinTrailingZerosCache.end())
5614     return I->second;
5615 
5616   uint32_t Result = GetMinTrailingZerosImpl(S);
5617   auto InsertPair = MinTrailingZerosCache.insert({S, Result});
5618   assert(InsertPair.second && "Should insert a new key");
5619   return InsertPair.first->second;
5620 }
5621 
5622 /// Helper method to assign a range to V from metadata present in the IR.
5623 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
5624   if (Instruction *I = dyn_cast<Instruction>(V))
5625     if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
5626       return getConstantRangeFromMetadata(*MD);
5627 
5628   return None;
5629 }
5630 
5631 void ScalarEvolution::setNoWrapFlags(SCEVAddRecExpr *AddRec,
5632                                      SCEV::NoWrapFlags Flags) {
5633   if (AddRec->getNoWrapFlags(Flags) != Flags) {
5634     AddRec->setNoWrapFlags(Flags);
5635     UnsignedRanges.erase(AddRec);
5636     SignedRanges.erase(AddRec);
5637   }
5638 }
5639 
5640 /// Determine the range for a particular SCEV.  If SignHint is
5641 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
5642 /// with a "cleaner" unsigned (resp. signed) representation.
5643 const ConstantRange &
5644 ScalarEvolution::getRangeRef(const SCEV *S,
5645                              ScalarEvolution::RangeSignHint SignHint) {
5646   DenseMap<const SCEV *, ConstantRange> &Cache =
5647       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
5648                                                        : SignedRanges;
5649   ConstantRange::PreferredRangeType RangeType =
5650       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED
5651           ? ConstantRange::Unsigned : ConstantRange::Signed;
5652 
5653   // See if we've computed this range already.
5654   DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
5655   if (I != Cache.end())
5656     return I->second;
5657 
5658   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5659     return setRange(C, SignHint, ConstantRange(C->getAPInt()));
5660 
5661   unsigned BitWidth = getTypeSizeInBits(S->getType());
5662   ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
5663   using OBO = OverflowingBinaryOperator;
5664 
5665   // If the value has known zeros, the maximum value will have those known zeros
5666   // as well.
5667   uint32_t TZ = GetMinTrailingZeros(S);
5668   if (TZ != 0) {
5669     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
5670       ConservativeResult =
5671           ConstantRange(APInt::getMinValue(BitWidth),
5672                         APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
5673     else
5674       ConservativeResult = ConstantRange(
5675           APInt::getSignedMinValue(BitWidth),
5676           APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
5677   }
5678 
5679   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
5680     ConstantRange X = getRangeRef(Add->getOperand(0), SignHint);
5681     unsigned WrapType = OBO::AnyWrap;
5682     if (Add->hasNoSignedWrap())
5683       WrapType |= OBO::NoSignedWrap;
5684     if (Add->hasNoUnsignedWrap())
5685       WrapType |= OBO::NoUnsignedWrap;
5686     for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
5687       X = X.addWithNoWrap(getRangeRef(Add->getOperand(i), SignHint),
5688                           WrapType, RangeType);
5689     return setRange(Add, SignHint,
5690                     ConservativeResult.intersectWith(X, RangeType));
5691   }
5692 
5693   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
5694     ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint);
5695     for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
5696       X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint));
5697     return setRange(Mul, SignHint,
5698                     ConservativeResult.intersectWith(X, RangeType));
5699   }
5700 
5701   if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
5702     ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint);
5703     for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
5704       X = X.smax(getRangeRef(SMax->getOperand(i), SignHint));
5705     return setRange(SMax, SignHint,
5706                     ConservativeResult.intersectWith(X, RangeType));
5707   }
5708 
5709   if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
5710     ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint);
5711     for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
5712       X = X.umax(getRangeRef(UMax->getOperand(i), SignHint));
5713     return setRange(UMax, SignHint,
5714                     ConservativeResult.intersectWith(X, RangeType));
5715   }
5716 
5717   if (const SCEVSMinExpr *SMin = dyn_cast<SCEVSMinExpr>(S)) {
5718     ConstantRange X = getRangeRef(SMin->getOperand(0), SignHint);
5719     for (unsigned i = 1, e = SMin->getNumOperands(); i != e; ++i)
5720       X = X.smin(getRangeRef(SMin->getOperand(i), SignHint));
5721     return setRange(SMin, SignHint,
5722                     ConservativeResult.intersectWith(X, RangeType));
5723   }
5724 
5725   if (const SCEVUMinExpr *UMin = dyn_cast<SCEVUMinExpr>(S)) {
5726     ConstantRange X = getRangeRef(UMin->getOperand(0), SignHint);
5727     for (unsigned i = 1, e = UMin->getNumOperands(); i != e; ++i)
5728       X = X.umin(getRangeRef(UMin->getOperand(i), SignHint));
5729     return setRange(UMin, SignHint,
5730                     ConservativeResult.intersectWith(X, RangeType));
5731   }
5732 
5733   if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
5734     ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint);
5735     ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint);
5736     return setRange(UDiv, SignHint,
5737                     ConservativeResult.intersectWith(X.udiv(Y), RangeType));
5738   }
5739 
5740   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
5741     ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint);
5742     return setRange(ZExt, SignHint,
5743                     ConservativeResult.intersectWith(X.zeroExtend(BitWidth),
5744                                                      RangeType));
5745   }
5746 
5747   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
5748     ConstantRange X = getRangeRef(SExt->getOperand(), SignHint);
5749     return setRange(SExt, SignHint,
5750                     ConservativeResult.intersectWith(X.signExtend(BitWidth),
5751                                                      RangeType));
5752   }
5753 
5754   if (const SCEVPtrToIntExpr *PtrToInt = dyn_cast<SCEVPtrToIntExpr>(S)) {
5755     ConstantRange X = getRangeRef(PtrToInt->getOperand(), SignHint);
5756     return setRange(PtrToInt, SignHint, X);
5757   }
5758 
5759   if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
5760     ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint);
5761     return setRange(Trunc, SignHint,
5762                     ConservativeResult.intersectWith(X.truncate(BitWidth),
5763                                                      RangeType));
5764   }
5765 
5766   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
5767     // If there's no unsigned wrap, the value will never be less than its
5768     // initial value.
5769     if (AddRec->hasNoUnsignedWrap()) {
5770       APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart());
5771       if (!UnsignedMinValue.isNullValue())
5772         ConservativeResult = ConservativeResult.intersectWith(
5773             ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType);
5774     }
5775 
5776     // If there's no signed wrap, and all the operands except initial value have
5777     // the same sign or zero, the value won't ever be:
5778     // 1: smaller than initial value if operands are non negative,
5779     // 2: bigger than initial value if operands are non positive.
5780     // For both cases, value can not cross signed min/max boundary.
5781     if (AddRec->hasNoSignedWrap()) {
5782       bool AllNonNeg = true;
5783       bool AllNonPos = true;
5784       for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) {
5785         if (!isKnownNonNegative(AddRec->getOperand(i)))
5786           AllNonNeg = false;
5787         if (!isKnownNonPositive(AddRec->getOperand(i)))
5788           AllNonPos = false;
5789       }
5790       if (AllNonNeg)
5791         ConservativeResult = ConservativeResult.intersectWith(
5792             ConstantRange::getNonEmpty(getSignedRangeMin(AddRec->getStart()),
5793                                        APInt::getSignedMinValue(BitWidth)),
5794             RangeType);
5795       else if (AllNonPos)
5796         ConservativeResult = ConservativeResult.intersectWith(
5797             ConstantRange::getNonEmpty(
5798                 APInt::getSignedMinValue(BitWidth),
5799                 getSignedRangeMax(AddRec->getStart()) + 1),
5800             RangeType);
5801     }
5802 
5803     // TODO: non-affine addrec
5804     if (AddRec->isAffine()) {
5805       const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(AddRec->getLoop());
5806       if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
5807           getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
5808         auto RangeFromAffine = getRangeForAffineAR(
5809             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
5810             BitWidth);
5811         ConservativeResult =
5812             ConservativeResult.intersectWith(RangeFromAffine, RangeType);
5813 
5814         auto RangeFromFactoring = getRangeViaFactoring(
5815             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
5816             BitWidth);
5817         ConservativeResult =
5818             ConservativeResult.intersectWith(RangeFromFactoring, RangeType);
5819       }
5820 
5821       // Now try symbolic BE count and more powerful methods.
5822       if (UseExpensiveRangeSharpening) {
5823         const SCEV *SymbolicMaxBECount =
5824             getSymbolicMaxBackedgeTakenCount(AddRec->getLoop());
5825         if (!isa<SCEVCouldNotCompute>(SymbolicMaxBECount) &&
5826             getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
5827             AddRec->hasNoSelfWrap()) {
5828           auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR(
5829               AddRec, SymbolicMaxBECount, BitWidth, SignHint);
5830           ConservativeResult =
5831               ConservativeResult.intersectWith(RangeFromAffineNew, RangeType);
5832         }
5833       }
5834     }
5835 
5836     return setRange(AddRec, SignHint, std::move(ConservativeResult));
5837   }
5838 
5839   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5840     // Check if the IR explicitly contains !range metadata.
5841     Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
5842     if (MDRange.hasValue())
5843       ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue(),
5844                                                             RangeType);
5845 
5846     // See if ValueTracking can give us a useful range.
5847     const DataLayout &DL = getDataLayout();
5848     KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
5849     if (Known.getBitWidth() != BitWidth)
5850       Known = Known.zextOrTrunc(BitWidth);
5851     // If Known does not result in full-set, intersect with it.
5852     if (Known.getMinValue() != Known.getMaxValue() + 1)
5853       ConservativeResult = ConservativeResult.intersectWith(
5854           ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1),
5855           RangeType);
5856 
5857     // ValueTracking may be able to compute a tighter result for the number of
5858     // sign bits than for the value of those sign bits.
5859     unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
5860     // If the pointer size is larger than the index size type, this can cause
5861     // NS to be larger than BitWidth. So compensate for this.
5862     if (U->getType()->isPointerTy()) {
5863       unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType());
5864       int ptrIdxDiff = ptrSize - BitWidth;
5865       if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff)
5866         NS -= ptrIdxDiff;
5867     }
5868 
5869     if (NS > 1)
5870       ConservativeResult = ConservativeResult.intersectWith(
5871           ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
5872                         APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1),
5873           RangeType);
5874 
5875     // A range of Phi is a subset of union of all ranges of its input.
5876     if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) {
5877       // Make sure that we do not run over cycled Phis.
5878       if (PendingPhiRanges.insert(Phi).second) {
5879         ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false);
5880         for (auto &Op : Phi->operands()) {
5881           auto OpRange = getRangeRef(getSCEV(Op), SignHint);
5882           RangeFromOps = RangeFromOps.unionWith(OpRange);
5883           // No point to continue if we already have a full set.
5884           if (RangeFromOps.isFullSet())
5885             break;
5886         }
5887         ConservativeResult =
5888             ConservativeResult.intersectWith(RangeFromOps, RangeType);
5889         bool Erased = PendingPhiRanges.erase(Phi);
5890         assert(Erased && "Failed to erase Phi properly?");
5891         (void) Erased;
5892       }
5893     }
5894 
5895     return setRange(U, SignHint, std::move(ConservativeResult));
5896   }
5897 
5898   return setRange(S, SignHint, std::move(ConservativeResult));
5899 }
5900 
5901 // Given a StartRange, Step and MaxBECount for an expression compute a range of
5902 // values that the expression can take. Initially, the expression has a value
5903 // from StartRange and then is changed by Step up to MaxBECount times. Signed
5904 // argument defines if we treat Step as signed or unsigned.
5905 static ConstantRange getRangeForAffineARHelper(APInt Step,
5906                                                const ConstantRange &StartRange,
5907                                                const APInt &MaxBECount,
5908                                                unsigned BitWidth, bool Signed) {
5909   // If either Step or MaxBECount is 0, then the expression won't change, and we
5910   // just need to return the initial range.
5911   if (Step == 0 || MaxBECount == 0)
5912     return StartRange;
5913 
5914   // If we don't know anything about the initial value (i.e. StartRange is
5915   // FullRange), then we don't know anything about the final range either.
5916   // Return FullRange.
5917   if (StartRange.isFullSet())
5918     return ConstantRange::getFull(BitWidth);
5919 
5920   // If Step is signed and negative, then we use its absolute value, but we also
5921   // note that we're moving in the opposite direction.
5922   bool Descending = Signed && Step.isNegative();
5923 
5924   if (Signed)
5925     // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
5926     // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
5927     // This equations hold true due to the well-defined wrap-around behavior of
5928     // APInt.
5929     Step = Step.abs();
5930 
5931   // Check if Offset is more than full span of BitWidth. If it is, the
5932   // expression is guaranteed to overflow.
5933   if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
5934     return ConstantRange::getFull(BitWidth);
5935 
5936   // Offset is by how much the expression can change. Checks above guarantee no
5937   // overflow here.
5938   APInt Offset = Step * MaxBECount;
5939 
5940   // Minimum value of the final range will match the minimal value of StartRange
5941   // if the expression is increasing and will be decreased by Offset otherwise.
5942   // Maximum value of the final range will match the maximal value of StartRange
5943   // if the expression is decreasing and will be increased by Offset otherwise.
5944   APInt StartLower = StartRange.getLower();
5945   APInt StartUpper = StartRange.getUpper() - 1;
5946   APInt MovedBoundary = Descending ? (StartLower - std::move(Offset))
5947                                    : (StartUpper + std::move(Offset));
5948 
5949   // It's possible that the new minimum/maximum value will fall into the initial
5950   // range (due to wrap around). This means that the expression can take any
5951   // value in this bitwidth, and we have to return full range.
5952   if (StartRange.contains(MovedBoundary))
5953     return ConstantRange::getFull(BitWidth);
5954 
5955   APInt NewLower =
5956       Descending ? std::move(MovedBoundary) : std::move(StartLower);
5957   APInt NewUpper =
5958       Descending ? std::move(StartUpper) : std::move(MovedBoundary);
5959   NewUpper += 1;
5960 
5961   // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
5962   return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper));
5963 }
5964 
5965 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
5966                                                    const SCEV *Step,
5967                                                    const SCEV *MaxBECount,
5968                                                    unsigned BitWidth) {
5969   assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&
5970          getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
5971          "Precondition!");
5972 
5973   MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType());
5974   APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount);
5975 
5976   // First, consider step signed.
5977   ConstantRange StartSRange = getSignedRange(Start);
5978   ConstantRange StepSRange = getSignedRange(Step);
5979 
5980   // If Step can be both positive and negative, we need to find ranges for the
5981   // maximum absolute step values in both directions and union them.
5982   ConstantRange SR =
5983       getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange,
5984                                 MaxBECountValue, BitWidth, /* Signed = */ true);
5985   SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(),
5986                                               StartSRange, MaxBECountValue,
5987                                               BitWidth, /* Signed = */ true));
5988 
5989   // Next, consider step unsigned.
5990   ConstantRange UR = getRangeForAffineARHelper(
5991       getUnsignedRangeMax(Step), getUnsignedRange(Start),
5992       MaxBECountValue, BitWidth, /* Signed = */ false);
5993 
5994   // Finally, intersect signed and unsigned ranges.
5995   return SR.intersectWith(UR, ConstantRange::Smallest);
5996 }
5997 
5998 ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR(
5999     const SCEVAddRecExpr *AddRec, const SCEV *MaxBECount, unsigned BitWidth,
6000     ScalarEvolution::RangeSignHint SignHint) {
6001   assert(AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n");
6002   assert(AddRec->hasNoSelfWrap() &&
6003          "This only works for non-self-wrapping AddRecs!");
6004   const bool IsSigned = SignHint == HINT_RANGE_SIGNED;
6005   const SCEV *Step = AddRec->getStepRecurrence(*this);
6006   // Only deal with constant step to save compile time.
6007   if (!isa<SCEVConstant>(Step))
6008     return ConstantRange::getFull(BitWidth);
6009   // Let's make sure that we can prove that we do not self-wrap during
6010   // MaxBECount iterations. We need this because MaxBECount is a maximum
6011   // iteration count estimate, and we might infer nw from some exit for which we
6012   // do not know max exit count (or any other side reasoning).
6013   // TODO: Turn into assert at some point.
6014   if (getTypeSizeInBits(MaxBECount->getType()) >
6015       getTypeSizeInBits(AddRec->getType()))
6016     return ConstantRange::getFull(BitWidth);
6017   MaxBECount = getNoopOrZeroExtend(MaxBECount, AddRec->getType());
6018   const SCEV *RangeWidth = getMinusOne(AddRec->getType());
6019   const SCEV *StepAbs = getUMinExpr(Step, getNegativeSCEV(Step));
6020   const SCEV *MaxItersWithoutWrap = getUDivExpr(RangeWidth, StepAbs);
6021   if (!isKnownPredicateViaConstantRanges(ICmpInst::ICMP_ULE, MaxBECount,
6022                                          MaxItersWithoutWrap))
6023     return ConstantRange::getFull(BitWidth);
6024 
6025   ICmpInst::Predicate LEPred =
6026       IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
6027   ICmpInst::Predicate GEPred =
6028       IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
6029   const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
6030 
6031   // We know that there is no self-wrap. Let's take Start and End values and
6032   // look at all intermediate values V1, V2, ..., Vn that IndVar takes during
6033   // the iteration. They either lie inside the range [Min(Start, End),
6034   // Max(Start, End)] or outside it:
6035   //
6036   // Case 1:   RangeMin    ...    Start V1 ... VN End ...           RangeMax;
6037   // Case 2:   RangeMin Vk ... V1 Start    ...    End Vn ... Vk + 1 RangeMax;
6038   //
6039   // No self wrap flag guarantees that the intermediate values cannot be BOTH
6040   // outside and inside the range [Min(Start, End), Max(Start, End)]. Using that
6041   // knowledge, let's try to prove that we are dealing with Case 1. It is so if
6042   // Start <= End and step is positive, or Start >= End and step is negative.
6043   const SCEV *Start = AddRec->getStart();
6044   ConstantRange StartRange = getRangeRef(Start, SignHint);
6045   ConstantRange EndRange = getRangeRef(End, SignHint);
6046   ConstantRange RangeBetween = StartRange.unionWith(EndRange);
6047   // If they already cover full iteration space, we will know nothing useful
6048   // even if we prove what we want to prove.
6049   if (RangeBetween.isFullSet())
6050     return RangeBetween;
6051   // Only deal with ranges that do not wrap (i.e. RangeMin < RangeMax).
6052   bool IsWrappedSet = IsSigned ? RangeBetween.isSignWrappedSet()
6053                                : RangeBetween.isWrappedSet();
6054   if (IsWrappedSet)
6055     return ConstantRange::getFull(BitWidth);
6056 
6057   if (isKnownPositive(Step) &&
6058       isKnownPredicateViaConstantRanges(LEPred, Start, End))
6059     return RangeBetween;
6060   else if (isKnownNegative(Step) &&
6061            isKnownPredicateViaConstantRanges(GEPred, Start, End))
6062     return RangeBetween;
6063   return ConstantRange::getFull(BitWidth);
6064 }
6065 
6066 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
6067                                                     const SCEV *Step,
6068                                                     const SCEV *MaxBECount,
6069                                                     unsigned BitWidth) {
6070   //    RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
6071   // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
6072 
6073   struct SelectPattern {
6074     Value *Condition = nullptr;
6075     APInt TrueValue;
6076     APInt FalseValue;
6077 
6078     explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
6079                            const SCEV *S) {
6080       Optional<unsigned> CastOp;
6081       APInt Offset(BitWidth, 0);
6082 
6083       assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&
6084              "Should be!");
6085 
6086       // Peel off a constant offset:
6087       if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
6088         // In the future we could consider being smarter here and handle
6089         // {Start+Step,+,Step} too.
6090         if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
6091           return;
6092 
6093         Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
6094         S = SA->getOperand(1);
6095       }
6096 
6097       // Peel off a cast operation
6098       if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) {
6099         CastOp = SCast->getSCEVType();
6100         S = SCast->getOperand();
6101       }
6102 
6103       using namespace llvm::PatternMatch;
6104 
6105       auto *SU = dyn_cast<SCEVUnknown>(S);
6106       const APInt *TrueVal, *FalseVal;
6107       if (!SU ||
6108           !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
6109                                           m_APInt(FalseVal)))) {
6110         Condition = nullptr;
6111         return;
6112       }
6113 
6114       TrueValue = *TrueVal;
6115       FalseValue = *FalseVal;
6116 
6117       // Re-apply the cast we peeled off earlier
6118       if (CastOp.hasValue())
6119         switch (*CastOp) {
6120         default:
6121           llvm_unreachable("Unknown SCEV cast type!");
6122 
6123         case scTruncate:
6124           TrueValue = TrueValue.trunc(BitWidth);
6125           FalseValue = FalseValue.trunc(BitWidth);
6126           break;
6127         case scZeroExtend:
6128           TrueValue = TrueValue.zext(BitWidth);
6129           FalseValue = FalseValue.zext(BitWidth);
6130           break;
6131         case scSignExtend:
6132           TrueValue = TrueValue.sext(BitWidth);
6133           FalseValue = FalseValue.sext(BitWidth);
6134           break;
6135         }
6136 
6137       // Re-apply the constant offset we peeled off earlier
6138       TrueValue += Offset;
6139       FalseValue += Offset;
6140     }
6141 
6142     bool isRecognized() { return Condition != nullptr; }
6143   };
6144 
6145   SelectPattern StartPattern(*this, BitWidth, Start);
6146   if (!StartPattern.isRecognized())
6147     return ConstantRange::getFull(BitWidth);
6148 
6149   SelectPattern StepPattern(*this, BitWidth, Step);
6150   if (!StepPattern.isRecognized())
6151     return ConstantRange::getFull(BitWidth);
6152 
6153   if (StartPattern.Condition != StepPattern.Condition) {
6154     // We don't handle this case today; but we could, by considering four
6155     // possibilities below instead of two. I'm not sure if there are cases where
6156     // that will help over what getRange already does, though.
6157     return ConstantRange::getFull(BitWidth);
6158   }
6159 
6160   // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
6161   // construct arbitrary general SCEV expressions here.  This function is called
6162   // from deep in the call stack, and calling getSCEV (on a sext instruction,
6163   // say) can end up caching a suboptimal value.
6164 
6165   // FIXME: without the explicit `this` receiver below, MSVC errors out with
6166   // C2352 and C2512 (otherwise it isn't needed).
6167 
6168   const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
6169   const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
6170   const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
6171   const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
6172 
6173   ConstantRange TrueRange =
6174       this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
6175   ConstantRange FalseRange =
6176       this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
6177 
6178   return TrueRange.unionWith(FalseRange);
6179 }
6180 
6181 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
6182   if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
6183   const BinaryOperator *BinOp = cast<BinaryOperator>(V);
6184 
6185   // Return early if there are no flags to propagate to the SCEV.
6186   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
6187   if (BinOp->hasNoUnsignedWrap())
6188     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
6189   if (BinOp->hasNoSignedWrap())
6190     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
6191   if (Flags == SCEV::FlagAnyWrap)
6192     return SCEV::FlagAnyWrap;
6193 
6194   return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
6195 }
6196 
6197 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
6198   // Here we check that I is in the header of the innermost loop containing I,
6199   // since we only deal with instructions in the loop header. The actual loop we
6200   // need to check later will come from an add recurrence, but getting that
6201   // requires computing the SCEV of the operands, which can be expensive. This
6202   // check we can do cheaply to rule out some cases early.
6203   Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent());
6204   if (InnermostContainingLoop == nullptr ||
6205       InnermostContainingLoop->getHeader() != I->getParent())
6206     return false;
6207 
6208   // Only proceed if we can prove that I does not yield poison.
6209   if (!programUndefinedIfPoison(I))
6210     return false;
6211 
6212   // At this point we know that if I is executed, then it does not wrap
6213   // according to at least one of NSW or NUW. If I is not executed, then we do
6214   // not know if the calculation that I represents would wrap. Multiple
6215   // instructions can map to the same SCEV. If we apply NSW or NUW from I to
6216   // the SCEV, we must guarantee no wrapping for that SCEV also when it is
6217   // derived from other instructions that map to the same SCEV. We cannot make
6218   // that guarantee for cases where I is not executed. So we need to find the
6219   // loop that I is considered in relation to and prove that I is executed for
6220   // every iteration of that loop. That implies that the value that I
6221   // calculates does not wrap anywhere in the loop, so then we can apply the
6222   // flags to the SCEV.
6223   //
6224   // We check isLoopInvariant to disambiguate in case we are adding recurrences
6225   // from different loops, so that we know which loop to prove that I is
6226   // executed in.
6227   for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) {
6228     // I could be an extractvalue from a call to an overflow intrinsic.
6229     // TODO: We can do better here in some cases.
6230     if (!isSCEVable(I->getOperand(OpIndex)->getType()))
6231       return false;
6232     const SCEV *Op = getSCEV(I->getOperand(OpIndex));
6233     if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
6234       bool AllOtherOpsLoopInvariant = true;
6235       for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands();
6236            ++OtherOpIndex) {
6237         if (OtherOpIndex != OpIndex) {
6238           const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex));
6239           if (!isLoopInvariant(OtherOp, AddRec->getLoop())) {
6240             AllOtherOpsLoopInvariant = false;
6241             break;
6242           }
6243         }
6244       }
6245       if (AllOtherOpsLoopInvariant &&
6246           isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop()))
6247         return true;
6248     }
6249   }
6250   return false;
6251 }
6252 
6253 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
6254   // If we know that \c I can never be poison period, then that's enough.
6255   if (isSCEVExprNeverPoison(I))
6256     return true;
6257 
6258   // For an add recurrence specifically, we assume that infinite loops without
6259   // side effects are undefined behavior, and then reason as follows:
6260   //
6261   // If the add recurrence is poison in any iteration, it is poison on all
6262   // future iterations (since incrementing poison yields poison). If the result
6263   // of the add recurrence is fed into the loop latch condition and the loop
6264   // does not contain any throws or exiting blocks other than the latch, we now
6265   // have the ability to "choose" whether the backedge is taken or not (by
6266   // choosing a sufficiently evil value for the poison feeding into the branch)
6267   // for every iteration including and after the one in which \p I first became
6268   // poison.  There are two possibilities (let's call the iteration in which \p
6269   // I first became poison as K):
6270   //
6271   //  1. In the set of iterations including and after K, the loop body executes
6272   //     no side effects.  In this case executing the backege an infinte number
6273   //     of times will yield undefined behavior.
6274   //
6275   //  2. In the set of iterations including and after K, the loop body executes
6276   //     at least one side effect.  In this case, that specific instance of side
6277   //     effect is control dependent on poison, which also yields undefined
6278   //     behavior.
6279 
6280   auto *ExitingBB = L->getExitingBlock();
6281   auto *LatchBB = L->getLoopLatch();
6282   if (!ExitingBB || !LatchBB || ExitingBB != LatchBB)
6283     return false;
6284 
6285   SmallPtrSet<const Instruction *, 16> Pushed;
6286   SmallVector<const Instruction *, 8> PoisonStack;
6287 
6288   // We start by assuming \c I, the post-inc add recurrence, is poison.  Only
6289   // things that are known to be poison under that assumption go on the
6290   // PoisonStack.
6291   Pushed.insert(I);
6292   PoisonStack.push_back(I);
6293 
6294   bool LatchControlDependentOnPoison = false;
6295   while (!PoisonStack.empty() && !LatchControlDependentOnPoison) {
6296     const Instruction *Poison = PoisonStack.pop_back_val();
6297 
6298     for (auto *PoisonUser : Poison->users()) {
6299       if (propagatesPoison(cast<Operator>(PoisonUser))) {
6300         if (Pushed.insert(cast<Instruction>(PoisonUser)).second)
6301           PoisonStack.push_back(cast<Instruction>(PoisonUser));
6302       } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) {
6303         assert(BI->isConditional() && "Only possibility!");
6304         if (BI->getParent() == LatchBB) {
6305           LatchControlDependentOnPoison = true;
6306           break;
6307         }
6308       }
6309     }
6310   }
6311 
6312   return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L);
6313 }
6314 
6315 ScalarEvolution::LoopProperties
6316 ScalarEvolution::getLoopProperties(const Loop *L) {
6317   using LoopProperties = ScalarEvolution::LoopProperties;
6318 
6319   auto Itr = LoopPropertiesCache.find(L);
6320   if (Itr == LoopPropertiesCache.end()) {
6321     auto HasSideEffects = [](Instruction *I) {
6322       if (auto *SI = dyn_cast<StoreInst>(I))
6323         return !SI->isSimple();
6324 
6325       return I->mayHaveSideEffects();
6326     };
6327 
6328     LoopProperties LP = {/* HasNoAbnormalExits */ true,
6329                          /*HasNoSideEffects*/ true};
6330 
6331     for (auto *BB : L->getBlocks())
6332       for (auto &I : *BB) {
6333         if (!isGuaranteedToTransferExecutionToSuccessor(&I))
6334           LP.HasNoAbnormalExits = false;
6335         if (HasSideEffects(&I))
6336           LP.HasNoSideEffects = false;
6337         if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
6338           break; // We're already as pessimistic as we can get.
6339       }
6340 
6341     auto InsertPair = LoopPropertiesCache.insert({L, LP});
6342     assert(InsertPair.second && "We just checked!");
6343     Itr = InsertPair.first;
6344   }
6345 
6346   return Itr->second;
6347 }
6348 
6349 const SCEV *ScalarEvolution::createSCEV(Value *V) {
6350   if (!isSCEVable(V->getType()))
6351     return getUnknown(V);
6352 
6353   if (Instruction *I = dyn_cast<Instruction>(V)) {
6354     // Don't attempt to analyze instructions in blocks that aren't
6355     // reachable. Such instructions don't matter, and they aren't required
6356     // to obey basic rules for definitions dominating uses which this
6357     // analysis depends on.
6358     if (!DT.isReachableFromEntry(I->getParent()))
6359       return getUnknown(UndefValue::get(V->getType()));
6360   } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
6361     return getConstant(CI);
6362   else if (isa<ConstantPointerNull>(V))
6363     // FIXME: we shouldn't special-case null pointer constant.
6364     return getZero(V->getType());
6365   else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
6366     return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee());
6367   else if (!isa<ConstantExpr>(V))
6368     return getUnknown(V);
6369 
6370   Operator *U = cast<Operator>(V);
6371   if (auto BO = MatchBinaryOp(U, DT)) {
6372     switch (BO->Opcode) {
6373     case Instruction::Add: {
6374       // The simple thing to do would be to just call getSCEV on both operands
6375       // and call getAddExpr with the result. However if we're looking at a
6376       // bunch of things all added together, this can be quite inefficient,
6377       // because it leads to N-1 getAddExpr calls for N ultimate operands.
6378       // Instead, gather up all the operands and make a single getAddExpr call.
6379       // LLVM IR canonical form means we need only traverse the left operands.
6380       SmallVector<const SCEV *, 4> AddOps;
6381       do {
6382         if (BO->Op) {
6383           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
6384             AddOps.push_back(OpSCEV);
6385             break;
6386           }
6387 
6388           // If a NUW or NSW flag can be applied to the SCEV for this
6389           // addition, then compute the SCEV for this addition by itself
6390           // with a separate call to getAddExpr. We need to do that
6391           // instead of pushing the operands of the addition onto AddOps,
6392           // since the flags are only known to apply to this particular
6393           // addition - they may not apply to other additions that can be
6394           // formed with operands from AddOps.
6395           const SCEV *RHS = getSCEV(BO->RHS);
6396           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
6397           if (Flags != SCEV::FlagAnyWrap) {
6398             const SCEV *LHS = getSCEV(BO->LHS);
6399             if (BO->Opcode == Instruction::Sub)
6400               AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
6401             else
6402               AddOps.push_back(getAddExpr(LHS, RHS, Flags));
6403             break;
6404           }
6405         }
6406 
6407         if (BO->Opcode == Instruction::Sub)
6408           AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
6409         else
6410           AddOps.push_back(getSCEV(BO->RHS));
6411 
6412         auto NewBO = MatchBinaryOp(BO->LHS, DT);
6413         if (!NewBO || (NewBO->Opcode != Instruction::Add &&
6414                        NewBO->Opcode != Instruction::Sub)) {
6415           AddOps.push_back(getSCEV(BO->LHS));
6416           break;
6417         }
6418         BO = NewBO;
6419       } while (true);
6420 
6421       return getAddExpr(AddOps);
6422     }
6423 
6424     case Instruction::Mul: {
6425       SmallVector<const SCEV *, 4> MulOps;
6426       do {
6427         if (BO->Op) {
6428           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
6429             MulOps.push_back(OpSCEV);
6430             break;
6431           }
6432 
6433           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
6434           if (Flags != SCEV::FlagAnyWrap) {
6435             MulOps.push_back(
6436                 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags));
6437             break;
6438           }
6439         }
6440 
6441         MulOps.push_back(getSCEV(BO->RHS));
6442         auto NewBO = MatchBinaryOp(BO->LHS, DT);
6443         if (!NewBO || NewBO->Opcode != Instruction::Mul) {
6444           MulOps.push_back(getSCEV(BO->LHS));
6445           break;
6446         }
6447         BO = NewBO;
6448       } while (true);
6449 
6450       return getMulExpr(MulOps);
6451     }
6452     case Instruction::UDiv:
6453       return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
6454     case Instruction::URem:
6455       return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
6456     case Instruction::Sub: {
6457       SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
6458       if (BO->Op)
6459         Flags = getNoWrapFlagsFromUB(BO->Op);
6460       return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags);
6461     }
6462     case Instruction::And:
6463       // For an expression like x&255 that merely masks off the high bits,
6464       // use zext(trunc(x)) as the SCEV expression.
6465       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6466         if (CI->isZero())
6467           return getSCEV(BO->RHS);
6468         if (CI->isMinusOne())
6469           return getSCEV(BO->LHS);
6470         const APInt &A = CI->getValue();
6471 
6472         // Instcombine's ShrinkDemandedConstant may strip bits out of
6473         // constants, obscuring what would otherwise be a low-bits mask.
6474         // Use computeKnownBits to compute what ShrinkDemandedConstant
6475         // knew about to reconstruct a low-bits mask value.
6476         unsigned LZ = A.countLeadingZeros();
6477         unsigned TZ = A.countTrailingZeros();
6478         unsigned BitWidth = A.getBitWidth();
6479         KnownBits Known(BitWidth);
6480         computeKnownBits(BO->LHS, Known, getDataLayout(),
6481                          0, &AC, nullptr, &DT);
6482 
6483         APInt EffectiveMask =
6484             APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
6485         if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
6486           const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
6487           const SCEV *LHS = getSCEV(BO->LHS);
6488           const SCEV *ShiftedLHS = nullptr;
6489           if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
6490             if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
6491               // For an expression like (x * 8) & 8, simplify the multiply.
6492               unsigned MulZeros = OpC->getAPInt().countTrailingZeros();
6493               unsigned GCD = std::min(MulZeros, TZ);
6494               APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
6495               SmallVector<const SCEV*, 4> MulOps;
6496               MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD)));
6497               MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end());
6498               auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
6499               ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
6500             }
6501           }
6502           if (!ShiftedLHS)
6503             ShiftedLHS = getUDivExpr(LHS, MulCount);
6504           return getMulExpr(
6505               getZeroExtendExpr(
6506                   getTruncateExpr(ShiftedLHS,
6507                       IntegerType::get(getContext(), BitWidth - LZ - TZ)),
6508                   BO->LHS->getType()),
6509               MulCount);
6510         }
6511       }
6512       break;
6513 
6514     case Instruction::Or:
6515       // If the RHS of the Or is a constant, we may have something like:
6516       // X*4+1 which got turned into X*4|1.  Handle this as an Add so loop
6517       // optimizations will transparently handle this case.
6518       //
6519       // In order for this transformation to be safe, the LHS must be of the
6520       // form X*(2^n) and the Or constant must be less than 2^n.
6521       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6522         const SCEV *LHS = getSCEV(BO->LHS);
6523         const APInt &CIVal = CI->getValue();
6524         if (GetMinTrailingZeros(LHS) >=
6525             (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
6526           // Build a plain add SCEV.
6527           return getAddExpr(LHS, getSCEV(CI),
6528                             (SCEV::NoWrapFlags)(SCEV::FlagNUW | SCEV::FlagNSW));
6529         }
6530       }
6531       break;
6532 
6533     case Instruction::Xor:
6534       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6535         // If the RHS of xor is -1, then this is a not operation.
6536         if (CI->isMinusOne())
6537           return getNotSCEV(getSCEV(BO->LHS));
6538 
6539         // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
6540         // This is a variant of the check for xor with -1, and it handles
6541         // the case where instcombine has trimmed non-demanded bits out
6542         // of an xor with -1.
6543         if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
6544           if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
6545             if (LBO->getOpcode() == Instruction::And &&
6546                 LCI->getValue() == CI->getValue())
6547               if (const SCEVZeroExtendExpr *Z =
6548                       dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
6549                 Type *UTy = BO->LHS->getType();
6550                 const SCEV *Z0 = Z->getOperand();
6551                 Type *Z0Ty = Z0->getType();
6552                 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
6553 
6554                 // If C is a low-bits mask, the zero extend is serving to
6555                 // mask off the high bits. Complement the operand and
6556                 // re-apply the zext.
6557                 if (CI->getValue().isMask(Z0TySize))
6558                   return getZeroExtendExpr(getNotSCEV(Z0), UTy);
6559 
6560                 // If C is a single bit, it may be in the sign-bit position
6561                 // before the zero-extend. In this case, represent the xor
6562                 // using an add, which is equivalent, and re-apply the zext.
6563                 APInt Trunc = CI->getValue().trunc(Z0TySize);
6564                 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
6565                     Trunc.isSignMask())
6566                   return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
6567                                            UTy);
6568               }
6569       }
6570       break;
6571 
6572     case Instruction::Shl:
6573       // Turn shift left of a constant amount into a multiply.
6574       if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
6575         uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
6576 
6577         // If the shift count is not less than the bitwidth, the result of
6578         // the shift is undefined. Don't try to analyze it, because the
6579         // resolution chosen here may differ from the resolution chosen in
6580         // other parts of the compiler.
6581         if (SA->getValue().uge(BitWidth))
6582           break;
6583 
6584         // We can safely preserve the nuw flag in all cases. It's also safe to
6585         // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation
6586         // requires special handling. It can be preserved as long as we're not
6587         // left shifting by bitwidth - 1.
6588         auto Flags = SCEV::FlagAnyWrap;
6589         if (BO->Op) {
6590           auto MulFlags = getNoWrapFlagsFromUB(BO->Op);
6591           if ((MulFlags & SCEV::FlagNSW) &&
6592               ((MulFlags & SCEV::FlagNUW) || SA->getValue().ult(BitWidth - 1)))
6593             Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNSW);
6594           if (MulFlags & SCEV::FlagNUW)
6595             Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNUW);
6596         }
6597 
6598         Constant *X = ConstantInt::get(
6599             getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
6600         return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags);
6601       }
6602       break;
6603 
6604     case Instruction::AShr: {
6605       // AShr X, C, where C is a constant.
6606       ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
6607       if (!CI)
6608         break;
6609 
6610       Type *OuterTy = BO->LHS->getType();
6611       uint64_t BitWidth = getTypeSizeInBits(OuterTy);
6612       // If the shift count is not less than the bitwidth, the result of
6613       // the shift is undefined. Don't try to analyze it, because the
6614       // resolution chosen here may differ from the resolution chosen in
6615       // other parts of the compiler.
6616       if (CI->getValue().uge(BitWidth))
6617         break;
6618 
6619       if (CI->isZero())
6620         return getSCEV(BO->LHS); // shift by zero --> noop
6621 
6622       uint64_t AShrAmt = CI->getZExtValue();
6623       Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
6624 
6625       Operator *L = dyn_cast<Operator>(BO->LHS);
6626       if (L && L->getOpcode() == Instruction::Shl) {
6627         // X = Shl A, n
6628         // Y = AShr X, m
6629         // Both n and m are constant.
6630 
6631         const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
6632         if (L->getOperand(1) == BO->RHS)
6633           // For a two-shift sext-inreg, i.e. n = m,
6634           // use sext(trunc(x)) as the SCEV expression.
6635           return getSignExtendExpr(
6636               getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy);
6637 
6638         ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
6639         if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) {
6640           uint64_t ShlAmt = ShlAmtCI->getZExtValue();
6641           if (ShlAmt > AShrAmt) {
6642             // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
6643             // expression. We already checked that ShlAmt < BitWidth, so
6644             // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
6645             // ShlAmt - AShrAmt < Amt.
6646             APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
6647                                             ShlAmt - AShrAmt);
6648             return getSignExtendExpr(
6649                 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy),
6650                 getConstant(Mul)), OuterTy);
6651           }
6652         }
6653       }
6654       if (BO->IsExact) {
6655         // Given exact arithmetic in-bounds right-shift by a constant,
6656         // we can lower it into:  (abs(x) EXACT/u (1<<C)) * signum(x)
6657         const SCEV *X = getSCEV(BO->LHS);
6658         const SCEV *AbsX = getAbsExpr(X, /*IsNSW=*/false);
6659         APInt Mult = APInt::getOneBitSet(BitWidth, AShrAmt);
6660         const SCEV *Div = getUDivExactExpr(AbsX, getConstant(Mult));
6661         return getMulExpr(Div, getSignumExpr(X), SCEV::FlagNSW);
6662       }
6663       break;
6664     }
6665     }
6666   }
6667 
6668   switch (U->getOpcode()) {
6669   case Instruction::Trunc:
6670     return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
6671 
6672   case Instruction::ZExt:
6673     return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
6674 
6675   case Instruction::SExt:
6676     if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) {
6677       // The NSW flag of a subtract does not always survive the conversion to
6678       // A + (-1)*B.  By pushing sign extension onto its operands we are much
6679       // more likely to preserve NSW and allow later AddRec optimisations.
6680       //
6681       // NOTE: This is effectively duplicating this logic from getSignExtend:
6682       //   sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
6683       // but by that point the NSW information has potentially been lost.
6684       if (BO->Opcode == Instruction::Sub && BO->IsNSW) {
6685         Type *Ty = U->getType();
6686         auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty);
6687         auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty);
6688         return getMinusSCEV(V1, V2, SCEV::FlagNSW);
6689       }
6690     }
6691     return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
6692 
6693   case Instruction::BitCast:
6694     // BitCasts are no-op casts so we just eliminate the cast.
6695     if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
6696       return getSCEV(U->getOperand(0));
6697     break;
6698 
6699   case Instruction::PtrToInt: {
6700     // Pointer to integer cast is straight-forward, so do model it.
6701     Value *Ptr = U->getOperand(0);
6702     const SCEV *Op = getSCEV(Ptr);
6703     Type *DstIntTy = U->getType();
6704     // SCEV doesn't have constant pointer expression type, but it supports
6705     // nullptr constant (and only that one), which is modelled in SCEV as a
6706     // zero integer constant. So just skip the ptrtoint cast for constants.
6707     if (isa<SCEVConstant>(Op))
6708       return getTruncateOrZeroExtend(Op, DstIntTy);
6709     Type *PtrTy = Ptr->getType();
6710     Type *IntPtrTy = getDataLayout().getIntPtrType(PtrTy);
6711     // But only if effective SCEV (integer) type is wide enough to represent
6712     // all possible pointer values.
6713     if (getDataLayout().getTypeSizeInBits(getEffectiveSCEVType(PtrTy)) !=
6714         getDataLayout().getTypeSizeInBits(IntPtrTy))
6715       return getUnknown(V);
6716     return getPtrToIntExpr(Op, DstIntTy);
6717   }
6718   case Instruction::IntToPtr:
6719     // Just don't deal with inttoptr casts.
6720     return getUnknown(V);
6721 
6722   case Instruction::SDiv:
6723     // If both operands are non-negative, this is just an udiv.
6724     if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
6725         isKnownNonNegative(getSCEV(U->getOperand(1))))
6726       return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
6727     break;
6728 
6729   case Instruction::SRem:
6730     // If both operands are non-negative, this is just an urem.
6731     if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
6732         isKnownNonNegative(getSCEV(U->getOperand(1))))
6733       return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
6734     break;
6735 
6736   case Instruction::GetElementPtr:
6737     return createNodeForGEP(cast<GEPOperator>(U));
6738 
6739   case Instruction::PHI:
6740     return createNodeForPHI(cast<PHINode>(U));
6741 
6742   case Instruction::Select:
6743     // U can also be a select constant expr, which let fall through.  Since
6744     // createNodeForSelect only works for a condition that is an `ICmpInst`, and
6745     // constant expressions cannot have instructions as operands, we'd have
6746     // returned getUnknown for a select constant expressions anyway.
6747     if (isa<Instruction>(U))
6748       return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0),
6749                                       U->getOperand(1), U->getOperand(2));
6750     break;
6751 
6752   case Instruction::Call:
6753   case Instruction::Invoke:
6754     if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand())
6755       return getSCEV(RV);
6756 
6757     if (auto *II = dyn_cast<IntrinsicInst>(U)) {
6758       switch (II->getIntrinsicID()) {
6759       case Intrinsic::abs:
6760         return getAbsExpr(
6761             getSCEV(II->getArgOperand(0)),
6762             /*IsNSW=*/cast<ConstantInt>(II->getArgOperand(1))->isOne());
6763       case Intrinsic::umax:
6764         return getUMaxExpr(getSCEV(II->getArgOperand(0)),
6765                            getSCEV(II->getArgOperand(1)));
6766       case Intrinsic::umin:
6767         return getUMinExpr(getSCEV(II->getArgOperand(0)),
6768                            getSCEV(II->getArgOperand(1)));
6769       case Intrinsic::smax:
6770         return getSMaxExpr(getSCEV(II->getArgOperand(0)),
6771                            getSCEV(II->getArgOperand(1)));
6772       case Intrinsic::smin:
6773         return getSMinExpr(getSCEV(II->getArgOperand(0)),
6774                            getSCEV(II->getArgOperand(1)));
6775       case Intrinsic::usub_sat: {
6776         const SCEV *X = getSCEV(II->getArgOperand(0));
6777         const SCEV *Y = getSCEV(II->getArgOperand(1));
6778         const SCEV *ClampedY = getUMinExpr(X, Y);
6779         return getMinusSCEV(X, ClampedY, SCEV::FlagNUW);
6780       }
6781       case Intrinsic::uadd_sat: {
6782         const SCEV *X = getSCEV(II->getArgOperand(0));
6783         const SCEV *Y = getSCEV(II->getArgOperand(1));
6784         const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y));
6785         return getAddExpr(ClampedX, Y, SCEV::FlagNUW);
6786       }
6787       case Intrinsic::start_loop_iterations:
6788         // A start_loop_iterations is just equivalent to the first operand for
6789         // SCEV purposes.
6790         return getSCEV(II->getArgOperand(0));
6791       default:
6792         break;
6793       }
6794     }
6795     break;
6796   }
6797 
6798   return getUnknown(V);
6799 }
6800 
6801 //===----------------------------------------------------------------------===//
6802 //                   Iteration Count Computation Code
6803 //
6804 
6805 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
6806   if (!ExitCount)
6807     return 0;
6808 
6809   ConstantInt *ExitConst = ExitCount->getValue();
6810 
6811   // Guard against huge trip counts.
6812   if (ExitConst->getValue().getActiveBits() > 32)
6813     return 0;
6814 
6815   // In case of integer overflow, this returns 0, which is correct.
6816   return ((unsigned)ExitConst->getZExtValue()) + 1;
6817 }
6818 
6819 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) {
6820   if (BasicBlock *ExitingBB = L->getExitingBlock())
6821     return getSmallConstantTripCount(L, ExitingBB);
6822 
6823   // No trip count information for multiple exits.
6824   return 0;
6825 }
6826 
6827 unsigned
6828 ScalarEvolution::getSmallConstantTripCount(const Loop *L,
6829                                            const BasicBlock *ExitingBlock) {
6830   assert(ExitingBlock && "Must pass a non-null exiting block!");
6831   assert(L->isLoopExiting(ExitingBlock) &&
6832          "Exiting block must actually branch out of the loop!");
6833   const SCEVConstant *ExitCount =
6834       dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
6835   return getConstantTripCount(ExitCount);
6836 }
6837 
6838 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) {
6839   const auto *MaxExitCount =
6840       dyn_cast<SCEVConstant>(getConstantMaxBackedgeTakenCount(L));
6841   return getConstantTripCount(MaxExitCount);
6842 }
6843 
6844 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) {
6845   if (BasicBlock *ExitingBB = L->getExitingBlock())
6846     return getSmallConstantTripMultiple(L, ExitingBB);
6847 
6848   // No trip multiple information for multiple exits.
6849   return 0;
6850 }
6851 
6852 /// Returns the largest constant divisor of the trip count of this loop as a
6853 /// normal unsigned value, if possible. This means that the actual trip count is
6854 /// always a multiple of the returned value (don't forget the trip count could
6855 /// very well be zero as well!).
6856 ///
6857 /// Returns 1 if the trip count is unknown or not guaranteed to be the
6858 /// multiple of a constant (which is also the case if the trip count is simply
6859 /// constant, use getSmallConstantTripCount for that case), Will also return 1
6860 /// if the trip count is very large (>= 2^32).
6861 ///
6862 /// As explained in the comments for getSmallConstantTripCount, this assumes
6863 /// that control exits the loop via ExitingBlock.
6864 unsigned
6865 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
6866                                               const BasicBlock *ExitingBlock) {
6867   assert(ExitingBlock && "Must pass a non-null exiting block!");
6868   assert(L->isLoopExiting(ExitingBlock) &&
6869          "Exiting block must actually branch out of the loop!");
6870   const SCEV *ExitCount = getExitCount(L, ExitingBlock);
6871   if (ExitCount == getCouldNotCompute())
6872     return 1;
6873 
6874   // Get the trip count from the BE count by adding 1.
6875   const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType()));
6876 
6877   const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr);
6878   if (!TC)
6879     // Attempt to factor more general cases. Returns the greatest power of
6880     // two divisor. If overflow happens, the trip count expression is still
6881     // divisible by the greatest power of 2 divisor returned.
6882     return 1U << std::min((uint32_t)31,
6883                           GetMinTrailingZeros(applyLoopGuards(TCExpr, L)));
6884 
6885   ConstantInt *Result = TC->getValue();
6886 
6887   // Guard against huge trip counts (this requires checking
6888   // for zero to handle the case where the trip count == -1 and the
6889   // addition wraps).
6890   if (!Result || Result->getValue().getActiveBits() > 32 ||
6891       Result->getValue().getActiveBits() == 0)
6892     return 1;
6893 
6894   return (unsigned)Result->getZExtValue();
6895 }
6896 
6897 const SCEV *ScalarEvolution::getExitCount(const Loop *L,
6898                                           const BasicBlock *ExitingBlock,
6899                                           ExitCountKind Kind) {
6900   switch (Kind) {
6901   case Exact:
6902   case SymbolicMaximum:
6903     return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
6904   case ConstantMaximum:
6905     return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this);
6906   };
6907   llvm_unreachable("Invalid ExitCountKind!");
6908 }
6909 
6910 const SCEV *
6911 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
6912                                                  SCEVUnionPredicate &Preds) {
6913   return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds);
6914 }
6915 
6916 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L,
6917                                                    ExitCountKind Kind) {
6918   switch (Kind) {
6919   case Exact:
6920     return getBackedgeTakenInfo(L).getExact(L, this);
6921   case ConstantMaximum:
6922     return getBackedgeTakenInfo(L).getConstantMax(this);
6923   case SymbolicMaximum:
6924     return getBackedgeTakenInfo(L).getSymbolicMax(L, this);
6925   };
6926   llvm_unreachable("Invalid ExitCountKind!");
6927 }
6928 
6929 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) {
6930   return getBackedgeTakenInfo(L).isConstantMaxOrZero(this);
6931 }
6932 
6933 /// Push PHI nodes in the header of the given loop onto the given Worklist.
6934 static void
6935 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
6936   BasicBlock *Header = L->getHeader();
6937 
6938   // Push all Loop-header PHIs onto the Worklist stack.
6939   for (PHINode &PN : Header->phis())
6940     Worklist.push_back(&PN);
6941 }
6942 
6943 const ScalarEvolution::BackedgeTakenInfo &
6944 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
6945   auto &BTI = getBackedgeTakenInfo(L);
6946   if (BTI.hasFullInfo())
6947     return BTI;
6948 
6949   auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
6950 
6951   if (!Pair.second)
6952     return Pair.first->second;
6953 
6954   BackedgeTakenInfo Result =
6955       computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
6956 
6957   return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
6958 }
6959 
6960 ScalarEvolution::BackedgeTakenInfo &
6961 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
6962   // Initially insert an invalid entry for this loop. If the insertion
6963   // succeeds, proceed to actually compute a backedge-taken count and
6964   // update the value. The temporary CouldNotCompute value tells SCEV
6965   // code elsewhere that it shouldn't attempt to request a new
6966   // backedge-taken count, which could result in infinite recursion.
6967   std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
6968       BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
6969   if (!Pair.second)
6970     return Pair.first->second;
6971 
6972   // computeBackedgeTakenCount may allocate memory for its result. Inserting it
6973   // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
6974   // must be cleared in this scope.
6975   BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
6976 
6977   // In product build, there are no usage of statistic.
6978   (void)NumTripCountsComputed;
6979   (void)NumTripCountsNotComputed;
6980 #if LLVM_ENABLE_STATS || !defined(NDEBUG)
6981   const SCEV *BEExact = Result.getExact(L, this);
6982   if (BEExact != getCouldNotCompute()) {
6983     assert(isLoopInvariant(BEExact, L) &&
6984            isLoopInvariant(Result.getConstantMax(this), L) &&
6985            "Computed backedge-taken count isn't loop invariant for loop!");
6986     ++NumTripCountsComputed;
6987   } else if (Result.getConstantMax(this) == getCouldNotCompute() &&
6988              isa<PHINode>(L->getHeader()->begin())) {
6989     // Only count loops that have phi nodes as not being computable.
6990     ++NumTripCountsNotComputed;
6991   }
6992 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG)
6993 
6994   // Now that we know more about the trip count for this loop, forget any
6995   // existing SCEV values for PHI nodes in this loop since they are only
6996   // conservative estimates made without the benefit of trip count
6997   // information. This is similar to the code in forgetLoop, except that
6998   // it handles SCEVUnknown PHI nodes specially.
6999   if (Result.hasAnyInfo()) {
7000     SmallVector<Instruction *, 16> Worklist;
7001     PushLoopPHIs(L, Worklist);
7002 
7003     SmallPtrSet<Instruction *, 8> Discovered;
7004     while (!Worklist.empty()) {
7005       Instruction *I = Worklist.pop_back_val();
7006 
7007       ValueExprMapType::iterator It =
7008         ValueExprMap.find_as(static_cast<Value *>(I));
7009       if (It != ValueExprMap.end()) {
7010         const SCEV *Old = It->second;
7011 
7012         // SCEVUnknown for a PHI either means that it has an unrecognized
7013         // structure, or it's a PHI that's in the progress of being computed
7014         // by createNodeForPHI.  In the former case, additional loop trip
7015         // count information isn't going to change anything. In the later
7016         // case, createNodeForPHI will perform the necessary updates on its
7017         // own when it gets to that point.
7018         if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
7019           eraseValueFromMap(It->first);
7020           forgetMemoizedResults(Old);
7021         }
7022         if (PHINode *PN = dyn_cast<PHINode>(I))
7023           ConstantEvolutionLoopExitValue.erase(PN);
7024       }
7025 
7026       // Since we don't need to invalidate anything for correctness and we're
7027       // only invalidating to make SCEV's results more precise, we get to stop
7028       // early to avoid invalidating too much.  This is especially important in
7029       // cases like:
7030       //
7031       //   %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node
7032       // loop0:
7033       //   %pn0 = phi
7034       //   ...
7035       // loop1:
7036       //   %pn1 = phi
7037       //   ...
7038       //
7039       // where both loop0 and loop1's backedge taken count uses the SCEV
7040       // expression for %v.  If we don't have the early stop below then in cases
7041       // like the above, getBackedgeTakenInfo(loop1) will clear out the trip
7042       // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip
7043       // count for loop1, effectively nullifying SCEV's trip count cache.
7044       for (auto *U : I->users())
7045         if (auto *I = dyn_cast<Instruction>(U)) {
7046           auto *LoopForUser = LI.getLoopFor(I->getParent());
7047           if (LoopForUser && L->contains(LoopForUser) &&
7048               Discovered.insert(I).second)
7049             Worklist.push_back(I);
7050         }
7051     }
7052   }
7053 
7054   // Re-lookup the insert position, since the call to
7055   // computeBackedgeTakenCount above could result in a
7056   // recusive call to getBackedgeTakenInfo (on a different
7057   // loop), which would invalidate the iterator computed
7058   // earlier.
7059   return BackedgeTakenCounts.find(L)->second = std::move(Result);
7060 }
7061 
7062 void ScalarEvolution::forgetAllLoops() {
7063   // This method is intended to forget all info about loops. It should
7064   // invalidate caches as if the following happened:
7065   // - The trip counts of all loops have changed arbitrarily
7066   // - Every llvm::Value has been updated in place to produce a different
7067   // result.
7068   BackedgeTakenCounts.clear();
7069   PredicatedBackedgeTakenCounts.clear();
7070   LoopPropertiesCache.clear();
7071   ConstantEvolutionLoopExitValue.clear();
7072   ValueExprMap.clear();
7073   ValuesAtScopes.clear();
7074   LoopDispositions.clear();
7075   BlockDispositions.clear();
7076   UnsignedRanges.clear();
7077   SignedRanges.clear();
7078   ExprValueMap.clear();
7079   HasRecMap.clear();
7080   MinTrailingZerosCache.clear();
7081   PredicatedSCEVRewrites.clear();
7082 }
7083 
7084 void ScalarEvolution::forgetLoop(const Loop *L) {
7085   // Drop any stored trip count value.
7086   auto RemoveLoopFromBackedgeMap =
7087       [](DenseMap<const Loop *, BackedgeTakenInfo> &Map, const Loop *L) {
7088         auto BTCPos = Map.find(L);
7089         if (BTCPos != Map.end()) {
7090           BTCPos->second.clear();
7091           Map.erase(BTCPos);
7092         }
7093       };
7094 
7095   SmallVector<const Loop *, 16> LoopWorklist(1, L);
7096   SmallVector<Instruction *, 32> Worklist;
7097   SmallPtrSet<Instruction *, 16> Visited;
7098 
7099   // Iterate over all the loops and sub-loops to drop SCEV information.
7100   while (!LoopWorklist.empty()) {
7101     auto *CurrL = LoopWorklist.pop_back_val();
7102 
7103     RemoveLoopFromBackedgeMap(BackedgeTakenCounts, CurrL);
7104     RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts, CurrL);
7105 
7106     // Drop information about predicated SCEV rewrites for this loop.
7107     for (auto I = PredicatedSCEVRewrites.begin();
7108          I != PredicatedSCEVRewrites.end();) {
7109       std::pair<const SCEV *, const Loop *> Entry = I->first;
7110       if (Entry.second == CurrL)
7111         PredicatedSCEVRewrites.erase(I++);
7112       else
7113         ++I;
7114     }
7115 
7116     auto LoopUsersItr = LoopUsers.find(CurrL);
7117     if (LoopUsersItr != LoopUsers.end()) {
7118       for (auto *S : LoopUsersItr->second)
7119         forgetMemoizedResults(S);
7120       LoopUsers.erase(LoopUsersItr);
7121     }
7122 
7123     // Drop information about expressions based on loop-header PHIs.
7124     PushLoopPHIs(CurrL, Worklist);
7125 
7126     while (!Worklist.empty()) {
7127       Instruction *I = Worklist.pop_back_val();
7128       if (!Visited.insert(I).second)
7129         continue;
7130 
7131       ValueExprMapType::iterator It =
7132           ValueExprMap.find_as(static_cast<Value *>(I));
7133       if (It != ValueExprMap.end()) {
7134         eraseValueFromMap(It->first);
7135         forgetMemoizedResults(It->second);
7136         if (PHINode *PN = dyn_cast<PHINode>(I))
7137           ConstantEvolutionLoopExitValue.erase(PN);
7138       }
7139 
7140       PushDefUseChildren(I, Worklist);
7141     }
7142 
7143     LoopPropertiesCache.erase(CurrL);
7144     // Forget all contained loops too, to avoid dangling entries in the
7145     // ValuesAtScopes map.
7146     LoopWorklist.append(CurrL->begin(), CurrL->end());
7147   }
7148 }
7149 
7150 void ScalarEvolution::forgetTopmostLoop(const Loop *L) {
7151   while (Loop *Parent = L->getParentLoop())
7152     L = Parent;
7153   forgetLoop(L);
7154 }
7155 
7156 void ScalarEvolution::forgetValue(Value *V) {
7157   Instruction *I = dyn_cast<Instruction>(V);
7158   if (!I) return;
7159 
7160   // Drop information about expressions based on loop-header PHIs.
7161   SmallVector<Instruction *, 16> Worklist;
7162   Worklist.push_back(I);
7163 
7164   SmallPtrSet<Instruction *, 8> Visited;
7165   while (!Worklist.empty()) {
7166     I = Worklist.pop_back_val();
7167     if (!Visited.insert(I).second)
7168       continue;
7169 
7170     ValueExprMapType::iterator It =
7171       ValueExprMap.find_as(static_cast<Value *>(I));
7172     if (It != ValueExprMap.end()) {
7173       eraseValueFromMap(It->first);
7174       forgetMemoizedResults(It->second);
7175       if (PHINode *PN = dyn_cast<PHINode>(I))
7176         ConstantEvolutionLoopExitValue.erase(PN);
7177     }
7178 
7179     PushDefUseChildren(I, Worklist);
7180   }
7181 }
7182 
7183 void ScalarEvolution::forgetLoopDispositions(const Loop *L) {
7184   LoopDispositions.clear();
7185 }
7186 
7187 /// Get the exact loop backedge taken count considering all loop exits. A
7188 /// computable result can only be returned for loops with all exiting blocks
7189 /// dominating the latch. howFarToZero assumes that the limit of each loop test
7190 /// is never skipped. This is a valid assumption as long as the loop exits via
7191 /// that test. For precise results, it is the caller's responsibility to specify
7192 /// the relevant loop exiting block using getExact(ExitingBlock, SE).
7193 const SCEV *
7194 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE,
7195                                              SCEVUnionPredicate *Preds) const {
7196   // If any exits were not computable, the loop is not computable.
7197   if (!isComplete() || ExitNotTaken.empty())
7198     return SE->getCouldNotCompute();
7199 
7200   const BasicBlock *Latch = L->getLoopLatch();
7201   // All exiting blocks we have collected must dominate the only backedge.
7202   if (!Latch)
7203     return SE->getCouldNotCompute();
7204 
7205   // All exiting blocks we have gathered dominate loop's latch, so exact trip
7206   // count is simply a minimum out of all these calculated exit counts.
7207   SmallVector<const SCEV *, 2> Ops;
7208   for (auto &ENT : ExitNotTaken) {
7209     const SCEV *BECount = ENT.ExactNotTaken;
7210     assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!");
7211     assert(SE->DT.dominates(ENT.ExitingBlock, Latch) &&
7212            "We should only have known counts for exiting blocks that dominate "
7213            "latch!");
7214 
7215     Ops.push_back(BECount);
7216 
7217     if (Preds && !ENT.hasAlwaysTruePredicate())
7218       Preds->add(ENT.Predicate.get());
7219 
7220     assert((Preds || ENT.hasAlwaysTruePredicate()) &&
7221            "Predicate should be always true!");
7222   }
7223 
7224   return SE->getUMinFromMismatchedTypes(Ops);
7225 }
7226 
7227 /// Get the exact not taken count for this loop exit.
7228 const SCEV *
7229 ScalarEvolution::BackedgeTakenInfo::getExact(const BasicBlock *ExitingBlock,
7230                                              ScalarEvolution *SE) const {
7231   for (auto &ENT : ExitNotTaken)
7232     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
7233       return ENT.ExactNotTaken;
7234 
7235   return SE->getCouldNotCompute();
7236 }
7237 
7238 const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax(
7239     const BasicBlock *ExitingBlock, ScalarEvolution *SE) const {
7240   for (auto &ENT : ExitNotTaken)
7241     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
7242       return ENT.MaxNotTaken;
7243 
7244   return SE->getCouldNotCompute();
7245 }
7246 
7247 /// getConstantMax - Get the constant max backedge taken count for the loop.
7248 const SCEV *
7249 ScalarEvolution::BackedgeTakenInfo::getConstantMax(ScalarEvolution *SE) const {
7250   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
7251     return !ENT.hasAlwaysTruePredicate();
7252   };
7253 
7254   if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getConstantMax())
7255     return SE->getCouldNotCompute();
7256 
7257   assert((isa<SCEVCouldNotCompute>(getConstantMax()) ||
7258           isa<SCEVConstant>(getConstantMax())) &&
7259          "No point in having a non-constant max backedge taken count!");
7260   return getConstantMax();
7261 }
7262 
7263 const SCEV *
7264 ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(const Loop *L,
7265                                                    ScalarEvolution *SE) {
7266   if (!SymbolicMax)
7267     SymbolicMax = SE->computeSymbolicMaxBackedgeTakenCount(L);
7268   return SymbolicMax;
7269 }
7270 
7271 bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero(
7272     ScalarEvolution *SE) const {
7273   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
7274     return !ENT.hasAlwaysTruePredicate();
7275   };
7276   return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
7277 }
7278 
7279 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S,
7280                                                     ScalarEvolution *SE) const {
7281   if (getConstantMax() && getConstantMax() != SE->getCouldNotCompute() &&
7282       SE->hasOperand(getConstantMax(), S))
7283     return true;
7284 
7285   for (auto &ENT : ExitNotTaken)
7286     if (ENT.ExactNotTaken != SE->getCouldNotCompute() &&
7287         SE->hasOperand(ENT.ExactNotTaken, S))
7288       return true;
7289 
7290   return false;
7291 }
7292 
7293 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E)
7294     : ExactNotTaken(E), MaxNotTaken(E) {
7295   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
7296           isa<SCEVConstant>(MaxNotTaken)) &&
7297          "No point in having a non-constant max backedge taken count!");
7298 }
7299 
7300 ScalarEvolution::ExitLimit::ExitLimit(
7301     const SCEV *E, const SCEV *M, bool MaxOrZero,
7302     ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList)
7303     : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) {
7304   assert((isa<SCEVCouldNotCompute>(ExactNotTaken) ||
7305           !isa<SCEVCouldNotCompute>(MaxNotTaken)) &&
7306          "Exact is not allowed to be less precise than Max");
7307   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
7308           isa<SCEVConstant>(MaxNotTaken)) &&
7309          "No point in having a non-constant max backedge taken count!");
7310   for (auto *PredSet : PredSetList)
7311     for (auto *P : *PredSet)
7312       addPredicate(P);
7313 }
7314 
7315 ScalarEvolution::ExitLimit::ExitLimit(
7316     const SCEV *E, const SCEV *M, bool MaxOrZero,
7317     const SmallPtrSetImpl<const SCEVPredicate *> &PredSet)
7318     : ExitLimit(E, M, MaxOrZero, {&PredSet}) {
7319   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
7320           isa<SCEVConstant>(MaxNotTaken)) &&
7321          "No point in having a non-constant max backedge taken count!");
7322 }
7323 
7324 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M,
7325                                       bool MaxOrZero)
7326     : ExitLimit(E, M, MaxOrZero, None) {
7327   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
7328           isa<SCEVConstant>(MaxNotTaken)) &&
7329          "No point in having a non-constant max backedge taken count!");
7330 }
7331 
7332 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
7333 /// computable exit into a persistent ExitNotTakenInfo array.
7334 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
7335     ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> ExitCounts,
7336     bool IsComplete, const SCEV *ConstantMax, bool MaxOrZero)
7337     : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) {
7338   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
7339 
7340   ExitNotTaken.reserve(ExitCounts.size());
7341   std::transform(
7342       ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken),
7343       [&](const EdgeExitInfo &EEI) {
7344         BasicBlock *ExitBB = EEI.first;
7345         const ExitLimit &EL = EEI.second;
7346         if (EL.Predicates.empty())
7347           return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken,
7348                                   nullptr);
7349 
7350         std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate);
7351         for (auto *Pred : EL.Predicates)
7352           Predicate->add(Pred);
7353 
7354         return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken,
7355                                 std::move(Predicate));
7356       });
7357   assert((isa<SCEVCouldNotCompute>(ConstantMax) ||
7358           isa<SCEVConstant>(ConstantMax)) &&
7359          "No point in having a non-constant max backedge taken count!");
7360 }
7361 
7362 /// Invalidate this result and free the ExitNotTakenInfo array.
7363 void ScalarEvolution::BackedgeTakenInfo::clear() {
7364   ExitNotTaken.clear();
7365 }
7366 
7367 /// Compute the number of times the backedge of the specified loop will execute.
7368 ScalarEvolution::BackedgeTakenInfo
7369 ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
7370                                            bool AllowPredicates) {
7371   SmallVector<BasicBlock *, 8> ExitingBlocks;
7372   L->getExitingBlocks(ExitingBlocks);
7373 
7374   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
7375 
7376   SmallVector<EdgeExitInfo, 4> ExitCounts;
7377   bool CouldComputeBECount = true;
7378   BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
7379   const SCEV *MustExitMaxBECount = nullptr;
7380   const SCEV *MayExitMaxBECount = nullptr;
7381   bool MustExitMaxOrZero = false;
7382 
7383   // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
7384   // and compute maxBECount.
7385   // Do a union of all the predicates here.
7386   for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
7387     BasicBlock *ExitBB = ExitingBlocks[i];
7388 
7389     // We canonicalize untaken exits to br (constant), ignore them so that
7390     // proving an exit untaken doesn't negatively impact our ability to reason
7391     // about the loop as whole.
7392     if (auto *BI = dyn_cast<BranchInst>(ExitBB->getTerminator()))
7393       if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
7394         bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
7395         if ((ExitIfTrue && CI->isZero()) || (!ExitIfTrue && CI->isOne()))
7396           continue;
7397       }
7398 
7399     ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
7400 
7401     assert((AllowPredicates || EL.Predicates.empty()) &&
7402            "Predicated exit limit when predicates are not allowed!");
7403 
7404     // 1. For each exit that can be computed, add an entry to ExitCounts.
7405     // CouldComputeBECount is true only if all exits can be computed.
7406     if (EL.ExactNotTaken == getCouldNotCompute())
7407       // We couldn't compute an exact value for this exit, so
7408       // we won't be able to compute an exact value for the loop.
7409       CouldComputeBECount = false;
7410     else
7411       ExitCounts.emplace_back(ExitBB, EL);
7412 
7413     // 2. Derive the loop's MaxBECount from each exit's max number of
7414     // non-exiting iterations. Partition the loop exits into two kinds:
7415     // LoopMustExits and LoopMayExits.
7416     //
7417     // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
7418     // is a LoopMayExit.  If any computable LoopMustExit is found, then
7419     // MaxBECount is the minimum EL.MaxNotTaken of computable
7420     // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
7421     // EL.MaxNotTaken, where CouldNotCompute is considered greater than any
7422     // computable EL.MaxNotTaken.
7423     if (EL.MaxNotTaken != getCouldNotCompute() && Latch &&
7424         DT.dominates(ExitBB, Latch)) {
7425       if (!MustExitMaxBECount) {
7426         MustExitMaxBECount = EL.MaxNotTaken;
7427         MustExitMaxOrZero = EL.MaxOrZero;
7428       } else {
7429         MustExitMaxBECount =
7430             getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken);
7431       }
7432     } else if (MayExitMaxBECount != getCouldNotCompute()) {
7433       if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute())
7434         MayExitMaxBECount = EL.MaxNotTaken;
7435       else {
7436         MayExitMaxBECount =
7437             getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken);
7438       }
7439     }
7440   }
7441   const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
7442     (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
7443   // The loop backedge will be taken the maximum or zero times if there's
7444   // a single exit that must be taken the maximum or zero times.
7445   bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
7446   return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
7447                            MaxBECount, MaxOrZero);
7448 }
7449 
7450 ScalarEvolution::ExitLimit
7451 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
7452                                       bool AllowPredicates) {
7453   assert(L->contains(ExitingBlock) && "Exit count for non-loop block?");
7454   // If our exiting block does not dominate the latch, then its connection with
7455   // loop's exit limit may be far from trivial.
7456   const BasicBlock *Latch = L->getLoopLatch();
7457   if (!Latch || !DT.dominates(ExitingBlock, Latch))
7458     return getCouldNotCompute();
7459 
7460   bool IsOnlyExit = (L->getExitingBlock() != nullptr);
7461   Instruction *Term = ExitingBlock->getTerminator();
7462   if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
7463     assert(BI->isConditional() && "If unconditional, it can't be in loop!");
7464     bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
7465     assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) &&
7466            "It should have one successor in loop and one exit block!");
7467     // Proceed to the next level to examine the exit condition expression.
7468     return computeExitLimitFromCond(
7469         L, BI->getCondition(), ExitIfTrue,
7470         /*ControlsExit=*/IsOnlyExit, AllowPredicates);
7471   }
7472 
7473   if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) {
7474     // For switch, make sure that there is a single exit from the loop.
7475     BasicBlock *Exit = nullptr;
7476     for (auto *SBB : successors(ExitingBlock))
7477       if (!L->contains(SBB)) {
7478         if (Exit) // Multiple exit successors.
7479           return getCouldNotCompute();
7480         Exit = SBB;
7481       }
7482     assert(Exit && "Exiting block must have at least one exit");
7483     return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
7484                                                 /*ControlsExit=*/IsOnlyExit);
7485   }
7486 
7487   return getCouldNotCompute();
7488 }
7489 
7490 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond(
7491     const Loop *L, Value *ExitCond, bool ExitIfTrue,
7492     bool ControlsExit, bool AllowPredicates) {
7493   ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates);
7494   return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue,
7495                                         ControlsExit, AllowPredicates);
7496 }
7497 
7498 Optional<ScalarEvolution::ExitLimit>
7499 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
7500                                       bool ExitIfTrue, bool ControlsExit,
7501                                       bool AllowPredicates) {
7502   (void)this->L;
7503   (void)this->ExitIfTrue;
7504   (void)this->AllowPredicates;
7505 
7506   assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
7507          this->AllowPredicates == AllowPredicates &&
7508          "Variance in assumed invariant key components!");
7509   auto Itr = TripCountMap.find({ExitCond, ControlsExit});
7510   if (Itr == TripCountMap.end())
7511     return None;
7512   return Itr->second;
7513 }
7514 
7515 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
7516                                              bool ExitIfTrue,
7517                                              bool ControlsExit,
7518                                              bool AllowPredicates,
7519                                              const ExitLimit &EL) {
7520   assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
7521          this->AllowPredicates == AllowPredicates &&
7522          "Variance in assumed invariant key components!");
7523 
7524   auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL});
7525   assert(InsertResult.second && "Expected successful insertion!");
7526   (void)InsertResult;
7527   (void)ExitIfTrue;
7528 }
7529 
7530 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
7531     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
7532     bool ControlsExit, bool AllowPredicates) {
7533 
7534   if (auto MaybeEL =
7535           Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates))
7536     return *MaybeEL;
7537 
7538   ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue,
7539                                               ControlsExit, AllowPredicates);
7540   Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL);
7541   return EL;
7542 }
7543 
7544 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
7545     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
7546     bool ControlsExit, bool AllowPredicates) {
7547   // Handle BinOp conditions (And, Or).
7548   if (auto LimitFromBinOp = computeExitLimitFromCondFromBinOp(
7549           Cache, L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates))
7550     return *LimitFromBinOp;
7551 
7552   // With an icmp, it may be feasible to compute an exact backedge-taken count.
7553   // Proceed to the next level to examine the icmp.
7554   if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
7555     ExitLimit EL =
7556         computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit);
7557     if (EL.hasFullInfo() || !AllowPredicates)
7558       return EL;
7559 
7560     // Try again, but use SCEV predicates this time.
7561     return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit,
7562                                     /*AllowPredicates=*/true);
7563   }
7564 
7565   // Check for a constant condition. These are normally stripped out by
7566   // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
7567   // preserve the CFG and is temporarily leaving constant conditions
7568   // in place.
7569   if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
7570     if (ExitIfTrue == !CI->getZExtValue())
7571       // The backedge is always taken.
7572       return getCouldNotCompute();
7573     else
7574       // The backedge is never taken.
7575       return getZero(CI->getType());
7576   }
7577 
7578   // If it's not an integer or pointer comparison then compute it the hard way.
7579   return computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
7580 }
7581 
7582 Optional<ScalarEvolution::ExitLimit>
7583 ScalarEvolution::computeExitLimitFromCondFromBinOp(
7584     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
7585     bool ControlsExit, bool AllowPredicates) {
7586   // Check if the controlling expression for this loop is an And or Or.
7587   Value *Op0, *Op1;
7588   bool IsAnd = false;
7589   if (match(ExitCond, m_LogicalAnd(m_Value(Op0), m_Value(Op1))))
7590     IsAnd = true;
7591   else if (match(ExitCond, m_LogicalOr(m_Value(Op0), m_Value(Op1))))
7592     IsAnd = false;
7593   else
7594     return None;
7595 
7596   // EitherMayExit is true in these two cases:
7597   //   br (and Op0 Op1), loop, exit
7598   //   br (or  Op0 Op1), exit, loop
7599   bool EitherMayExit = IsAnd ^ ExitIfTrue;
7600   ExitLimit EL0 = computeExitLimitFromCondCached(Cache, L, Op0, ExitIfTrue,
7601                                                  ControlsExit && !EitherMayExit,
7602                                                  AllowPredicates);
7603   ExitLimit EL1 = computeExitLimitFromCondCached(Cache, L, Op1, ExitIfTrue,
7604                                                  ControlsExit && !EitherMayExit,
7605                                                  AllowPredicates);
7606 
7607   // Be robust against unsimplified IR for the form "op i1 X, NeutralElement"
7608   const Constant *NeutralElement = ConstantInt::get(ExitCond->getType(), IsAnd);
7609   if (isa<ConstantInt>(Op1))
7610     return Op1 == NeutralElement ? EL0 : EL1;
7611   if (isa<ConstantInt>(Op0))
7612     return Op0 == NeutralElement ? EL1 : EL0;
7613 
7614   const SCEV *BECount = getCouldNotCompute();
7615   const SCEV *MaxBECount = getCouldNotCompute();
7616   if (EitherMayExit) {
7617     // Both conditions must be same for the loop to continue executing.
7618     // Choose the less conservative count.
7619     // If ExitCond is a short-circuit form (select), using
7620     // umin(EL0.ExactNotTaken, EL1.ExactNotTaken) is unsafe in general.
7621     // To see the detailed examples, please see
7622     // test/Analysis/ScalarEvolution/exit-count-select.ll
7623     bool PoisonSafe = isa<BinaryOperator>(ExitCond);
7624     if (!PoisonSafe)
7625       // Even if ExitCond is select, we can safely derive BECount using both
7626       // EL0 and EL1 in these cases:
7627       // (1) EL0.ExactNotTaken is non-zero
7628       // (2) EL1.ExactNotTaken is non-poison
7629       // (3) EL0.ExactNotTaken is zero (BECount should be simply zero and
7630       //     it cannot be umin(0, ..))
7631       // The PoisonSafe assignment below is simplified and the assertion after
7632       // BECount calculation fully guarantees the condition (3).
7633       PoisonSafe = isa<SCEVConstant>(EL0.ExactNotTaken) ||
7634                    isa<SCEVConstant>(EL1.ExactNotTaken);
7635     if (EL0.ExactNotTaken != getCouldNotCompute() &&
7636         EL1.ExactNotTaken != getCouldNotCompute() && PoisonSafe) {
7637       BECount =
7638           getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
7639 
7640       // If EL0.ExactNotTaken was zero and ExitCond was a short-circuit form,
7641       // it should have been simplified to zero (see the condition (3) above)
7642       assert(!isa<BinaryOperator>(ExitCond) || !EL0.ExactNotTaken->isZero() ||
7643              BECount->isZero());
7644     }
7645     if (EL0.MaxNotTaken == getCouldNotCompute())
7646       MaxBECount = EL1.MaxNotTaken;
7647     else if (EL1.MaxNotTaken == getCouldNotCompute())
7648       MaxBECount = EL0.MaxNotTaken;
7649     else
7650       MaxBECount = getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
7651   } else {
7652     // Both conditions must be same at the same time for the loop to exit.
7653     // For now, be conservative.
7654     if (EL0.ExactNotTaken == EL1.ExactNotTaken)
7655       BECount = EL0.ExactNotTaken;
7656   }
7657 
7658   // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
7659   // to be more aggressive when computing BECount than when computing
7660   // MaxBECount.  In these cases it is possible for EL0.ExactNotTaken and
7661   // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
7662   // to not.
7663   if (isa<SCEVCouldNotCompute>(MaxBECount) &&
7664       !isa<SCEVCouldNotCompute>(BECount))
7665     MaxBECount = getConstant(getUnsignedRangeMax(BECount));
7666 
7667   return ExitLimit(BECount, MaxBECount, false,
7668                    { &EL0.Predicates, &EL1.Predicates });
7669 }
7670 
7671 ScalarEvolution::ExitLimit
7672 ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
7673                                           ICmpInst *ExitCond,
7674                                           bool ExitIfTrue,
7675                                           bool ControlsExit,
7676                                           bool AllowPredicates) {
7677   // If the condition was exit on true, convert the condition to exit on false
7678   ICmpInst::Predicate Pred;
7679   if (!ExitIfTrue)
7680     Pred = ExitCond->getPredicate();
7681   else
7682     Pred = ExitCond->getInversePredicate();
7683   const ICmpInst::Predicate OriginalPred = Pred;
7684 
7685   // Handle common loops like: for (X = "string"; *X; ++X)
7686   if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
7687     if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
7688       ExitLimit ItCnt =
7689         computeLoadConstantCompareExitLimit(LI, RHS, L, Pred);
7690       if (ItCnt.hasAnyInfo())
7691         return ItCnt;
7692     }
7693 
7694   const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
7695   const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
7696 
7697   // Try to evaluate any dependencies out of the loop.
7698   LHS = getSCEVAtScope(LHS, L);
7699   RHS = getSCEVAtScope(RHS, L);
7700 
7701   // At this point, we would like to compute how many iterations of the
7702   // loop the predicate will return true for these inputs.
7703   if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
7704     // If there is a loop-invariant, force it into the RHS.
7705     std::swap(LHS, RHS);
7706     Pred = ICmpInst::getSwappedPredicate(Pred);
7707   }
7708 
7709   // Simplify the operands before analyzing them.
7710   (void)SimplifyICmpOperands(Pred, LHS, RHS);
7711 
7712   // If we have a comparison of a chrec against a constant, try to use value
7713   // ranges to answer this query.
7714   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
7715     if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
7716       if (AddRec->getLoop() == L) {
7717         // Form the constant range.
7718         ConstantRange CompRange =
7719             ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt());
7720 
7721         const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
7722         if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
7723       }
7724 
7725   switch (Pred) {
7726   case ICmpInst::ICMP_NE: {                     // while (X != Y)
7727     // Convert to: while (X-Y != 0)
7728     ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit,
7729                                 AllowPredicates);
7730     if (EL.hasAnyInfo()) return EL;
7731     break;
7732   }
7733   case ICmpInst::ICMP_EQ: {                     // while (X == Y)
7734     // Convert to: while (X-Y == 0)
7735     ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
7736     if (EL.hasAnyInfo()) return EL;
7737     break;
7738   }
7739   case ICmpInst::ICMP_SLT:
7740   case ICmpInst::ICMP_ULT: {                    // while (X < Y)
7741     bool IsSigned = Pred == ICmpInst::ICMP_SLT;
7742     ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit,
7743                                     AllowPredicates);
7744     if (EL.hasAnyInfo()) return EL;
7745     break;
7746   }
7747   case ICmpInst::ICMP_SGT:
7748   case ICmpInst::ICMP_UGT: {                    // while (X > Y)
7749     bool IsSigned = Pred == ICmpInst::ICMP_SGT;
7750     ExitLimit EL =
7751         howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
7752                             AllowPredicates);
7753     if (EL.hasAnyInfo()) return EL;
7754     break;
7755   }
7756   default:
7757     break;
7758   }
7759 
7760   auto *ExhaustiveCount =
7761       computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
7762 
7763   if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
7764     return ExhaustiveCount;
7765 
7766   return computeShiftCompareExitLimit(ExitCond->getOperand(0),
7767                                       ExitCond->getOperand(1), L, OriginalPred);
7768 }
7769 
7770 ScalarEvolution::ExitLimit
7771 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
7772                                                       SwitchInst *Switch,
7773                                                       BasicBlock *ExitingBlock,
7774                                                       bool ControlsExit) {
7775   assert(!L->contains(ExitingBlock) && "Not an exiting block!");
7776 
7777   // Give up if the exit is the default dest of a switch.
7778   if (Switch->getDefaultDest() == ExitingBlock)
7779     return getCouldNotCompute();
7780 
7781   assert(L->contains(Switch->getDefaultDest()) &&
7782          "Default case must not exit the loop!");
7783   const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
7784   const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
7785 
7786   // while (X != Y) --> while (X-Y != 0)
7787   ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
7788   if (EL.hasAnyInfo())
7789     return EL;
7790 
7791   return getCouldNotCompute();
7792 }
7793 
7794 static ConstantInt *
7795 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
7796                                 ScalarEvolution &SE) {
7797   const SCEV *InVal = SE.getConstant(C);
7798   const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
7799   assert(isa<SCEVConstant>(Val) &&
7800          "Evaluation of SCEV at constant didn't fold correctly?");
7801   return cast<SCEVConstant>(Val)->getValue();
7802 }
7803 
7804 /// Given an exit condition of 'icmp op load X, cst', try to see if we can
7805 /// compute the backedge execution count.
7806 ScalarEvolution::ExitLimit
7807 ScalarEvolution::computeLoadConstantCompareExitLimit(
7808   LoadInst *LI,
7809   Constant *RHS,
7810   const Loop *L,
7811   ICmpInst::Predicate predicate) {
7812   if (LI->isVolatile()) return getCouldNotCompute();
7813 
7814   // Check to see if the loaded pointer is a getelementptr of a global.
7815   // TODO: Use SCEV instead of manually grubbing with GEPs.
7816   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
7817   if (!GEP) return getCouldNotCompute();
7818 
7819   // Make sure that it is really a constant global we are gepping, with an
7820   // initializer, and make sure the first IDX is really 0.
7821   GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
7822   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
7823       GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
7824       !cast<Constant>(GEP->getOperand(1))->isNullValue())
7825     return getCouldNotCompute();
7826 
7827   // Okay, we allow one non-constant index into the GEP instruction.
7828   Value *VarIdx = nullptr;
7829   std::vector<Constant*> Indexes;
7830   unsigned VarIdxNum = 0;
7831   for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
7832     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
7833       Indexes.push_back(CI);
7834     } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
7835       if (VarIdx) return getCouldNotCompute();  // Multiple non-constant idx's.
7836       VarIdx = GEP->getOperand(i);
7837       VarIdxNum = i-2;
7838       Indexes.push_back(nullptr);
7839     }
7840 
7841   // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
7842   if (!VarIdx)
7843     return getCouldNotCompute();
7844 
7845   // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
7846   // Check to see if X is a loop variant variable value now.
7847   const SCEV *Idx = getSCEV(VarIdx);
7848   Idx = getSCEVAtScope(Idx, L);
7849 
7850   // We can only recognize very limited forms of loop index expressions, in
7851   // particular, only affine AddRec's like {C1,+,C2}<L>.
7852   const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
7853   if (!IdxExpr || IdxExpr->getLoop() != L || !IdxExpr->isAffine() ||
7854       isLoopInvariant(IdxExpr, L) ||
7855       !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
7856       !isa<SCEVConstant>(IdxExpr->getOperand(1)))
7857     return getCouldNotCompute();
7858 
7859   unsigned MaxSteps = MaxBruteForceIterations;
7860   for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
7861     ConstantInt *ItCst = ConstantInt::get(
7862                            cast<IntegerType>(IdxExpr->getType()), IterationNum);
7863     ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
7864 
7865     // Form the GEP offset.
7866     Indexes[VarIdxNum] = Val;
7867 
7868     Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
7869                                                          Indexes);
7870     if (!Result) break;  // Cannot compute!
7871 
7872     // Evaluate the condition for this iteration.
7873     Result = ConstantExpr::getICmp(predicate, Result, RHS);
7874     if (!isa<ConstantInt>(Result)) break;  // Couldn't decide for sure
7875     if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
7876       ++NumArrayLenItCounts;
7877       return getConstant(ItCst);   // Found terminating iteration!
7878     }
7879   }
7880   return getCouldNotCompute();
7881 }
7882 
7883 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
7884     Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
7885   ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
7886   if (!RHS)
7887     return getCouldNotCompute();
7888 
7889   const BasicBlock *Latch = L->getLoopLatch();
7890   if (!Latch)
7891     return getCouldNotCompute();
7892 
7893   const BasicBlock *Predecessor = L->getLoopPredecessor();
7894   if (!Predecessor)
7895     return getCouldNotCompute();
7896 
7897   // Return true if V is of the form "LHS `shift_op` <positive constant>".
7898   // Return LHS in OutLHS and shift_opt in OutOpCode.
7899   auto MatchPositiveShift =
7900       [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
7901 
7902     using namespace PatternMatch;
7903 
7904     ConstantInt *ShiftAmt;
7905     if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7906       OutOpCode = Instruction::LShr;
7907     else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7908       OutOpCode = Instruction::AShr;
7909     else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7910       OutOpCode = Instruction::Shl;
7911     else
7912       return false;
7913 
7914     return ShiftAmt->getValue().isStrictlyPositive();
7915   };
7916 
7917   // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
7918   //
7919   // loop:
7920   //   %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
7921   //   %iv.shifted = lshr i32 %iv, <positive constant>
7922   //
7923   // Return true on a successful match.  Return the corresponding PHI node (%iv
7924   // above) in PNOut and the opcode of the shift operation in OpCodeOut.
7925   auto MatchShiftRecurrence =
7926       [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
7927     Optional<Instruction::BinaryOps> PostShiftOpCode;
7928 
7929     {
7930       Instruction::BinaryOps OpC;
7931       Value *V;
7932 
7933       // If we encounter a shift instruction, "peel off" the shift operation,
7934       // and remember that we did so.  Later when we inspect %iv's backedge
7935       // value, we will make sure that the backedge value uses the same
7936       // operation.
7937       //
7938       // Note: the peeled shift operation does not have to be the same
7939       // instruction as the one feeding into the PHI's backedge value.  We only
7940       // really care about it being the same *kind* of shift instruction --
7941       // that's all that is required for our later inferences to hold.
7942       if (MatchPositiveShift(LHS, V, OpC)) {
7943         PostShiftOpCode = OpC;
7944         LHS = V;
7945       }
7946     }
7947 
7948     PNOut = dyn_cast<PHINode>(LHS);
7949     if (!PNOut || PNOut->getParent() != L->getHeader())
7950       return false;
7951 
7952     Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
7953     Value *OpLHS;
7954 
7955     return
7956         // The backedge value for the PHI node must be a shift by a positive
7957         // amount
7958         MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
7959 
7960         // of the PHI node itself
7961         OpLHS == PNOut &&
7962 
7963         // and the kind of shift should be match the kind of shift we peeled
7964         // off, if any.
7965         (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut);
7966   };
7967 
7968   PHINode *PN;
7969   Instruction::BinaryOps OpCode;
7970   if (!MatchShiftRecurrence(LHS, PN, OpCode))
7971     return getCouldNotCompute();
7972 
7973   const DataLayout &DL = getDataLayout();
7974 
7975   // The key rationale for this optimization is that for some kinds of shift
7976   // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
7977   // within a finite number of iterations.  If the condition guarding the
7978   // backedge (in the sense that the backedge is taken if the condition is true)
7979   // is false for the value the shift recurrence stabilizes to, then we know
7980   // that the backedge is taken only a finite number of times.
7981 
7982   ConstantInt *StableValue = nullptr;
7983   switch (OpCode) {
7984   default:
7985     llvm_unreachable("Impossible case!");
7986 
7987   case Instruction::AShr: {
7988     // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
7989     // bitwidth(K) iterations.
7990     Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
7991     KnownBits Known = computeKnownBits(FirstValue, DL, 0, &AC,
7992                                        Predecessor->getTerminator(), &DT);
7993     auto *Ty = cast<IntegerType>(RHS->getType());
7994     if (Known.isNonNegative())
7995       StableValue = ConstantInt::get(Ty, 0);
7996     else if (Known.isNegative())
7997       StableValue = ConstantInt::get(Ty, -1, true);
7998     else
7999       return getCouldNotCompute();
8000 
8001     break;
8002   }
8003   case Instruction::LShr:
8004   case Instruction::Shl:
8005     // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
8006     // stabilize to 0 in at most bitwidth(K) iterations.
8007     StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
8008     break;
8009   }
8010 
8011   auto *Result =
8012       ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
8013   assert(Result->getType()->isIntegerTy(1) &&
8014          "Otherwise cannot be an operand to a branch instruction");
8015 
8016   if (Result->isZeroValue()) {
8017     unsigned BitWidth = getTypeSizeInBits(RHS->getType());
8018     const SCEV *UpperBound =
8019         getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
8020     return ExitLimit(getCouldNotCompute(), UpperBound, false);
8021   }
8022 
8023   return getCouldNotCompute();
8024 }
8025 
8026 /// Return true if we can constant fold an instruction of the specified type,
8027 /// assuming that all operands were constants.
8028 static bool CanConstantFold(const Instruction *I) {
8029   if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
8030       isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
8031       isa<LoadInst>(I) || isa<ExtractValueInst>(I))
8032     return true;
8033 
8034   if (const CallInst *CI = dyn_cast<CallInst>(I))
8035     if (const Function *F = CI->getCalledFunction())
8036       return canConstantFoldCallTo(CI, F);
8037   return false;
8038 }
8039 
8040 /// Determine whether this instruction can constant evolve within this loop
8041 /// assuming its operands can all constant evolve.
8042 static bool canConstantEvolve(Instruction *I, const Loop *L) {
8043   // An instruction outside of the loop can't be derived from a loop PHI.
8044   if (!L->contains(I)) return false;
8045 
8046   if (isa<PHINode>(I)) {
8047     // We don't currently keep track of the control flow needed to evaluate
8048     // PHIs, so we cannot handle PHIs inside of loops.
8049     return L->getHeader() == I->getParent();
8050   }
8051 
8052   // If we won't be able to constant fold this expression even if the operands
8053   // are constants, bail early.
8054   return CanConstantFold(I);
8055 }
8056 
8057 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
8058 /// recursing through each instruction operand until reaching a loop header phi.
8059 static PHINode *
8060 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
8061                                DenseMap<Instruction *, PHINode *> &PHIMap,
8062                                unsigned Depth) {
8063   if (Depth > MaxConstantEvolvingDepth)
8064     return nullptr;
8065 
8066   // Otherwise, we can evaluate this instruction if all of its operands are
8067   // constant or derived from a PHI node themselves.
8068   PHINode *PHI = nullptr;
8069   for (Value *Op : UseInst->operands()) {
8070     if (isa<Constant>(Op)) continue;
8071 
8072     Instruction *OpInst = dyn_cast<Instruction>(Op);
8073     if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
8074 
8075     PHINode *P = dyn_cast<PHINode>(OpInst);
8076     if (!P)
8077       // If this operand is already visited, reuse the prior result.
8078       // We may have P != PHI if this is the deepest point at which the
8079       // inconsistent paths meet.
8080       P = PHIMap.lookup(OpInst);
8081     if (!P) {
8082       // Recurse and memoize the results, whether a phi is found or not.
8083       // This recursive call invalidates pointers into PHIMap.
8084       P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1);
8085       PHIMap[OpInst] = P;
8086     }
8087     if (!P)
8088       return nullptr;  // Not evolving from PHI
8089     if (PHI && PHI != P)
8090       return nullptr;  // Evolving from multiple different PHIs.
8091     PHI = P;
8092   }
8093   // This is a expression evolving from a constant PHI!
8094   return PHI;
8095 }
8096 
8097 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
8098 /// in the loop that V is derived from.  We allow arbitrary operations along the
8099 /// way, but the operands of an operation must either be constants or a value
8100 /// derived from a constant PHI.  If this expression does not fit with these
8101 /// constraints, return null.
8102 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
8103   Instruction *I = dyn_cast<Instruction>(V);
8104   if (!I || !canConstantEvolve(I, L)) return nullptr;
8105 
8106   if (PHINode *PN = dyn_cast<PHINode>(I))
8107     return PN;
8108 
8109   // Record non-constant instructions contained by the loop.
8110   DenseMap<Instruction *, PHINode *> PHIMap;
8111   return getConstantEvolvingPHIOperands(I, L, PHIMap, 0);
8112 }
8113 
8114 /// EvaluateExpression - Given an expression that passes the
8115 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
8116 /// in the loop has the value PHIVal.  If we can't fold this expression for some
8117 /// reason, return null.
8118 static Constant *EvaluateExpression(Value *V, const Loop *L,
8119                                     DenseMap<Instruction *, Constant *> &Vals,
8120                                     const DataLayout &DL,
8121                                     const TargetLibraryInfo *TLI) {
8122   // Convenient constant check, but redundant for recursive calls.
8123   if (Constant *C = dyn_cast<Constant>(V)) return C;
8124   Instruction *I = dyn_cast<Instruction>(V);
8125   if (!I) return nullptr;
8126 
8127   if (Constant *C = Vals.lookup(I)) return C;
8128 
8129   // An instruction inside the loop depends on a value outside the loop that we
8130   // weren't given a mapping for, or a value such as a call inside the loop.
8131   if (!canConstantEvolve(I, L)) return nullptr;
8132 
8133   // An unmapped PHI can be due to a branch or another loop inside this loop,
8134   // or due to this not being the initial iteration through a loop where we
8135   // couldn't compute the evolution of this particular PHI last time.
8136   if (isa<PHINode>(I)) return nullptr;
8137 
8138   std::vector<Constant*> Operands(I->getNumOperands());
8139 
8140   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
8141     Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
8142     if (!Operand) {
8143       Operands[i] = dyn_cast<Constant>(I->getOperand(i));
8144       if (!Operands[i]) return nullptr;
8145       continue;
8146     }
8147     Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
8148     Vals[Operand] = C;
8149     if (!C) return nullptr;
8150     Operands[i] = C;
8151   }
8152 
8153   if (CmpInst *CI = dyn_cast<CmpInst>(I))
8154     return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
8155                                            Operands[1], DL, TLI);
8156   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
8157     if (!LI->isVolatile())
8158       return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
8159   }
8160   return ConstantFoldInstOperands(I, Operands, DL, TLI);
8161 }
8162 
8163 
8164 // If every incoming value to PN except the one for BB is a specific Constant,
8165 // return that, else return nullptr.
8166 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
8167   Constant *IncomingVal = nullptr;
8168 
8169   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
8170     if (PN->getIncomingBlock(i) == BB)
8171       continue;
8172 
8173     auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
8174     if (!CurrentVal)
8175       return nullptr;
8176 
8177     if (IncomingVal != CurrentVal) {
8178       if (IncomingVal)
8179         return nullptr;
8180       IncomingVal = CurrentVal;
8181     }
8182   }
8183 
8184   return IncomingVal;
8185 }
8186 
8187 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
8188 /// in the header of its containing loop, we know the loop executes a
8189 /// constant number of times, and the PHI node is just a recurrence
8190 /// involving constants, fold it.
8191 Constant *
8192 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
8193                                                    const APInt &BEs,
8194                                                    const Loop *L) {
8195   auto I = ConstantEvolutionLoopExitValue.find(PN);
8196   if (I != ConstantEvolutionLoopExitValue.end())
8197     return I->second;
8198 
8199   if (BEs.ugt(MaxBruteForceIterations))
8200     return ConstantEvolutionLoopExitValue[PN] = nullptr;  // Not going to evaluate it.
8201 
8202   Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
8203 
8204   DenseMap<Instruction *, Constant *> CurrentIterVals;
8205   BasicBlock *Header = L->getHeader();
8206   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
8207 
8208   BasicBlock *Latch = L->getLoopLatch();
8209   if (!Latch)
8210     return nullptr;
8211 
8212   for (PHINode &PHI : Header->phis()) {
8213     if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
8214       CurrentIterVals[&PHI] = StartCST;
8215   }
8216   if (!CurrentIterVals.count(PN))
8217     return RetVal = nullptr;
8218 
8219   Value *BEValue = PN->getIncomingValueForBlock(Latch);
8220 
8221   // Execute the loop symbolically to determine the exit value.
8222   assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) &&
8223          "BEs is <= MaxBruteForceIterations which is an 'unsigned'!");
8224 
8225   unsigned NumIterations = BEs.getZExtValue(); // must be in range
8226   unsigned IterationNum = 0;
8227   const DataLayout &DL = getDataLayout();
8228   for (; ; ++IterationNum) {
8229     if (IterationNum == NumIterations)
8230       return RetVal = CurrentIterVals[PN];  // Got exit value!
8231 
8232     // Compute the value of the PHIs for the next iteration.
8233     // EvaluateExpression adds non-phi values to the CurrentIterVals map.
8234     DenseMap<Instruction *, Constant *> NextIterVals;
8235     Constant *NextPHI =
8236         EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
8237     if (!NextPHI)
8238       return nullptr;        // Couldn't evaluate!
8239     NextIterVals[PN] = NextPHI;
8240 
8241     bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
8242 
8243     // Also evaluate the other PHI nodes.  However, we don't get to stop if we
8244     // cease to be able to evaluate one of them or if they stop evolving,
8245     // because that doesn't necessarily prevent us from computing PN.
8246     SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
8247     for (const auto &I : CurrentIterVals) {
8248       PHINode *PHI = dyn_cast<PHINode>(I.first);
8249       if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
8250       PHIsToCompute.emplace_back(PHI, I.second);
8251     }
8252     // We use two distinct loops because EvaluateExpression may invalidate any
8253     // iterators into CurrentIterVals.
8254     for (const auto &I : PHIsToCompute) {
8255       PHINode *PHI = I.first;
8256       Constant *&NextPHI = NextIterVals[PHI];
8257       if (!NextPHI) {   // Not already computed.
8258         Value *BEValue = PHI->getIncomingValueForBlock(Latch);
8259         NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
8260       }
8261       if (NextPHI != I.second)
8262         StoppedEvolving = false;
8263     }
8264 
8265     // If all entries in CurrentIterVals == NextIterVals then we can stop
8266     // iterating, the loop can't continue to change.
8267     if (StoppedEvolving)
8268       return RetVal = CurrentIterVals[PN];
8269 
8270     CurrentIterVals.swap(NextIterVals);
8271   }
8272 }
8273 
8274 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
8275                                                           Value *Cond,
8276                                                           bool ExitWhen) {
8277   PHINode *PN = getConstantEvolvingPHI(Cond, L);
8278   if (!PN) return getCouldNotCompute();
8279 
8280   // If the loop is canonicalized, the PHI will have exactly two entries.
8281   // That's the only form we support here.
8282   if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
8283 
8284   DenseMap<Instruction *, Constant *> CurrentIterVals;
8285   BasicBlock *Header = L->getHeader();
8286   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
8287 
8288   BasicBlock *Latch = L->getLoopLatch();
8289   assert(Latch && "Should follow from NumIncomingValues == 2!");
8290 
8291   for (PHINode &PHI : Header->phis()) {
8292     if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
8293       CurrentIterVals[&PHI] = StartCST;
8294   }
8295   if (!CurrentIterVals.count(PN))
8296     return getCouldNotCompute();
8297 
8298   // Okay, we find a PHI node that defines the trip count of this loop.  Execute
8299   // the loop symbolically to determine when the condition gets a value of
8300   // "ExitWhen".
8301   unsigned MaxIterations = MaxBruteForceIterations;   // Limit analysis.
8302   const DataLayout &DL = getDataLayout();
8303   for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
8304     auto *CondVal = dyn_cast_or_null<ConstantInt>(
8305         EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
8306 
8307     // Couldn't symbolically evaluate.
8308     if (!CondVal) return getCouldNotCompute();
8309 
8310     if (CondVal->getValue() == uint64_t(ExitWhen)) {
8311       ++NumBruteForceTripCountsComputed;
8312       return getConstant(Type::getInt32Ty(getContext()), IterationNum);
8313     }
8314 
8315     // Update all the PHI nodes for the next iteration.
8316     DenseMap<Instruction *, Constant *> NextIterVals;
8317 
8318     // Create a list of which PHIs we need to compute. We want to do this before
8319     // calling EvaluateExpression on them because that may invalidate iterators
8320     // into CurrentIterVals.
8321     SmallVector<PHINode *, 8> PHIsToCompute;
8322     for (const auto &I : CurrentIterVals) {
8323       PHINode *PHI = dyn_cast<PHINode>(I.first);
8324       if (!PHI || PHI->getParent() != Header) continue;
8325       PHIsToCompute.push_back(PHI);
8326     }
8327     for (PHINode *PHI : PHIsToCompute) {
8328       Constant *&NextPHI = NextIterVals[PHI];
8329       if (NextPHI) continue;    // Already computed!
8330 
8331       Value *BEValue = PHI->getIncomingValueForBlock(Latch);
8332       NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
8333     }
8334     CurrentIterVals.swap(NextIterVals);
8335   }
8336 
8337   // Too many iterations were needed to evaluate.
8338   return getCouldNotCompute();
8339 }
8340 
8341 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
8342   SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
8343       ValuesAtScopes[V];
8344   // Check to see if we've folded this expression at this loop before.
8345   for (auto &LS : Values)
8346     if (LS.first == L)
8347       return LS.second ? LS.second : V;
8348 
8349   Values.emplace_back(L, nullptr);
8350 
8351   // Otherwise compute it.
8352   const SCEV *C = computeSCEVAtScope(V, L);
8353   for (auto &LS : reverse(ValuesAtScopes[V]))
8354     if (LS.first == L) {
8355       LS.second = C;
8356       break;
8357     }
8358   return C;
8359 }
8360 
8361 /// This builds up a Constant using the ConstantExpr interface.  That way, we
8362 /// will return Constants for objects which aren't represented by a
8363 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
8364 /// Returns NULL if the SCEV isn't representable as a Constant.
8365 static Constant *BuildConstantFromSCEV(const SCEV *V) {
8366   switch (V->getSCEVType()) {
8367   case scCouldNotCompute:
8368   case scAddRecExpr:
8369     return nullptr;
8370   case scConstant:
8371     return cast<SCEVConstant>(V)->getValue();
8372   case scUnknown:
8373     return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
8374   case scSignExtend: {
8375     const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
8376     if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
8377       return ConstantExpr::getSExt(CastOp, SS->getType());
8378     return nullptr;
8379   }
8380   case scZeroExtend: {
8381     const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
8382     if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
8383       return ConstantExpr::getZExt(CastOp, SZ->getType());
8384     return nullptr;
8385   }
8386   case scPtrToInt: {
8387     const SCEVPtrToIntExpr *P2I = cast<SCEVPtrToIntExpr>(V);
8388     if (Constant *CastOp = BuildConstantFromSCEV(P2I->getOperand()))
8389       return ConstantExpr::getPtrToInt(CastOp, P2I->getType());
8390 
8391     return nullptr;
8392   }
8393   case scTruncate: {
8394     const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
8395     if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
8396       return ConstantExpr::getTrunc(CastOp, ST->getType());
8397     return nullptr;
8398   }
8399   case scAddExpr: {
8400     const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
8401     if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
8402       if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
8403         unsigned AS = PTy->getAddressSpace();
8404         Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
8405         C = ConstantExpr::getBitCast(C, DestPtrTy);
8406       }
8407       for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
8408         Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
8409         if (!C2)
8410           return nullptr;
8411 
8412         // First pointer!
8413         if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
8414           unsigned AS = C2->getType()->getPointerAddressSpace();
8415           std::swap(C, C2);
8416           Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
8417           // The offsets have been converted to bytes.  We can add bytes to an
8418           // i8* by GEP with the byte count in the first index.
8419           C = ConstantExpr::getBitCast(C, DestPtrTy);
8420         }
8421 
8422         // Don't bother trying to sum two pointers. We probably can't
8423         // statically compute a load that results from it anyway.
8424         if (C2->getType()->isPointerTy())
8425           return nullptr;
8426 
8427         if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
8428           if (PTy->getElementType()->isStructTy())
8429             C2 = ConstantExpr::getIntegerCast(
8430                 C2, Type::getInt32Ty(C->getContext()), true);
8431           C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2);
8432         } else
8433           C = ConstantExpr::getAdd(C, C2);
8434       }
8435       return C;
8436     }
8437     return nullptr;
8438   }
8439   case scMulExpr: {
8440     const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
8441     if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
8442       // Don't bother with pointers at all.
8443       if (C->getType()->isPointerTy())
8444         return nullptr;
8445       for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
8446         Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
8447         if (!C2 || C2->getType()->isPointerTy())
8448           return nullptr;
8449         C = ConstantExpr::getMul(C, C2);
8450       }
8451       return C;
8452     }
8453     return nullptr;
8454   }
8455   case scUDivExpr: {
8456     const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
8457     if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
8458       if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
8459         if (LHS->getType() == RHS->getType())
8460           return ConstantExpr::getUDiv(LHS, RHS);
8461     return nullptr;
8462   }
8463   case scSMaxExpr:
8464   case scUMaxExpr:
8465   case scSMinExpr:
8466   case scUMinExpr:
8467     return nullptr; // TODO: smax, umax, smin, umax.
8468   }
8469   llvm_unreachable("Unknown SCEV kind!");
8470 }
8471 
8472 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
8473   if (isa<SCEVConstant>(V)) return V;
8474 
8475   // If this instruction is evolved from a constant-evolving PHI, compute the
8476   // exit value from the loop without using SCEVs.
8477   if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
8478     if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
8479       if (PHINode *PN = dyn_cast<PHINode>(I)) {
8480         const Loop *CurrLoop = this->LI[I->getParent()];
8481         // Looking for loop exit value.
8482         if (CurrLoop && CurrLoop->getParentLoop() == L &&
8483             PN->getParent() == CurrLoop->getHeader()) {
8484           // Okay, there is no closed form solution for the PHI node.  Check
8485           // to see if the loop that contains it has a known backedge-taken
8486           // count.  If so, we may be able to force computation of the exit
8487           // value.
8488           const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop);
8489           // This trivial case can show up in some degenerate cases where
8490           // the incoming IR has not yet been fully simplified.
8491           if (BackedgeTakenCount->isZero()) {
8492             Value *InitValue = nullptr;
8493             bool MultipleInitValues = false;
8494             for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
8495               if (!CurrLoop->contains(PN->getIncomingBlock(i))) {
8496                 if (!InitValue)
8497                   InitValue = PN->getIncomingValue(i);
8498                 else if (InitValue != PN->getIncomingValue(i)) {
8499                   MultipleInitValues = true;
8500                   break;
8501                 }
8502               }
8503             }
8504             if (!MultipleInitValues && InitValue)
8505               return getSCEV(InitValue);
8506           }
8507           // Do we have a loop invariant value flowing around the backedge
8508           // for a loop which must execute the backedge?
8509           if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
8510               isKnownPositive(BackedgeTakenCount) &&
8511               PN->getNumIncomingValues() == 2) {
8512 
8513             unsigned InLoopPred =
8514                 CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1;
8515             Value *BackedgeVal = PN->getIncomingValue(InLoopPred);
8516             if (CurrLoop->isLoopInvariant(BackedgeVal))
8517               return getSCEV(BackedgeVal);
8518           }
8519           if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
8520             // Okay, we know how many times the containing loop executes.  If
8521             // this is a constant evolving PHI node, get the final value at
8522             // the specified iteration number.
8523             Constant *RV = getConstantEvolutionLoopExitValue(
8524                 PN, BTCC->getAPInt(), CurrLoop);
8525             if (RV) return getSCEV(RV);
8526           }
8527         }
8528 
8529         // If there is a single-input Phi, evaluate it at our scope. If we can
8530         // prove that this replacement does not break LCSSA form, use new value.
8531         if (PN->getNumOperands() == 1) {
8532           const SCEV *Input = getSCEV(PN->getOperand(0));
8533           const SCEV *InputAtScope = getSCEVAtScope(Input, L);
8534           // TODO: We can generalize it using LI.replacementPreservesLCSSAForm,
8535           // for the simplest case just support constants.
8536           if (isa<SCEVConstant>(InputAtScope)) return InputAtScope;
8537         }
8538       }
8539 
8540       // Okay, this is an expression that we cannot symbolically evaluate
8541       // into a SCEV.  Check to see if it's possible to symbolically evaluate
8542       // the arguments into constants, and if so, try to constant propagate the
8543       // result.  This is particularly useful for computing loop exit values.
8544       if (CanConstantFold(I)) {
8545         SmallVector<Constant *, 4> Operands;
8546         bool MadeImprovement = false;
8547         for (Value *Op : I->operands()) {
8548           if (Constant *C = dyn_cast<Constant>(Op)) {
8549             Operands.push_back(C);
8550             continue;
8551           }
8552 
8553           // If any of the operands is non-constant and if they are
8554           // non-integer and non-pointer, don't even try to analyze them
8555           // with scev techniques.
8556           if (!isSCEVable(Op->getType()))
8557             return V;
8558 
8559           const SCEV *OrigV = getSCEV(Op);
8560           const SCEV *OpV = getSCEVAtScope(OrigV, L);
8561           MadeImprovement |= OrigV != OpV;
8562 
8563           Constant *C = BuildConstantFromSCEV(OpV);
8564           if (!C) return V;
8565           if (C->getType() != Op->getType())
8566             C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
8567                                                               Op->getType(),
8568                                                               false),
8569                                       C, Op->getType());
8570           Operands.push_back(C);
8571         }
8572 
8573         // Check to see if getSCEVAtScope actually made an improvement.
8574         if (MadeImprovement) {
8575           Constant *C = nullptr;
8576           const DataLayout &DL = getDataLayout();
8577           if (const CmpInst *CI = dyn_cast<CmpInst>(I))
8578             C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
8579                                                 Operands[1], DL, &TLI);
8580           else if (const LoadInst *Load = dyn_cast<LoadInst>(I)) {
8581             if (!Load->isVolatile())
8582               C = ConstantFoldLoadFromConstPtr(Operands[0], Load->getType(),
8583                                                DL);
8584           } else
8585             C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
8586           if (!C) return V;
8587           return getSCEV(C);
8588         }
8589       }
8590     }
8591 
8592     // This is some other type of SCEVUnknown, just return it.
8593     return V;
8594   }
8595 
8596   if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
8597     // Avoid performing the look-up in the common case where the specified
8598     // expression has no loop-variant portions.
8599     for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
8600       const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
8601       if (OpAtScope != Comm->getOperand(i)) {
8602         // Okay, at least one of these operands is loop variant but might be
8603         // foldable.  Build a new instance of the folded commutative expression.
8604         SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
8605                                             Comm->op_begin()+i);
8606         NewOps.push_back(OpAtScope);
8607 
8608         for (++i; i != e; ++i) {
8609           OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
8610           NewOps.push_back(OpAtScope);
8611         }
8612         if (isa<SCEVAddExpr>(Comm))
8613           return getAddExpr(NewOps, Comm->getNoWrapFlags());
8614         if (isa<SCEVMulExpr>(Comm))
8615           return getMulExpr(NewOps, Comm->getNoWrapFlags());
8616         if (isa<SCEVMinMaxExpr>(Comm))
8617           return getMinMaxExpr(Comm->getSCEVType(), NewOps);
8618         llvm_unreachable("Unknown commutative SCEV type!");
8619       }
8620     }
8621     // If we got here, all operands are loop invariant.
8622     return Comm;
8623   }
8624 
8625   if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
8626     const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
8627     const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
8628     if (LHS == Div->getLHS() && RHS == Div->getRHS())
8629       return Div;   // must be loop invariant
8630     return getUDivExpr(LHS, RHS);
8631   }
8632 
8633   // If this is a loop recurrence for a loop that does not contain L, then we
8634   // are dealing with the final value computed by the loop.
8635   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
8636     // First, attempt to evaluate each operand.
8637     // Avoid performing the look-up in the common case where the specified
8638     // expression has no loop-variant portions.
8639     for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
8640       const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
8641       if (OpAtScope == AddRec->getOperand(i))
8642         continue;
8643 
8644       // Okay, at least one of these operands is loop variant but might be
8645       // foldable.  Build a new instance of the folded commutative expression.
8646       SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
8647                                           AddRec->op_begin()+i);
8648       NewOps.push_back(OpAtScope);
8649       for (++i; i != e; ++i)
8650         NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
8651 
8652       const SCEV *FoldedRec =
8653         getAddRecExpr(NewOps, AddRec->getLoop(),
8654                       AddRec->getNoWrapFlags(SCEV::FlagNW));
8655       AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
8656       // The addrec may be folded to a nonrecurrence, for example, if the
8657       // induction variable is multiplied by zero after constant folding. Go
8658       // ahead and return the folded value.
8659       if (!AddRec)
8660         return FoldedRec;
8661       break;
8662     }
8663 
8664     // If the scope is outside the addrec's loop, evaluate it by using the
8665     // loop exit value of the addrec.
8666     if (!AddRec->getLoop()->contains(L)) {
8667       // To evaluate this recurrence, we need to know how many times the AddRec
8668       // loop iterates.  Compute this now.
8669       const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
8670       if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
8671 
8672       // Then, evaluate the AddRec.
8673       return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
8674     }
8675 
8676     return AddRec;
8677   }
8678 
8679   if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
8680     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8681     if (Op == Cast->getOperand())
8682       return Cast;  // must be loop invariant
8683     return getZeroExtendExpr(Op, Cast->getType());
8684   }
8685 
8686   if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
8687     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8688     if (Op == Cast->getOperand())
8689       return Cast;  // must be loop invariant
8690     return getSignExtendExpr(Op, Cast->getType());
8691   }
8692 
8693   if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
8694     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8695     if (Op == Cast->getOperand())
8696       return Cast;  // must be loop invariant
8697     return getTruncateExpr(Op, Cast->getType());
8698   }
8699 
8700   if (const SCEVPtrToIntExpr *Cast = dyn_cast<SCEVPtrToIntExpr>(V)) {
8701     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8702     if (Op == Cast->getOperand())
8703       return Cast; // must be loop invariant
8704     return getPtrToIntExpr(Op, Cast->getType());
8705   }
8706 
8707   llvm_unreachable("Unknown SCEV type!");
8708 }
8709 
8710 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
8711   return getSCEVAtScope(getSCEV(V), L);
8712 }
8713 
8714 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const {
8715   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S))
8716     return stripInjectiveFunctions(ZExt->getOperand());
8717   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S))
8718     return stripInjectiveFunctions(SExt->getOperand());
8719   return S;
8720 }
8721 
8722 /// Finds the minimum unsigned root of the following equation:
8723 ///
8724 ///     A * X = B (mod N)
8725 ///
8726 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
8727 /// A and B isn't important.
8728 ///
8729 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
8730 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B,
8731                                                ScalarEvolution &SE) {
8732   uint32_t BW = A.getBitWidth();
8733   assert(BW == SE.getTypeSizeInBits(B->getType()));
8734   assert(A != 0 && "A must be non-zero.");
8735 
8736   // 1. D = gcd(A, N)
8737   //
8738   // The gcd of A and N may have only one prime factor: 2. The number of
8739   // trailing zeros in A is its multiplicity
8740   uint32_t Mult2 = A.countTrailingZeros();
8741   // D = 2^Mult2
8742 
8743   // 2. Check if B is divisible by D.
8744   //
8745   // B is divisible by D if and only if the multiplicity of prime factor 2 for B
8746   // is not less than multiplicity of this prime factor for D.
8747   if (SE.GetMinTrailingZeros(B) < Mult2)
8748     return SE.getCouldNotCompute();
8749 
8750   // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
8751   // modulo (N / D).
8752   //
8753   // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
8754   // (N / D) in general. The inverse itself always fits into BW bits, though,
8755   // so we immediately truncate it.
8756   APInt AD = A.lshr(Mult2).zext(BW + 1);  // AD = A / D
8757   APInt Mod(BW + 1, 0);
8758   Mod.setBit(BW - Mult2);  // Mod = N / D
8759   APInt I = AD.multiplicativeInverse(Mod).trunc(BW);
8760 
8761   // 4. Compute the minimum unsigned root of the equation:
8762   // I * (B / D) mod (N / D)
8763   // To simplify the computation, we factor out the divide by D:
8764   // (I * B mod N) / D
8765   const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
8766   return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
8767 }
8768 
8769 /// For a given quadratic addrec, generate coefficients of the corresponding
8770 /// quadratic equation, multiplied by a common value to ensure that they are
8771 /// integers.
8772 /// The returned value is a tuple { A, B, C, M, BitWidth }, where
8773 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C
8774 /// were multiplied by, and BitWidth is the bit width of the original addrec
8775 /// coefficients.
8776 /// This function returns None if the addrec coefficients are not compile-
8777 /// time constants.
8778 static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>>
8779 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) {
8780   assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
8781   const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
8782   const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
8783   const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
8784   LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: "
8785                     << *AddRec << '\n');
8786 
8787   // We currently can only solve this if the coefficients are constants.
8788   if (!LC || !MC || !NC) {
8789     LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n");
8790     return None;
8791   }
8792 
8793   APInt L = LC->getAPInt();
8794   APInt M = MC->getAPInt();
8795   APInt N = NC->getAPInt();
8796   assert(!N.isNullValue() && "This is not a quadratic addrec");
8797 
8798   unsigned BitWidth = LC->getAPInt().getBitWidth();
8799   unsigned NewWidth = BitWidth + 1;
8800   LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: "
8801                     << BitWidth << '\n');
8802   // The sign-extension (as opposed to a zero-extension) here matches the
8803   // extension used in SolveQuadraticEquationWrap (with the same motivation).
8804   N = N.sext(NewWidth);
8805   M = M.sext(NewWidth);
8806   L = L.sext(NewWidth);
8807 
8808   // The increments are M, M+N, M+2N, ..., so the accumulated values are
8809   //   L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is,
8810   //   L+M, L+2M+N, L+3M+3N, ...
8811   // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N.
8812   //
8813   // The equation Acc = 0 is then
8814   //   L + nM + n(n-1)/2 N = 0,  or  2L + 2M n + n(n-1) N = 0.
8815   // In a quadratic form it becomes:
8816   //   N n^2 + (2M-N) n + 2L = 0.
8817 
8818   APInt A = N;
8819   APInt B = 2 * M - A;
8820   APInt C = 2 * L;
8821   APInt T = APInt(NewWidth, 2);
8822   LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B
8823                     << "x + " << C << ", coeff bw: " << NewWidth
8824                     << ", multiplied by " << T << '\n');
8825   return std::make_tuple(A, B, C, T, BitWidth);
8826 }
8827 
8828 /// Helper function to compare optional APInts:
8829 /// (a) if X and Y both exist, return min(X, Y),
8830 /// (b) if neither X nor Y exist, return None,
8831 /// (c) if exactly one of X and Y exists, return that value.
8832 static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) {
8833   if (X.hasValue() && Y.hasValue()) {
8834     unsigned W = std::max(X->getBitWidth(), Y->getBitWidth());
8835     APInt XW = X->sextOrSelf(W);
8836     APInt YW = Y->sextOrSelf(W);
8837     return XW.slt(YW) ? *X : *Y;
8838   }
8839   if (!X.hasValue() && !Y.hasValue())
8840     return None;
8841   return X.hasValue() ? *X : *Y;
8842 }
8843 
8844 /// Helper function to truncate an optional APInt to a given BitWidth.
8845 /// When solving addrec-related equations, it is preferable to return a value
8846 /// that has the same bit width as the original addrec's coefficients. If the
8847 /// solution fits in the original bit width, truncate it (except for i1).
8848 /// Returning a value of a different bit width may inhibit some optimizations.
8849 ///
8850 /// In general, a solution to a quadratic equation generated from an addrec
8851 /// may require BW+1 bits, where BW is the bit width of the addrec's
8852 /// coefficients. The reason is that the coefficients of the quadratic
8853 /// equation are BW+1 bits wide (to avoid truncation when converting from
8854 /// the addrec to the equation).
8855 static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) {
8856   if (!X.hasValue())
8857     return None;
8858   unsigned W = X->getBitWidth();
8859   if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth))
8860     return X->trunc(BitWidth);
8861   return X;
8862 }
8863 
8864 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n
8865 /// iterations. The values L, M, N are assumed to be signed, and they
8866 /// should all have the same bit widths.
8867 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW,
8868 /// where BW is the bit width of the addrec's coefficients.
8869 /// If the calculated value is a BW-bit integer (for BW > 1), it will be
8870 /// returned as such, otherwise the bit width of the returned value may
8871 /// be greater than BW.
8872 ///
8873 /// This function returns None if
8874 /// (a) the addrec coefficients are not constant, or
8875 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases
8876 ///     like x^2 = 5, no integer solutions exist, in other cases an integer
8877 ///     solution may exist, but SolveQuadraticEquationWrap may fail to find it.
8878 static Optional<APInt>
8879 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
8880   APInt A, B, C, M;
8881   unsigned BitWidth;
8882   auto T = GetQuadraticEquation(AddRec);
8883   if (!T.hasValue())
8884     return None;
8885 
8886   std::tie(A, B, C, M, BitWidth) = *T;
8887   LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n");
8888   Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1);
8889   if (!X.hasValue())
8890     return None;
8891 
8892   ConstantInt *CX = ConstantInt::get(SE.getContext(), *X);
8893   ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE);
8894   if (!V->isZero())
8895     return None;
8896 
8897   return TruncIfPossible(X, BitWidth);
8898 }
8899 
8900 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n
8901 /// iterations. The values M, N are assumed to be signed, and they
8902 /// should all have the same bit widths.
8903 /// Find the least n such that c(n) does not belong to the given range,
8904 /// while c(n-1) does.
8905 ///
8906 /// This function returns None if
8907 /// (a) the addrec coefficients are not constant, or
8908 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the
8909 ///     bounds of the range.
8910 static Optional<APInt>
8911 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec,
8912                           const ConstantRange &Range, ScalarEvolution &SE) {
8913   assert(AddRec->getOperand(0)->isZero() &&
8914          "Starting value of addrec should be 0");
8915   LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range "
8916                     << Range << ", addrec " << *AddRec << '\n');
8917   // This case is handled in getNumIterationsInRange. Here we can assume that
8918   // we start in the range.
8919   assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) &&
8920          "Addrec's initial value should be in range");
8921 
8922   APInt A, B, C, M;
8923   unsigned BitWidth;
8924   auto T = GetQuadraticEquation(AddRec);
8925   if (!T.hasValue())
8926     return None;
8927 
8928   // Be careful about the return value: there can be two reasons for not
8929   // returning an actual number. First, if no solutions to the equations
8930   // were found, and second, if the solutions don't leave the given range.
8931   // The first case means that the actual solution is "unknown", the second
8932   // means that it's known, but not valid. If the solution is unknown, we
8933   // cannot make any conclusions.
8934   // Return a pair: the optional solution and a flag indicating if the
8935   // solution was found.
8936   auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> {
8937     // Solve for signed overflow and unsigned overflow, pick the lower
8938     // solution.
8939     LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary "
8940                       << Bound << " (before multiplying by " << M << ")\n");
8941     Bound *= M; // The quadratic equation multiplier.
8942 
8943     Optional<APInt> SO = None;
8944     if (BitWidth > 1) {
8945       LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
8946                            "signed overflow\n");
8947       SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth);
8948     }
8949     LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
8950                          "unsigned overflow\n");
8951     Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound,
8952                                                               BitWidth+1);
8953 
8954     auto LeavesRange = [&] (const APInt &X) {
8955       ConstantInt *C0 = ConstantInt::get(SE.getContext(), X);
8956       ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE);
8957       if (Range.contains(V0->getValue()))
8958         return false;
8959       // X should be at least 1, so X-1 is non-negative.
8960       ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1);
8961       ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE);
8962       if (Range.contains(V1->getValue()))
8963         return true;
8964       return false;
8965     };
8966 
8967     // If SolveQuadraticEquationWrap returns None, it means that there can
8968     // be a solution, but the function failed to find it. We cannot treat it
8969     // as "no solution".
8970     if (!SO.hasValue() || !UO.hasValue())
8971       return { None, false };
8972 
8973     // Check the smaller value first to see if it leaves the range.
8974     // At this point, both SO and UO must have values.
8975     Optional<APInt> Min = MinOptional(SO, UO);
8976     if (LeavesRange(*Min))
8977       return { Min, true };
8978     Optional<APInt> Max = Min == SO ? UO : SO;
8979     if (LeavesRange(*Max))
8980       return { Max, true };
8981 
8982     // Solutions were found, but were eliminated, hence the "true".
8983     return { None, true };
8984   };
8985 
8986   std::tie(A, B, C, M, BitWidth) = *T;
8987   // Lower bound is inclusive, subtract 1 to represent the exiting value.
8988   APInt Lower = Range.getLower().sextOrSelf(A.getBitWidth()) - 1;
8989   APInt Upper = Range.getUpper().sextOrSelf(A.getBitWidth());
8990   auto SL = SolveForBoundary(Lower);
8991   auto SU = SolveForBoundary(Upper);
8992   // If any of the solutions was unknown, no meaninigful conclusions can
8993   // be made.
8994   if (!SL.second || !SU.second)
8995     return None;
8996 
8997   // Claim: The correct solution is not some value between Min and Max.
8998   //
8999   // Justification: Assuming that Min and Max are different values, one of
9000   // them is when the first signed overflow happens, the other is when the
9001   // first unsigned overflow happens. Crossing the range boundary is only
9002   // possible via an overflow (treating 0 as a special case of it, modeling
9003   // an overflow as crossing k*2^W for some k).
9004   //
9005   // The interesting case here is when Min was eliminated as an invalid
9006   // solution, but Max was not. The argument is that if there was another
9007   // overflow between Min and Max, it would also have been eliminated if
9008   // it was considered.
9009   //
9010   // For a given boundary, it is possible to have two overflows of the same
9011   // type (signed/unsigned) without having the other type in between: this
9012   // can happen when the vertex of the parabola is between the iterations
9013   // corresponding to the overflows. This is only possible when the two
9014   // overflows cross k*2^W for the same k. In such case, if the second one
9015   // left the range (and was the first one to do so), the first overflow
9016   // would have to enter the range, which would mean that either we had left
9017   // the range before or that we started outside of it. Both of these cases
9018   // are contradictions.
9019   //
9020   // Claim: In the case where SolveForBoundary returns None, the correct
9021   // solution is not some value between the Max for this boundary and the
9022   // Min of the other boundary.
9023   //
9024   // Justification: Assume that we had such Max_A and Min_B corresponding
9025   // to range boundaries A and B and such that Max_A < Min_B. If there was
9026   // a solution between Max_A and Min_B, it would have to be caused by an
9027   // overflow corresponding to either A or B. It cannot correspond to B,
9028   // since Min_B is the first occurrence of such an overflow. If it
9029   // corresponded to A, it would have to be either a signed or an unsigned
9030   // overflow that is larger than both eliminated overflows for A. But
9031   // between the eliminated overflows and this overflow, the values would
9032   // cover the entire value space, thus crossing the other boundary, which
9033   // is a contradiction.
9034 
9035   return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth);
9036 }
9037 
9038 ScalarEvolution::ExitLimit
9039 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit,
9040                               bool AllowPredicates) {
9041 
9042   // This is only used for loops with a "x != y" exit test. The exit condition
9043   // is now expressed as a single expression, V = x-y. So the exit test is
9044   // effectively V != 0.  We know and take advantage of the fact that this
9045   // expression only being used in a comparison by zero context.
9046 
9047   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
9048   // If the value is a constant
9049   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
9050     // If the value is already zero, the branch will execute zero times.
9051     if (C->getValue()->isZero()) return C;
9052     return getCouldNotCompute();  // Otherwise it will loop infinitely.
9053   }
9054 
9055   const SCEVAddRecExpr *AddRec =
9056       dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V));
9057 
9058   if (!AddRec && AllowPredicates)
9059     // Try to make this an AddRec using runtime tests, in the first X
9060     // iterations of this loop, where X is the SCEV expression found by the
9061     // algorithm below.
9062     AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
9063 
9064   if (!AddRec || AddRec->getLoop() != L)
9065     return getCouldNotCompute();
9066 
9067   // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
9068   // the quadratic equation to solve it.
9069   if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
9070     // We can only use this value if the chrec ends up with an exact zero
9071     // value at this index.  When solving for "X*X != 5", for example, we
9072     // should not accept a root of 2.
9073     if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) {
9074       const auto *R = cast<SCEVConstant>(getConstant(S.getValue()));
9075       return ExitLimit(R, R, false, Predicates);
9076     }
9077     return getCouldNotCompute();
9078   }
9079 
9080   // Otherwise we can only handle this if it is affine.
9081   if (!AddRec->isAffine())
9082     return getCouldNotCompute();
9083 
9084   // If this is an affine expression, the execution count of this branch is
9085   // the minimum unsigned root of the following equation:
9086   //
9087   //     Start + Step*N = 0 (mod 2^BW)
9088   //
9089   // equivalent to:
9090   //
9091   //             Step*N = -Start (mod 2^BW)
9092   //
9093   // where BW is the common bit width of Start and Step.
9094 
9095   // Get the initial value for the loop.
9096   const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
9097   const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
9098 
9099   // For now we handle only constant steps.
9100   //
9101   // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
9102   // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
9103   // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
9104   // We have not yet seen any such cases.
9105   const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
9106   if (!StepC || StepC->getValue()->isZero())
9107     return getCouldNotCompute();
9108 
9109   // For positive steps (counting up until unsigned overflow):
9110   //   N = -Start/Step (as unsigned)
9111   // For negative steps (counting down to zero):
9112   //   N = Start/-Step
9113   // First compute the unsigned distance from zero in the direction of Step.
9114   bool CountDown = StepC->getAPInt().isNegative();
9115   const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
9116 
9117   // Handle unitary steps, which cannot wraparound.
9118   // 1*N = -Start; -1*N = Start (mod 2^BW), so:
9119   //   N = Distance (as unsigned)
9120   if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) {
9121     APInt MaxBECount = getUnsignedRangeMax(applyLoopGuards(Distance, L));
9122     APInt MaxBECountBase = getUnsignedRangeMax(Distance);
9123     if (MaxBECountBase.ult(MaxBECount))
9124       MaxBECount = MaxBECountBase;
9125 
9126     // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
9127     // we end up with a loop whose backedge-taken count is n - 1.  Detect this
9128     // case, and see if we can improve the bound.
9129     //
9130     // Explicitly handling this here is necessary because getUnsignedRange
9131     // isn't context-sensitive; it doesn't know that we only care about the
9132     // range inside the loop.
9133     const SCEV *Zero = getZero(Distance->getType());
9134     const SCEV *One = getOne(Distance->getType());
9135     const SCEV *DistancePlusOne = getAddExpr(Distance, One);
9136     if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
9137       // If Distance + 1 doesn't overflow, we can compute the maximum distance
9138       // as "unsigned_max(Distance + 1) - 1".
9139       ConstantRange CR = getUnsignedRange(DistancePlusOne);
9140       MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1);
9141     }
9142     return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates);
9143   }
9144 
9145   // If the condition controls loop exit (the loop exits only if the expression
9146   // is true) and the addition is no-wrap we can use unsigned divide to
9147   // compute the backedge count.  In this case, the step may not divide the
9148   // distance, but we don't care because if the condition is "missed" the loop
9149   // will have undefined behavior due to wrapping.
9150   if (ControlsExit && AddRec->hasNoSelfWrap() &&
9151       loopHasNoAbnormalExits(AddRec->getLoop())) {
9152     const SCEV *Exact =
9153         getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
9154     const SCEV *Max =
9155         Exact == getCouldNotCompute()
9156             ? Exact
9157             : getConstant(getUnsignedRangeMax(Exact));
9158     return ExitLimit(Exact, Max, false, Predicates);
9159   }
9160 
9161   // Solve the general equation.
9162   const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(),
9163                                                getNegativeSCEV(Start), *this);
9164   const SCEV *M = E == getCouldNotCompute()
9165                       ? E
9166                       : getConstant(getUnsignedRangeMax(E));
9167   return ExitLimit(E, M, false, Predicates);
9168 }
9169 
9170 ScalarEvolution::ExitLimit
9171 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
9172   // Loops that look like: while (X == 0) are very strange indeed.  We don't
9173   // handle them yet except for the trivial case.  This could be expanded in the
9174   // future as needed.
9175 
9176   // If the value is a constant, check to see if it is known to be non-zero
9177   // already.  If so, the backedge will execute zero times.
9178   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
9179     if (!C->getValue()->isZero())
9180       return getZero(C->getType());
9181     return getCouldNotCompute();  // Otherwise it will loop infinitely.
9182   }
9183 
9184   // We could implement others, but I really doubt anyone writes loops like
9185   // this, and if they did, they would already be constant folded.
9186   return getCouldNotCompute();
9187 }
9188 
9189 std::pair<const BasicBlock *, const BasicBlock *>
9190 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB)
9191     const {
9192   // If the block has a unique predecessor, then there is no path from the
9193   // predecessor to the block that does not go through the direct edge
9194   // from the predecessor to the block.
9195   if (const BasicBlock *Pred = BB->getSinglePredecessor())
9196     return {Pred, BB};
9197 
9198   // A loop's header is defined to be a block that dominates the loop.
9199   // If the header has a unique predecessor outside the loop, it must be
9200   // a block that has exactly one successor that can reach the loop.
9201   if (const Loop *L = LI.getLoopFor(BB))
9202     return {L->getLoopPredecessor(), L->getHeader()};
9203 
9204   return {nullptr, nullptr};
9205 }
9206 
9207 /// SCEV structural equivalence is usually sufficient for testing whether two
9208 /// expressions are equal, however for the purposes of looking for a condition
9209 /// guarding a loop, it can be useful to be a little more general, since a
9210 /// front-end may have replicated the controlling expression.
9211 static bool HasSameValue(const SCEV *A, const SCEV *B) {
9212   // Quick check to see if they are the same SCEV.
9213   if (A == B) return true;
9214 
9215   auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
9216     // Not all instructions that are "identical" compute the same value.  For
9217     // instance, two distinct alloca instructions allocating the same type are
9218     // identical and do not read memory; but compute distinct values.
9219     return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
9220   };
9221 
9222   // Otherwise, if they're both SCEVUnknown, it's possible that they hold
9223   // two different instructions with the same value. Check for this case.
9224   if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
9225     if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
9226       if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
9227         if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
9228           if (ComputesEqualValues(AI, BI))
9229             return true;
9230 
9231   // Otherwise assume they may have a different value.
9232   return false;
9233 }
9234 
9235 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
9236                                            const SCEV *&LHS, const SCEV *&RHS,
9237                                            unsigned Depth) {
9238   bool Changed = false;
9239   // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or
9240   // '0 != 0'.
9241   auto TrivialCase = [&](bool TriviallyTrue) {
9242     LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
9243     Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
9244     return true;
9245   };
9246   // If we hit the max recursion limit bail out.
9247   if (Depth >= 3)
9248     return false;
9249 
9250   // Canonicalize a constant to the right side.
9251   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
9252     // Check for both operands constant.
9253     if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
9254       if (ConstantExpr::getICmp(Pred,
9255                                 LHSC->getValue(),
9256                                 RHSC->getValue())->isNullValue())
9257         return TrivialCase(false);
9258       else
9259         return TrivialCase(true);
9260     }
9261     // Otherwise swap the operands to put the constant on the right.
9262     std::swap(LHS, RHS);
9263     Pred = ICmpInst::getSwappedPredicate(Pred);
9264     Changed = true;
9265   }
9266 
9267   // If we're comparing an addrec with a value which is loop-invariant in the
9268   // addrec's loop, put the addrec on the left. Also make a dominance check,
9269   // as both operands could be addrecs loop-invariant in each other's loop.
9270   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
9271     const Loop *L = AR->getLoop();
9272     if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
9273       std::swap(LHS, RHS);
9274       Pred = ICmpInst::getSwappedPredicate(Pred);
9275       Changed = true;
9276     }
9277   }
9278 
9279   // If there's a constant operand, canonicalize comparisons with boundary
9280   // cases, and canonicalize *-or-equal comparisons to regular comparisons.
9281   if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
9282     const APInt &RA = RC->getAPInt();
9283 
9284     bool SimplifiedByConstantRange = false;
9285 
9286     if (!ICmpInst::isEquality(Pred)) {
9287       ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA);
9288       if (ExactCR.isFullSet())
9289         return TrivialCase(true);
9290       else if (ExactCR.isEmptySet())
9291         return TrivialCase(false);
9292 
9293       APInt NewRHS;
9294       CmpInst::Predicate NewPred;
9295       if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
9296           ICmpInst::isEquality(NewPred)) {
9297         // We were able to convert an inequality to an equality.
9298         Pred = NewPred;
9299         RHS = getConstant(NewRHS);
9300         Changed = SimplifiedByConstantRange = true;
9301       }
9302     }
9303 
9304     if (!SimplifiedByConstantRange) {
9305       switch (Pred) {
9306       default:
9307         break;
9308       case ICmpInst::ICMP_EQ:
9309       case ICmpInst::ICMP_NE:
9310         // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
9311         if (!RA)
9312           if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
9313             if (const SCEVMulExpr *ME =
9314                     dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
9315               if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
9316                   ME->getOperand(0)->isAllOnesValue()) {
9317                 RHS = AE->getOperand(1);
9318                 LHS = ME->getOperand(1);
9319                 Changed = true;
9320               }
9321         break;
9322 
9323 
9324         // The "Should have been caught earlier!" messages refer to the fact
9325         // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
9326         // should have fired on the corresponding cases, and canonicalized the
9327         // check to trivial case.
9328 
9329       case ICmpInst::ICMP_UGE:
9330         assert(!RA.isMinValue() && "Should have been caught earlier!");
9331         Pred = ICmpInst::ICMP_UGT;
9332         RHS = getConstant(RA - 1);
9333         Changed = true;
9334         break;
9335       case ICmpInst::ICMP_ULE:
9336         assert(!RA.isMaxValue() && "Should have been caught earlier!");
9337         Pred = ICmpInst::ICMP_ULT;
9338         RHS = getConstant(RA + 1);
9339         Changed = true;
9340         break;
9341       case ICmpInst::ICMP_SGE:
9342         assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
9343         Pred = ICmpInst::ICMP_SGT;
9344         RHS = getConstant(RA - 1);
9345         Changed = true;
9346         break;
9347       case ICmpInst::ICMP_SLE:
9348         assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
9349         Pred = ICmpInst::ICMP_SLT;
9350         RHS = getConstant(RA + 1);
9351         Changed = true;
9352         break;
9353       }
9354     }
9355   }
9356 
9357   // Check for obvious equality.
9358   if (HasSameValue(LHS, RHS)) {
9359     if (ICmpInst::isTrueWhenEqual(Pred))
9360       return TrivialCase(true);
9361     if (ICmpInst::isFalseWhenEqual(Pred))
9362       return TrivialCase(false);
9363   }
9364 
9365   // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
9366   // adding or subtracting 1 from one of the operands.
9367   switch (Pred) {
9368   case ICmpInst::ICMP_SLE:
9369     if (!getSignedRangeMax(RHS).isMaxSignedValue()) {
9370       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
9371                        SCEV::FlagNSW);
9372       Pred = ICmpInst::ICMP_SLT;
9373       Changed = true;
9374     } else if (!getSignedRangeMin(LHS).isMinSignedValue()) {
9375       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
9376                        SCEV::FlagNSW);
9377       Pred = ICmpInst::ICMP_SLT;
9378       Changed = true;
9379     }
9380     break;
9381   case ICmpInst::ICMP_SGE:
9382     if (!getSignedRangeMin(RHS).isMinSignedValue()) {
9383       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
9384                        SCEV::FlagNSW);
9385       Pred = ICmpInst::ICMP_SGT;
9386       Changed = true;
9387     } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) {
9388       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
9389                        SCEV::FlagNSW);
9390       Pred = ICmpInst::ICMP_SGT;
9391       Changed = true;
9392     }
9393     break;
9394   case ICmpInst::ICMP_ULE:
9395     if (!getUnsignedRangeMax(RHS).isMaxValue()) {
9396       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
9397                        SCEV::FlagNUW);
9398       Pred = ICmpInst::ICMP_ULT;
9399       Changed = true;
9400     } else if (!getUnsignedRangeMin(LHS).isMinValue()) {
9401       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
9402       Pred = ICmpInst::ICMP_ULT;
9403       Changed = true;
9404     }
9405     break;
9406   case ICmpInst::ICMP_UGE:
9407     if (!getUnsignedRangeMin(RHS).isMinValue()) {
9408       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
9409       Pred = ICmpInst::ICMP_UGT;
9410       Changed = true;
9411     } else if (!getUnsignedRangeMax(LHS).isMaxValue()) {
9412       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
9413                        SCEV::FlagNUW);
9414       Pred = ICmpInst::ICMP_UGT;
9415       Changed = true;
9416     }
9417     break;
9418   default:
9419     break;
9420   }
9421 
9422   // TODO: More simplifications are possible here.
9423 
9424   // Recursively simplify until we either hit a recursion limit or nothing
9425   // changes.
9426   if (Changed)
9427     return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
9428 
9429   return Changed;
9430 }
9431 
9432 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
9433   return getSignedRangeMax(S).isNegative();
9434 }
9435 
9436 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
9437   return getSignedRangeMin(S).isStrictlyPositive();
9438 }
9439 
9440 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
9441   return !getSignedRangeMin(S).isNegative();
9442 }
9443 
9444 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
9445   return !getSignedRangeMax(S).isStrictlyPositive();
9446 }
9447 
9448 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
9449   return isKnownNegative(S) || isKnownPositive(S);
9450 }
9451 
9452 std::pair<const SCEV *, const SCEV *>
9453 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) {
9454   // Compute SCEV on entry of loop L.
9455   const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this);
9456   if (Start == getCouldNotCompute())
9457     return { Start, Start };
9458   // Compute post increment SCEV for loop L.
9459   const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this);
9460   assert(PostInc != getCouldNotCompute() && "Unexpected could not compute");
9461   return { Start, PostInc };
9462 }
9463 
9464 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred,
9465                                           const SCEV *LHS, const SCEV *RHS) {
9466   // First collect all loops.
9467   SmallPtrSet<const Loop *, 8> LoopsUsed;
9468   getUsedLoops(LHS, LoopsUsed);
9469   getUsedLoops(RHS, LoopsUsed);
9470 
9471   if (LoopsUsed.empty())
9472     return false;
9473 
9474   // Domination relationship must be a linear order on collected loops.
9475 #ifndef NDEBUG
9476   for (auto *L1 : LoopsUsed)
9477     for (auto *L2 : LoopsUsed)
9478       assert((DT.dominates(L1->getHeader(), L2->getHeader()) ||
9479               DT.dominates(L2->getHeader(), L1->getHeader())) &&
9480              "Domination relationship is not a linear order");
9481 #endif
9482 
9483   const Loop *MDL =
9484       *std::max_element(LoopsUsed.begin(), LoopsUsed.end(),
9485                         [&](const Loop *L1, const Loop *L2) {
9486          return DT.properlyDominates(L1->getHeader(), L2->getHeader());
9487        });
9488 
9489   // Get init and post increment value for LHS.
9490   auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS);
9491   // if LHS contains unknown non-invariant SCEV then bail out.
9492   if (SplitLHS.first == getCouldNotCompute())
9493     return false;
9494   assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC");
9495   // Get init and post increment value for RHS.
9496   auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS);
9497   // if RHS contains unknown non-invariant SCEV then bail out.
9498   if (SplitRHS.first == getCouldNotCompute())
9499     return false;
9500   assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC");
9501   // It is possible that init SCEV contains an invariant load but it does
9502   // not dominate MDL and is not available at MDL loop entry, so we should
9503   // check it here.
9504   if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) ||
9505       !isAvailableAtLoopEntry(SplitRHS.first, MDL))
9506     return false;
9507 
9508   // It seems backedge guard check is faster than entry one so in some cases
9509   // it can speed up whole estimation by short circuit
9510   return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second,
9511                                      SplitRHS.second) &&
9512          isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first);
9513 }
9514 
9515 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
9516                                        const SCEV *LHS, const SCEV *RHS) {
9517   // Canonicalize the inputs first.
9518   (void)SimplifyICmpOperands(Pred, LHS, RHS);
9519 
9520   if (isKnownViaInduction(Pred, LHS, RHS))
9521     return true;
9522 
9523   if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
9524     return true;
9525 
9526   // Otherwise see what can be done with some simple reasoning.
9527   return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS);
9528 }
9529 
9530 bool ScalarEvolution::isKnownPredicateAt(ICmpInst::Predicate Pred,
9531                                          const SCEV *LHS, const SCEV *RHS,
9532                                          const Instruction *Context) {
9533   // TODO: Analyze guards and assumes from Context's block.
9534   return isKnownPredicate(Pred, LHS, RHS) ||
9535          isBasicBlockEntryGuardedByCond(Context->getParent(), Pred, LHS, RHS);
9536 }
9537 
9538 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred,
9539                                               const SCEVAddRecExpr *LHS,
9540                                               const SCEV *RHS) {
9541   const Loop *L = LHS->getLoop();
9542   return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) &&
9543          isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS);
9544 }
9545 
9546 Optional<ScalarEvolution::MonotonicPredicateType>
9547 ScalarEvolution::getMonotonicPredicateType(const SCEVAddRecExpr *LHS,
9548                                            ICmpInst::Predicate Pred) {
9549   auto Result = getMonotonicPredicateTypeImpl(LHS, Pred);
9550 
9551 #ifndef NDEBUG
9552   // Verify an invariant: inverting the predicate should turn a monotonically
9553   // increasing change to a monotonically decreasing one, and vice versa.
9554   if (Result) {
9555     auto ResultSwapped =
9556         getMonotonicPredicateTypeImpl(LHS, ICmpInst::getSwappedPredicate(Pred));
9557 
9558     assert(ResultSwapped.hasValue() && "should be able to analyze both!");
9559     assert(ResultSwapped.getValue() != Result.getValue() &&
9560            "monotonicity should flip as we flip the predicate");
9561   }
9562 #endif
9563 
9564   return Result;
9565 }
9566 
9567 Optional<ScalarEvolution::MonotonicPredicateType>
9568 ScalarEvolution::getMonotonicPredicateTypeImpl(const SCEVAddRecExpr *LHS,
9569                                                ICmpInst::Predicate Pred) {
9570   // A zero step value for LHS means the induction variable is essentially a
9571   // loop invariant value. We don't really depend on the predicate actually
9572   // flipping from false to true (for increasing predicates, and the other way
9573   // around for decreasing predicates), all we care about is that *if* the
9574   // predicate changes then it only changes from false to true.
9575   //
9576   // A zero step value in itself is not very useful, but there may be places
9577   // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
9578   // as general as possible.
9579 
9580   // Only handle LE/LT/GE/GT predicates.
9581   if (!ICmpInst::isRelational(Pred))
9582     return None;
9583 
9584   bool IsGreater = ICmpInst::isGE(Pred) || ICmpInst::isGT(Pred);
9585   assert((IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) &&
9586          "Should be greater or less!");
9587 
9588   // Check that AR does not wrap.
9589   if (ICmpInst::isUnsigned(Pred)) {
9590     if (!LHS->hasNoUnsignedWrap())
9591       return None;
9592     return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
9593   } else {
9594     assert(ICmpInst::isSigned(Pred) &&
9595            "Relational predicate is either signed or unsigned!");
9596     if (!LHS->hasNoSignedWrap())
9597       return None;
9598 
9599     const SCEV *Step = LHS->getStepRecurrence(*this);
9600 
9601     if (isKnownNonNegative(Step))
9602       return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
9603 
9604     if (isKnownNonPositive(Step))
9605       return !IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
9606 
9607     return None;
9608   }
9609 }
9610 
9611 Optional<ScalarEvolution::LoopInvariantPredicate>
9612 ScalarEvolution::getLoopInvariantPredicate(ICmpInst::Predicate Pred,
9613                                            const SCEV *LHS, const SCEV *RHS,
9614                                            const Loop *L) {
9615 
9616   // If there is a loop-invariant, force it into the RHS, otherwise bail out.
9617   if (!isLoopInvariant(RHS, L)) {
9618     if (!isLoopInvariant(LHS, L))
9619       return None;
9620 
9621     std::swap(LHS, RHS);
9622     Pred = ICmpInst::getSwappedPredicate(Pred);
9623   }
9624 
9625   const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
9626   if (!ArLHS || ArLHS->getLoop() != L)
9627     return None;
9628 
9629   auto MonotonicType = getMonotonicPredicateType(ArLHS, Pred);
9630   if (!MonotonicType)
9631     return None;
9632   // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
9633   // true as the loop iterates, and the backedge is control dependent on
9634   // "ArLHS `Pred` RHS" == true then we can reason as follows:
9635   //
9636   //   * if the predicate was false in the first iteration then the predicate
9637   //     is never evaluated again, since the loop exits without taking the
9638   //     backedge.
9639   //   * if the predicate was true in the first iteration then it will
9640   //     continue to be true for all future iterations since it is
9641   //     monotonically increasing.
9642   //
9643   // For both the above possibilities, we can replace the loop varying
9644   // predicate with its value on the first iteration of the loop (which is
9645   // loop invariant).
9646   //
9647   // A similar reasoning applies for a monotonically decreasing predicate, by
9648   // replacing true with false and false with true in the above two bullets.
9649   bool Increasing = *MonotonicType == ScalarEvolution::MonotonicallyIncreasing;
9650   auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
9651 
9652   if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
9653     return None;
9654 
9655   return ScalarEvolution::LoopInvariantPredicate(Pred, ArLHS->getStart(), RHS);
9656 }
9657 
9658 Optional<ScalarEvolution::LoopInvariantPredicate>
9659 ScalarEvolution::getLoopInvariantExitCondDuringFirstIterations(
9660     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
9661     const Instruction *Context, const SCEV *MaxIter) {
9662   // Try to prove the following set of facts:
9663   // - The predicate is monotonic in the iteration space.
9664   // - If the check does not fail on the 1st iteration:
9665   //   - No overflow will happen during first MaxIter iterations;
9666   //   - It will not fail on the MaxIter'th iteration.
9667   // If the check does fail on the 1st iteration, we leave the loop and no
9668   // other checks matter.
9669 
9670   // If there is a loop-invariant, force it into the RHS, otherwise bail out.
9671   if (!isLoopInvariant(RHS, L)) {
9672     if (!isLoopInvariant(LHS, L))
9673       return None;
9674 
9675     std::swap(LHS, RHS);
9676     Pred = ICmpInst::getSwappedPredicate(Pred);
9677   }
9678 
9679   auto *AR = dyn_cast<SCEVAddRecExpr>(LHS);
9680   if (!AR || AR->getLoop() != L)
9681     return None;
9682 
9683   // The predicate must be relational (i.e. <, <=, >=, >).
9684   if (!ICmpInst::isRelational(Pred))
9685     return None;
9686 
9687   // TODO: Support steps other than +/- 1.
9688   const SCEV *Step = AR->getStepRecurrence(*this);
9689   auto *One = getOne(Step->getType());
9690   auto *MinusOne = getNegativeSCEV(One);
9691   if (Step != One && Step != MinusOne)
9692     return None;
9693 
9694   // Type mismatch here means that MaxIter is potentially larger than max
9695   // unsigned value in start type, which mean we cannot prove no wrap for the
9696   // indvar.
9697   if (AR->getType() != MaxIter->getType())
9698     return None;
9699 
9700   // Value of IV on suggested last iteration.
9701   const SCEV *Last = AR->evaluateAtIteration(MaxIter, *this);
9702   // Does it still meet the requirement?
9703   if (!isLoopBackedgeGuardedByCond(L, Pred, Last, RHS))
9704     return None;
9705   // Because step is +/- 1 and MaxIter has same type as Start (i.e. it does
9706   // not exceed max unsigned value of this type), this effectively proves
9707   // that there is no wrap during the iteration. To prove that there is no
9708   // signed/unsigned wrap, we need to check that
9709   // Start <= Last for step = 1 or Start >= Last for step = -1.
9710   ICmpInst::Predicate NoOverflowPred =
9711       CmpInst::isSigned(Pred) ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
9712   if (Step == MinusOne)
9713     NoOverflowPred = CmpInst::getSwappedPredicate(NoOverflowPred);
9714   const SCEV *Start = AR->getStart();
9715   if (!isKnownPredicateAt(NoOverflowPred, Start, Last, Context))
9716     return None;
9717 
9718   // Everything is fine.
9719   return ScalarEvolution::LoopInvariantPredicate(Pred, Start, RHS);
9720 }
9721 
9722 bool ScalarEvolution::isKnownPredicateViaConstantRanges(
9723     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
9724   if (HasSameValue(LHS, RHS))
9725     return ICmpInst::isTrueWhenEqual(Pred);
9726 
9727   // This code is split out from isKnownPredicate because it is called from
9728   // within isLoopEntryGuardedByCond.
9729 
9730   auto CheckRanges =
9731       [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) {
9732     return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS)
9733         .contains(RangeLHS);
9734   };
9735 
9736   // The check at the top of the function catches the case where the values are
9737   // known to be equal.
9738   if (Pred == CmpInst::ICMP_EQ)
9739     return false;
9740 
9741   if (Pred == CmpInst::ICMP_NE)
9742     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) ||
9743            CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) ||
9744            isKnownNonZero(getMinusSCEV(LHS, RHS));
9745 
9746   if (CmpInst::isSigned(Pred))
9747     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS));
9748 
9749   return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS));
9750 }
9751 
9752 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
9753                                                     const SCEV *LHS,
9754                                                     const SCEV *RHS) {
9755   // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer.
9756   // Return Y via OutY.
9757   auto MatchBinaryAddToConst =
9758       [this](const SCEV *Result, const SCEV *X, APInt &OutY,
9759              SCEV::NoWrapFlags ExpectedFlags) {
9760     const SCEV *NonConstOp, *ConstOp;
9761     SCEV::NoWrapFlags FlagsPresent;
9762 
9763     if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) ||
9764         !isa<SCEVConstant>(ConstOp) || NonConstOp != X)
9765       return false;
9766 
9767     OutY = cast<SCEVConstant>(ConstOp)->getAPInt();
9768     return (FlagsPresent & ExpectedFlags) == ExpectedFlags;
9769   };
9770 
9771   APInt C;
9772 
9773   switch (Pred) {
9774   default:
9775     break;
9776 
9777   case ICmpInst::ICMP_SGE:
9778     std::swap(LHS, RHS);
9779     LLVM_FALLTHROUGH;
9780   case ICmpInst::ICMP_SLE:
9781     // X s<= (X + C)<nsw> if C >= 0
9782     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative())
9783       return true;
9784 
9785     // (X + C)<nsw> s<= X if C <= 0
9786     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) &&
9787         !C.isStrictlyPositive())
9788       return true;
9789     break;
9790 
9791   case ICmpInst::ICMP_SGT:
9792     std::swap(LHS, RHS);
9793     LLVM_FALLTHROUGH;
9794   case ICmpInst::ICMP_SLT:
9795     // X s< (X + C)<nsw> if C > 0
9796     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) &&
9797         C.isStrictlyPositive())
9798       return true;
9799 
9800     // (X + C)<nsw> s< X if C < 0
9801     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative())
9802       return true;
9803     break;
9804 
9805   case ICmpInst::ICMP_UGE:
9806     std::swap(LHS, RHS);
9807     LLVM_FALLTHROUGH;
9808   case ICmpInst::ICMP_ULE:
9809     // X u<= (X + C)<nuw> for any C
9810     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNUW))
9811       return true;
9812     break;
9813 
9814   case ICmpInst::ICMP_UGT:
9815     std::swap(LHS, RHS);
9816     LLVM_FALLTHROUGH;
9817   case ICmpInst::ICMP_ULT:
9818     // X u< (X + C)<nuw> if C != 0
9819     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNUW) && !C.isNullValue())
9820       return true;
9821     break;
9822   }
9823 
9824   return false;
9825 }
9826 
9827 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
9828                                                    const SCEV *LHS,
9829                                                    const SCEV *RHS) {
9830   if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
9831     return false;
9832 
9833   // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
9834   // the stack can result in exponential time complexity.
9835   SaveAndRestore<bool> Restore(ProvingSplitPredicate, true);
9836 
9837   // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
9838   //
9839   // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
9840   // isKnownPredicate.  isKnownPredicate is more powerful, but also more
9841   // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
9842   // interesting cases seen in practice.  We can consider "upgrading" L >= 0 to
9843   // use isKnownPredicate later if needed.
9844   return isKnownNonNegative(RHS) &&
9845          isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
9846          isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
9847 }
9848 
9849 bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB,
9850                                         ICmpInst::Predicate Pred,
9851                                         const SCEV *LHS, const SCEV *RHS) {
9852   // No need to even try if we know the module has no guards.
9853   if (!HasGuards)
9854     return false;
9855 
9856   return any_of(*BB, [&](const Instruction &I) {
9857     using namespace llvm::PatternMatch;
9858 
9859     Value *Condition;
9860     return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
9861                          m_Value(Condition))) &&
9862            isImpliedCond(Pred, LHS, RHS, Condition, false);
9863   });
9864 }
9865 
9866 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
9867 /// protected by a conditional between LHS and RHS.  This is used to
9868 /// to eliminate casts.
9869 bool
9870 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
9871                                              ICmpInst::Predicate Pred,
9872                                              const SCEV *LHS, const SCEV *RHS) {
9873   // Interpret a null as meaning no loop, where there is obviously no guard
9874   // (interprocedural conditions notwithstanding).
9875   if (!L) return true;
9876 
9877   if (VerifyIR)
9878     assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) &&
9879            "This cannot be done on broken IR!");
9880 
9881 
9882   if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
9883     return true;
9884 
9885   BasicBlock *Latch = L->getLoopLatch();
9886   if (!Latch)
9887     return false;
9888 
9889   BranchInst *LoopContinuePredicate =
9890     dyn_cast<BranchInst>(Latch->getTerminator());
9891   if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
9892       isImpliedCond(Pred, LHS, RHS,
9893                     LoopContinuePredicate->getCondition(),
9894                     LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
9895     return true;
9896 
9897   // We don't want more than one activation of the following loops on the stack
9898   // -- that can lead to O(n!) time complexity.
9899   if (WalkingBEDominatingConds)
9900     return false;
9901 
9902   SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true);
9903 
9904   // See if we can exploit a trip count to prove the predicate.
9905   const auto &BETakenInfo = getBackedgeTakenInfo(L);
9906   const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
9907   if (LatchBECount != getCouldNotCompute()) {
9908     // We know that Latch branches back to the loop header exactly
9909     // LatchBECount times.  This means the backdege condition at Latch is
9910     // equivalent to  "{0,+,1} u< LatchBECount".
9911     Type *Ty = LatchBECount->getType();
9912     auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
9913     const SCEV *LoopCounter =
9914       getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
9915     if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
9916                       LatchBECount))
9917       return true;
9918   }
9919 
9920   // Check conditions due to any @llvm.assume intrinsics.
9921   for (auto &AssumeVH : AC.assumptions()) {
9922     if (!AssumeVH)
9923       continue;
9924     auto *CI = cast<CallInst>(AssumeVH);
9925     if (!DT.dominates(CI, Latch->getTerminator()))
9926       continue;
9927 
9928     if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
9929       return true;
9930   }
9931 
9932   // If the loop is not reachable from the entry block, we risk running into an
9933   // infinite loop as we walk up into the dom tree.  These loops do not matter
9934   // anyway, so we just return a conservative answer when we see them.
9935   if (!DT.isReachableFromEntry(L->getHeader()))
9936     return false;
9937 
9938   if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
9939     return true;
9940 
9941   for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
9942        DTN != HeaderDTN; DTN = DTN->getIDom()) {
9943     assert(DTN && "should reach the loop header before reaching the root!");
9944 
9945     BasicBlock *BB = DTN->getBlock();
9946     if (isImpliedViaGuard(BB, Pred, LHS, RHS))
9947       return true;
9948 
9949     BasicBlock *PBB = BB->getSinglePredecessor();
9950     if (!PBB)
9951       continue;
9952 
9953     BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
9954     if (!ContinuePredicate || !ContinuePredicate->isConditional())
9955       continue;
9956 
9957     Value *Condition = ContinuePredicate->getCondition();
9958 
9959     // If we have an edge `E` within the loop body that dominates the only
9960     // latch, the condition guarding `E` also guards the backedge.  This
9961     // reasoning works only for loops with a single latch.
9962 
9963     BasicBlockEdge DominatingEdge(PBB, BB);
9964     if (DominatingEdge.isSingleEdge()) {
9965       // We're constructively (and conservatively) enumerating edges within the
9966       // loop body that dominate the latch.  The dominator tree better agree
9967       // with us on this:
9968       assert(DT.dominates(DominatingEdge, Latch) && "should be!");
9969 
9970       if (isImpliedCond(Pred, LHS, RHS, Condition,
9971                         BB != ContinuePredicate->getSuccessor(0)))
9972         return true;
9973     }
9974   }
9975 
9976   return false;
9977 }
9978 
9979 bool ScalarEvolution::isBasicBlockEntryGuardedByCond(const BasicBlock *BB,
9980                                                      ICmpInst::Predicate Pred,
9981                                                      const SCEV *LHS,
9982                                                      const SCEV *RHS) {
9983   if (VerifyIR)
9984     assert(!verifyFunction(*BB->getParent(), &dbgs()) &&
9985            "This cannot be done on broken IR!");
9986 
9987   if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
9988     return true;
9989 
9990   // If we cannot prove strict comparison (e.g. a > b), maybe we can prove
9991   // the facts (a >= b && a != b) separately. A typical situation is when the
9992   // non-strict comparison is known from ranges and non-equality is known from
9993   // dominating predicates. If we are proving strict comparison, we always try
9994   // to prove non-equality and non-strict comparison separately.
9995   auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred);
9996   const bool ProvingStrictComparison = (Pred != NonStrictPredicate);
9997   bool ProvedNonStrictComparison = false;
9998   bool ProvedNonEquality = false;
9999 
10000   if (ProvingStrictComparison) {
10001     ProvedNonStrictComparison =
10002         isKnownViaNonRecursiveReasoning(NonStrictPredicate, LHS, RHS);
10003     ProvedNonEquality =
10004         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, LHS, RHS);
10005     if (ProvedNonStrictComparison && ProvedNonEquality)
10006       return true;
10007   }
10008 
10009   // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard.
10010   auto ProveViaGuard = [&](const BasicBlock *Block) {
10011     if (isImpliedViaGuard(Block, Pred, LHS, RHS))
10012       return true;
10013     if (ProvingStrictComparison) {
10014       if (!ProvedNonStrictComparison)
10015         ProvedNonStrictComparison =
10016             isImpliedViaGuard(Block, NonStrictPredicate, LHS, RHS);
10017       if (!ProvedNonEquality)
10018         ProvedNonEquality =
10019             isImpliedViaGuard(Block, ICmpInst::ICMP_NE, LHS, RHS);
10020       if (ProvedNonStrictComparison && ProvedNonEquality)
10021         return true;
10022     }
10023     return false;
10024   };
10025 
10026   // Try to prove (Pred, LHS, RHS) using isImpliedCond.
10027   auto ProveViaCond = [&](const Value *Condition, bool Inverse) {
10028     const Instruction *Context = &BB->front();
10029     if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse, Context))
10030       return true;
10031     if (ProvingStrictComparison) {
10032       if (!ProvedNonStrictComparison)
10033         ProvedNonStrictComparison = isImpliedCond(NonStrictPredicate, LHS, RHS,
10034                                                   Condition, Inverse, Context);
10035       if (!ProvedNonEquality)
10036         ProvedNonEquality = isImpliedCond(ICmpInst::ICMP_NE, LHS, RHS,
10037                                           Condition, Inverse, Context);
10038       if (ProvedNonStrictComparison && ProvedNonEquality)
10039         return true;
10040     }
10041     return false;
10042   };
10043 
10044   // Starting at the block's predecessor, climb up the predecessor chain, as long
10045   // as there are predecessors that can be found that have unique successors
10046   // leading to the original block.
10047   const Loop *ContainingLoop = LI.getLoopFor(BB);
10048   const BasicBlock *PredBB;
10049   if (ContainingLoop && ContainingLoop->getHeader() == BB)
10050     PredBB = ContainingLoop->getLoopPredecessor();
10051   else
10052     PredBB = BB->getSinglePredecessor();
10053   for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB);
10054        Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
10055     if (ProveViaGuard(Pair.first))
10056       return true;
10057 
10058     const BranchInst *LoopEntryPredicate =
10059         dyn_cast<BranchInst>(Pair.first->getTerminator());
10060     if (!LoopEntryPredicate ||
10061         LoopEntryPredicate->isUnconditional())
10062       continue;
10063 
10064     if (ProveViaCond(LoopEntryPredicate->getCondition(),
10065                      LoopEntryPredicate->getSuccessor(0) != Pair.second))
10066       return true;
10067   }
10068 
10069   // Check conditions due to any @llvm.assume intrinsics.
10070   for (auto &AssumeVH : AC.assumptions()) {
10071     if (!AssumeVH)
10072       continue;
10073     auto *CI = cast<CallInst>(AssumeVH);
10074     if (!DT.dominates(CI, BB))
10075       continue;
10076 
10077     if (ProveViaCond(CI->getArgOperand(0), false))
10078       return true;
10079   }
10080 
10081   return false;
10082 }
10083 
10084 bool ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
10085                                                ICmpInst::Predicate Pred,
10086                                                const SCEV *LHS,
10087                                                const SCEV *RHS) {
10088   // Interpret a null as meaning no loop, where there is obviously no guard
10089   // (interprocedural conditions notwithstanding).
10090   if (!L)
10091     return false;
10092 
10093   // Both LHS and RHS must be available at loop entry.
10094   assert(isAvailableAtLoopEntry(LHS, L) &&
10095          "LHS is not available at Loop Entry");
10096   assert(isAvailableAtLoopEntry(RHS, L) &&
10097          "RHS is not available at Loop Entry");
10098   return isBasicBlockEntryGuardedByCond(L->getHeader(), Pred, LHS, RHS);
10099 }
10100 
10101 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
10102                                     const SCEV *RHS,
10103                                     const Value *FoundCondValue, bool Inverse,
10104                                     const Instruction *Context) {
10105   if (!PendingLoopPredicates.insert(FoundCondValue).second)
10106     return false;
10107 
10108   auto ClearOnExit =
10109       make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
10110 
10111   // Recursively handle And and Or conditions.
10112   if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
10113     if (BO->getOpcode() == Instruction::And) {
10114       if (!Inverse)
10115         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse,
10116                              Context) ||
10117                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse,
10118                              Context);
10119     } else if (BO->getOpcode() == Instruction::Or) {
10120       if (Inverse)
10121         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse,
10122                              Context) ||
10123                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse,
10124                              Context);
10125     }
10126   }
10127 
10128   const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
10129   if (!ICI) return false;
10130 
10131   // Now that we found a conditional branch that dominates the loop or controls
10132   // the loop latch. Check to see if it is the comparison we are looking for.
10133   ICmpInst::Predicate FoundPred;
10134   if (Inverse)
10135     FoundPred = ICI->getInversePredicate();
10136   else
10137     FoundPred = ICI->getPredicate();
10138 
10139   const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
10140   const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
10141 
10142   return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, Context);
10143 }
10144 
10145 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
10146                                     const SCEV *RHS,
10147                                     ICmpInst::Predicate FoundPred,
10148                                     const SCEV *FoundLHS, const SCEV *FoundRHS,
10149                                     const Instruction *Context) {
10150   // Balance the types.
10151   if (getTypeSizeInBits(LHS->getType()) <
10152       getTypeSizeInBits(FoundLHS->getType())) {
10153     // For unsigned and equality predicates, try to prove that both found
10154     // operands fit into narrow unsigned range. If so, try to prove facts in
10155     // narrow types.
10156     if (!CmpInst::isSigned(FoundPred)) {
10157       auto *NarrowType = LHS->getType();
10158       auto *WideType = FoundLHS->getType();
10159       auto BitWidth = getTypeSizeInBits(NarrowType);
10160       const SCEV *MaxValue = getZeroExtendExpr(
10161           getConstant(APInt::getMaxValue(BitWidth)), WideType);
10162       if (isKnownPredicate(ICmpInst::ICMP_ULE, FoundLHS, MaxValue) &&
10163           isKnownPredicate(ICmpInst::ICMP_ULE, FoundRHS, MaxValue)) {
10164         const SCEV *TruncFoundLHS = getTruncateExpr(FoundLHS, NarrowType);
10165         const SCEV *TruncFoundRHS = getTruncateExpr(FoundRHS, NarrowType);
10166         if (isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, TruncFoundLHS,
10167                                        TruncFoundRHS, Context))
10168           return true;
10169       }
10170     }
10171 
10172     if (CmpInst::isSigned(Pred)) {
10173       LHS = getSignExtendExpr(LHS, FoundLHS->getType());
10174       RHS = getSignExtendExpr(RHS, FoundLHS->getType());
10175     } else {
10176       LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
10177       RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
10178     }
10179   } else if (getTypeSizeInBits(LHS->getType()) >
10180       getTypeSizeInBits(FoundLHS->getType())) {
10181     if (CmpInst::isSigned(FoundPred)) {
10182       FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
10183       FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
10184     } else {
10185       FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
10186       FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
10187     }
10188   }
10189   return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS,
10190                                     FoundRHS, Context);
10191 }
10192 
10193 bool ScalarEvolution::isImpliedCondBalancedTypes(
10194     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
10195     ICmpInst::Predicate FoundPred, const SCEV *FoundLHS, const SCEV *FoundRHS,
10196     const Instruction *Context) {
10197   assert(getTypeSizeInBits(LHS->getType()) ==
10198              getTypeSizeInBits(FoundLHS->getType()) &&
10199          "Types should be balanced!");
10200   // Canonicalize the query to match the way instcombine will have
10201   // canonicalized the comparison.
10202   if (SimplifyICmpOperands(Pred, LHS, RHS))
10203     if (LHS == RHS)
10204       return CmpInst::isTrueWhenEqual(Pred);
10205   if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
10206     if (FoundLHS == FoundRHS)
10207       return CmpInst::isFalseWhenEqual(FoundPred);
10208 
10209   // Check to see if we can make the LHS or RHS match.
10210   if (LHS == FoundRHS || RHS == FoundLHS) {
10211     if (isa<SCEVConstant>(RHS)) {
10212       std::swap(FoundLHS, FoundRHS);
10213       FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
10214     } else {
10215       std::swap(LHS, RHS);
10216       Pred = ICmpInst::getSwappedPredicate(Pred);
10217     }
10218   }
10219 
10220   // Check whether the found predicate is the same as the desired predicate.
10221   if (FoundPred == Pred)
10222     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context);
10223 
10224   // Check whether swapping the found predicate makes it the same as the
10225   // desired predicate.
10226   if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
10227     if (isa<SCEVConstant>(RHS))
10228       return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS, Context);
10229     else
10230       return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred), RHS,
10231                                    LHS, FoundLHS, FoundRHS, Context);
10232   }
10233 
10234   // Unsigned comparison is the same as signed comparison when both the operands
10235   // are non-negative.
10236   if (CmpInst::isUnsigned(FoundPred) &&
10237       CmpInst::getSignedPredicate(FoundPred) == Pred &&
10238       isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS))
10239     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context);
10240 
10241   // Check if we can make progress by sharpening ranges.
10242   if (FoundPred == ICmpInst::ICMP_NE &&
10243       (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
10244 
10245     const SCEVConstant *C = nullptr;
10246     const SCEV *V = nullptr;
10247 
10248     if (isa<SCEVConstant>(FoundLHS)) {
10249       C = cast<SCEVConstant>(FoundLHS);
10250       V = FoundRHS;
10251     } else {
10252       C = cast<SCEVConstant>(FoundRHS);
10253       V = FoundLHS;
10254     }
10255 
10256     // The guarding predicate tells us that C != V. If the known range
10257     // of V is [C, t), we can sharpen the range to [C + 1, t).  The
10258     // range we consider has to correspond to same signedness as the
10259     // predicate we're interested in folding.
10260 
10261     APInt Min = ICmpInst::isSigned(Pred) ?
10262         getSignedRangeMin(V) : getUnsignedRangeMin(V);
10263 
10264     if (Min == C->getAPInt()) {
10265       // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
10266       // This is true even if (Min + 1) wraps around -- in case of
10267       // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
10268 
10269       APInt SharperMin = Min + 1;
10270 
10271       switch (Pred) {
10272         case ICmpInst::ICMP_SGE:
10273         case ICmpInst::ICMP_UGE:
10274           // We know V `Pred` SharperMin.  If this implies LHS `Pred`
10275           // RHS, we're done.
10276           if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(SharperMin),
10277                                     Context))
10278             return true;
10279           LLVM_FALLTHROUGH;
10280 
10281         case ICmpInst::ICMP_SGT:
10282         case ICmpInst::ICMP_UGT:
10283           // We know from the range information that (V `Pred` Min ||
10284           // V == Min).  We know from the guarding condition that !(V
10285           // == Min).  This gives us
10286           //
10287           //       V `Pred` Min || V == Min && !(V == Min)
10288           //   =>  V `Pred` Min
10289           //
10290           // If V `Pred` Min implies LHS `Pred` RHS, we're done.
10291 
10292           if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min),
10293                                     Context))
10294             return true;
10295           break;
10296 
10297         // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively.
10298         case ICmpInst::ICMP_SLE:
10299         case ICmpInst::ICMP_ULE:
10300           if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS,
10301                                     LHS, V, getConstant(SharperMin), Context))
10302             return true;
10303           LLVM_FALLTHROUGH;
10304 
10305         case ICmpInst::ICMP_SLT:
10306         case ICmpInst::ICMP_ULT:
10307           if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS,
10308                                     LHS, V, getConstant(Min), Context))
10309             return true;
10310           break;
10311 
10312         default:
10313           // No change
10314           break;
10315       }
10316     }
10317   }
10318 
10319   // Check whether the actual condition is beyond sufficient.
10320   if (FoundPred == ICmpInst::ICMP_EQ)
10321     if (ICmpInst::isTrueWhenEqual(Pred))
10322       if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context))
10323         return true;
10324   if (Pred == ICmpInst::ICMP_NE)
10325     if (!ICmpInst::isTrueWhenEqual(FoundPred))
10326       if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS,
10327                                 Context))
10328         return true;
10329 
10330   // Otherwise assume the worst.
10331   return false;
10332 }
10333 
10334 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
10335                                      const SCEV *&L, const SCEV *&R,
10336                                      SCEV::NoWrapFlags &Flags) {
10337   const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
10338   if (!AE || AE->getNumOperands() != 2)
10339     return false;
10340 
10341   L = AE->getOperand(0);
10342   R = AE->getOperand(1);
10343   Flags = AE->getNoWrapFlags();
10344   return true;
10345 }
10346 
10347 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More,
10348                                                            const SCEV *Less) {
10349   // We avoid subtracting expressions here because this function is usually
10350   // fairly deep in the call stack (i.e. is called many times).
10351 
10352   // X - X = 0.
10353   if (More == Less)
10354     return APInt(getTypeSizeInBits(More->getType()), 0);
10355 
10356   if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
10357     const auto *LAR = cast<SCEVAddRecExpr>(Less);
10358     const auto *MAR = cast<SCEVAddRecExpr>(More);
10359 
10360     if (LAR->getLoop() != MAR->getLoop())
10361       return None;
10362 
10363     // We look at affine expressions only; not for correctness but to keep
10364     // getStepRecurrence cheap.
10365     if (!LAR->isAffine() || !MAR->isAffine())
10366       return None;
10367 
10368     if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
10369       return None;
10370 
10371     Less = LAR->getStart();
10372     More = MAR->getStart();
10373 
10374     // fall through
10375   }
10376 
10377   if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
10378     const auto &M = cast<SCEVConstant>(More)->getAPInt();
10379     const auto &L = cast<SCEVConstant>(Less)->getAPInt();
10380     return M - L;
10381   }
10382 
10383   SCEV::NoWrapFlags Flags;
10384   const SCEV *LLess = nullptr, *RLess = nullptr;
10385   const SCEV *LMore = nullptr, *RMore = nullptr;
10386   const SCEVConstant *C1 = nullptr, *C2 = nullptr;
10387   // Compare (X + C1) vs X.
10388   if (splitBinaryAdd(Less, LLess, RLess, Flags))
10389     if ((C1 = dyn_cast<SCEVConstant>(LLess)))
10390       if (RLess == More)
10391         return -(C1->getAPInt());
10392 
10393   // Compare X vs (X + C2).
10394   if (splitBinaryAdd(More, LMore, RMore, Flags))
10395     if ((C2 = dyn_cast<SCEVConstant>(LMore)))
10396       if (RMore == Less)
10397         return C2->getAPInt();
10398 
10399   // Compare (X + C1) vs (X + C2).
10400   if (C1 && C2 && RLess == RMore)
10401     return C2->getAPInt() - C1->getAPInt();
10402 
10403   return None;
10404 }
10405 
10406 bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart(
10407     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
10408     const SCEV *FoundLHS, const SCEV *FoundRHS, const Instruction *Context) {
10409   // Try to recognize the following pattern:
10410   //
10411   //   FoundRHS = ...
10412   // ...
10413   // loop:
10414   //   FoundLHS = {Start,+,W}
10415   // context_bb: // Basic block from the same loop
10416   //   known(Pred, FoundLHS, FoundRHS)
10417   //
10418   // If some predicate is known in the context of a loop, it is also known on
10419   // each iteration of this loop, including the first iteration. Therefore, in
10420   // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to
10421   // prove the original pred using this fact.
10422   if (!Context)
10423     return false;
10424   const BasicBlock *ContextBB = Context->getParent();
10425   // Make sure AR varies in the context block.
10426   if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) {
10427     const Loop *L = AR->getLoop();
10428     // Make sure that context belongs to the loop and executes on 1st iteration
10429     // (if it ever executes at all).
10430     if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch()))
10431       return false;
10432     if (!isAvailableAtLoopEntry(FoundRHS, AR->getLoop()))
10433       return false;
10434     return isImpliedCondOperands(Pred, LHS, RHS, AR->getStart(), FoundRHS);
10435   }
10436 
10437   if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) {
10438     const Loop *L = AR->getLoop();
10439     // Make sure that context belongs to the loop and executes on 1st iteration
10440     // (if it ever executes at all).
10441     if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch()))
10442       return false;
10443     if (!isAvailableAtLoopEntry(FoundLHS, AR->getLoop()))
10444       return false;
10445     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->getStart());
10446   }
10447 
10448   return false;
10449 }
10450 
10451 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
10452     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
10453     const SCEV *FoundLHS, const SCEV *FoundRHS) {
10454   if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
10455     return false;
10456 
10457   const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
10458   if (!AddRecLHS)
10459     return false;
10460 
10461   const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
10462   if (!AddRecFoundLHS)
10463     return false;
10464 
10465   // We'd like to let SCEV reason about control dependencies, so we constrain
10466   // both the inequalities to be about add recurrences on the same loop.  This
10467   // way we can use isLoopEntryGuardedByCond later.
10468 
10469   const Loop *L = AddRecFoundLHS->getLoop();
10470   if (L != AddRecLHS->getLoop())
10471     return false;
10472 
10473   //  FoundLHS u< FoundRHS u< -C =>  (FoundLHS + C) u< (FoundRHS + C) ... (1)
10474   //
10475   //  FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
10476   //                                                                  ... (2)
10477   //
10478   // Informal proof for (2), assuming (1) [*]:
10479   //
10480   // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
10481   //
10482   // Then
10483   //
10484   //       FoundLHS s< FoundRHS s< INT_MIN - C
10485   // <=>  (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C   [ using (3) ]
10486   // <=>  (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
10487   // <=>  (FoundLHS + INT_MIN + C + INT_MIN) s<
10488   //                        (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
10489   // <=>  FoundLHS + C s< FoundRHS + C
10490   //
10491   // [*]: (1) can be proved by ruling out overflow.
10492   //
10493   // [**]: This can be proved by analyzing all the four possibilities:
10494   //    (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
10495   //    (A s>= 0, B s>= 0).
10496   //
10497   // Note:
10498   // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
10499   // will not sign underflow.  For instance, say FoundLHS = (i8 -128), FoundRHS
10500   // = (i8 -127) and C = (i8 -100).  Then INT_MIN - C = (i8 -28), and FoundRHS
10501   // s< (INT_MIN - C).  Lack of sign overflow / underflow in "FoundRHS + C" is
10502   // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
10503   // C)".
10504 
10505   Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
10506   Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
10507   if (!LDiff || !RDiff || *LDiff != *RDiff)
10508     return false;
10509 
10510   if (LDiff->isMinValue())
10511     return true;
10512 
10513   APInt FoundRHSLimit;
10514 
10515   if (Pred == CmpInst::ICMP_ULT) {
10516     FoundRHSLimit = -(*RDiff);
10517   } else {
10518     assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
10519     FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
10520   }
10521 
10522   // Try to prove (1) or (2), as needed.
10523   return isAvailableAtLoopEntry(FoundRHS, L) &&
10524          isLoopEntryGuardedByCond(L, Pred, FoundRHS,
10525                                   getConstant(FoundRHSLimit));
10526 }
10527 
10528 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred,
10529                                         const SCEV *LHS, const SCEV *RHS,
10530                                         const SCEV *FoundLHS,
10531                                         const SCEV *FoundRHS, unsigned Depth) {
10532   const PHINode *LPhi = nullptr, *RPhi = nullptr;
10533 
10534   auto ClearOnExit = make_scope_exit([&]() {
10535     if (LPhi) {
10536       bool Erased = PendingMerges.erase(LPhi);
10537       assert(Erased && "Failed to erase LPhi!");
10538       (void)Erased;
10539     }
10540     if (RPhi) {
10541       bool Erased = PendingMerges.erase(RPhi);
10542       assert(Erased && "Failed to erase RPhi!");
10543       (void)Erased;
10544     }
10545   });
10546 
10547   // Find respective Phis and check that they are not being pending.
10548   if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS))
10549     if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) {
10550       if (!PendingMerges.insert(Phi).second)
10551         return false;
10552       LPhi = Phi;
10553     }
10554   if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS))
10555     if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) {
10556       // If we detect a loop of Phi nodes being processed by this method, for
10557       // example:
10558       //
10559       //   %a = phi i32 [ %some1, %preheader ], [ %b, %latch ]
10560       //   %b = phi i32 [ %some2, %preheader ], [ %a, %latch ]
10561       //
10562       // we don't want to deal with a case that complex, so return conservative
10563       // answer false.
10564       if (!PendingMerges.insert(Phi).second)
10565         return false;
10566       RPhi = Phi;
10567     }
10568 
10569   // If none of LHS, RHS is a Phi, nothing to do here.
10570   if (!LPhi && !RPhi)
10571     return false;
10572 
10573   // If there is a SCEVUnknown Phi we are interested in, make it left.
10574   if (!LPhi) {
10575     std::swap(LHS, RHS);
10576     std::swap(FoundLHS, FoundRHS);
10577     std::swap(LPhi, RPhi);
10578     Pred = ICmpInst::getSwappedPredicate(Pred);
10579   }
10580 
10581   assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!");
10582   const BasicBlock *LBB = LPhi->getParent();
10583   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
10584 
10585   auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) {
10586     return isKnownViaNonRecursiveReasoning(Pred, S1, S2) ||
10587            isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) ||
10588            isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth);
10589   };
10590 
10591   if (RPhi && RPhi->getParent() == LBB) {
10592     // Case one: RHS is also a SCEVUnknown Phi from the same basic block.
10593     // If we compare two Phis from the same block, and for each entry block
10594     // the predicate is true for incoming values from this block, then the
10595     // predicate is also true for the Phis.
10596     for (const BasicBlock *IncBB : predecessors(LBB)) {
10597       const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
10598       const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB));
10599       if (!ProvedEasily(L, R))
10600         return false;
10601     }
10602   } else if (RAR && RAR->getLoop()->getHeader() == LBB) {
10603     // Case two: RHS is also a Phi from the same basic block, and it is an
10604     // AddRec. It means that there is a loop which has both AddRec and Unknown
10605     // PHIs, for it we can compare incoming values of AddRec from above the loop
10606     // and latch with their respective incoming values of LPhi.
10607     // TODO: Generalize to handle loops with many inputs in a header.
10608     if (LPhi->getNumIncomingValues() != 2) return false;
10609 
10610     auto *RLoop = RAR->getLoop();
10611     auto *Predecessor = RLoop->getLoopPredecessor();
10612     assert(Predecessor && "Loop with AddRec with no predecessor?");
10613     const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor));
10614     if (!ProvedEasily(L1, RAR->getStart()))
10615       return false;
10616     auto *Latch = RLoop->getLoopLatch();
10617     assert(Latch && "Loop with AddRec with no latch?");
10618     const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch));
10619     if (!ProvedEasily(L2, RAR->getPostIncExpr(*this)))
10620       return false;
10621   } else {
10622     // In all other cases go over inputs of LHS and compare each of them to RHS,
10623     // the predicate is true for (LHS, RHS) if it is true for all such pairs.
10624     // At this point RHS is either a non-Phi, or it is a Phi from some block
10625     // different from LBB.
10626     for (const BasicBlock *IncBB : predecessors(LBB)) {
10627       // Check that RHS is available in this block.
10628       if (!dominates(RHS, IncBB))
10629         return false;
10630       const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
10631       if (!ProvedEasily(L, RHS))
10632         return false;
10633     }
10634   }
10635   return true;
10636 }
10637 
10638 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
10639                                             const SCEV *LHS, const SCEV *RHS,
10640                                             const SCEV *FoundLHS,
10641                                             const SCEV *FoundRHS,
10642                                             const Instruction *Context) {
10643   if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
10644     return true;
10645 
10646   if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
10647     return true;
10648 
10649   if (isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS,
10650                                           Context))
10651     return true;
10652 
10653   return isImpliedCondOperandsHelper(Pred, LHS, RHS,
10654                                      FoundLHS, FoundRHS) ||
10655          // ~x < ~y --> x > y
10656          isImpliedCondOperandsHelper(Pred, LHS, RHS,
10657                                      getNotSCEV(FoundRHS),
10658                                      getNotSCEV(FoundLHS));
10659 }
10660 
10661 /// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values?
10662 template <typename MinMaxExprType>
10663 static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr,
10664                                  const SCEV *Candidate) {
10665   const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr);
10666   if (!MinMaxExpr)
10667     return false;
10668 
10669   return is_contained(MinMaxExpr->operands(), Candidate);
10670 }
10671 
10672 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
10673                                            ICmpInst::Predicate Pred,
10674                                            const SCEV *LHS, const SCEV *RHS) {
10675   // If both sides are affine addrecs for the same loop, with equal
10676   // steps, and we know the recurrences don't wrap, then we only
10677   // need to check the predicate on the starting values.
10678 
10679   if (!ICmpInst::isRelational(Pred))
10680     return false;
10681 
10682   const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
10683   if (!LAR)
10684     return false;
10685   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
10686   if (!RAR)
10687     return false;
10688   if (LAR->getLoop() != RAR->getLoop())
10689     return false;
10690   if (!LAR->isAffine() || !RAR->isAffine())
10691     return false;
10692 
10693   if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
10694     return false;
10695 
10696   SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
10697                          SCEV::FlagNSW : SCEV::FlagNUW;
10698   if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
10699     return false;
10700 
10701   return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
10702 }
10703 
10704 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
10705 /// expression?
10706 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
10707                                         ICmpInst::Predicate Pred,
10708                                         const SCEV *LHS, const SCEV *RHS) {
10709   switch (Pred) {
10710   default:
10711     return false;
10712 
10713   case ICmpInst::ICMP_SGE:
10714     std::swap(LHS, RHS);
10715     LLVM_FALLTHROUGH;
10716   case ICmpInst::ICMP_SLE:
10717     return
10718         // min(A, ...) <= A
10719         IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) ||
10720         // A <= max(A, ...)
10721         IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
10722 
10723   case ICmpInst::ICMP_UGE:
10724     std::swap(LHS, RHS);
10725     LLVM_FALLTHROUGH;
10726   case ICmpInst::ICMP_ULE:
10727     return
10728         // min(A, ...) <= A
10729         IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) ||
10730         // A <= max(A, ...)
10731         IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
10732   }
10733 
10734   llvm_unreachable("covered switch fell through?!");
10735 }
10736 
10737 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred,
10738                                              const SCEV *LHS, const SCEV *RHS,
10739                                              const SCEV *FoundLHS,
10740                                              const SCEV *FoundRHS,
10741                                              unsigned Depth) {
10742   assert(getTypeSizeInBits(LHS->getType()) ==
10743              getTypeSizeInBits(RHS->getType()) &&
10744          "LHS and RHS have different sizes?");
10745   assert(getTypeSizeInBits(FoundLHS->getType()) ==
10746              getTypeSizeInBits(FoundRHS->getType()) &&
10747          "FoundLHS and FoundRHS have different sizes?");
10748   // We want to avoid hurting the compile time with analysis of too big trees.
10749   if (Depth > MaxSCEVOperationsImplicationDepth)
10750     return false;
10751 
10752   // We only want to work with GT comparison so far.
10753   if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT) {
10754     Pred = CmpInst::getSwappedPredicate(Pred);
10755     std::swap(LHS, RHS);
10756     std::swap(FoundLHS, FoundRHS);
10757   }
10758 
10759   // For unsigned, try to reduce it to corresponding signed comparison.
10760   if (Pred == ICmpInst::ICMP_UGT)
10761     // We can replace unsigned predicate with its signed counterpart if all
10762     // involved values are non-negative.
10763     // TODO: We could have better support for unsigned.
10764     if (isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) {
10765       // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing
10766       // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us
10767       // use this fact to prove that LHS and RHS are non-negative.
10768       const SCEV *MinusOne = getMinusOne(LHS->getType());
10769       if (isImpliedCondOperands(ICmpInst::ICMP_SGT, LHS, MinusOne, FoundLHS,
10770                                 FoundRHS) &&
10771           isImpliedCondOperands(ICmpInst::ICMP_SGT, RHS, MinusOne, FoundLHS,
10772                                 FoundRHS))
10773         Pred = ICmpInst::ICMP_SGT;
10774     }
10775 
10776   if (Pred != ICmpInst::ICMP_SGT)
10777     return false;
10778 
10779   auto GetOpFromSExt = [&](const SCEV *S) {
10780     if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
10781       return Ext->getOperand();
10782     // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
10783     // the constant in some cases.
10784     return S;
10785   };
10786 
10787   // Acquire values from extensions.
10788   auto *OrigLHS = LHS;
10789   auto *OrigFoundLHS = FoundLHS;
10790   LHS = GetOpFromSExt(LHS);
10791   FoundLHS = GetOpFromSExt(FoundLHS);
10792 
10793   // Is the SGT predicate can be proved trivially or using the found context.
10794   auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
10795     return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
10796            isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
10797                                   FoundRHS, Depth + 1);
10798   };
10799 
10800   if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
10801     // We want to avoid creation of any new non-constant SCEV. Since we are
10802     // going to compare the operands to RHS, we should be certain that we don't
10803     // need any size extensions for this. So let's decline all cases when the
10804     // sizes of types of LHS and RHS do not match.
10805     // TODO: Maybe try to get RHS from sext to catch more cases?
10806     if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType()))
10807       return false;
10808 
10809     // Should not overflow.
10810     if (!LHSAddExpr->hasNoSignedWrap())
10811       return false;
10812 
10813     auto *LL = LHSAddExpr->getOperand(0);
10814     auto *LR = LHSAddExpr->getOperand(1);
10815     auto *MinusOne = getMinusOne(RHS->getType());
10816 
10817     // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
10818     auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
10819       return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
10820     };
10821     // Try to prove the following rule:
10822     // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
10823     // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
10824     if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
10825       return true;
10826   } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
10827     Value *LL, *LR;
10828     // FIXME: Once we have SDiv implemented, we can get rid of this matching.
10829 
10830     using namespace llvm::PatternMatch;
10831 
10832     if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
10833       // Rules for division.
10834       // We are going to perform some comparisons with Denominator and its
10835       // derivative expressions. In general case, creating a SCEV for it may
10836       // lead to a complex analysis of the entire graph, and in particular it
10837       // can request trip count recalculation for the same loop. This would
10838       // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
10839       // this, we only want to create SCEVs that are constants in this section.
10840       // So we bail if Denominator is not a constant.
10841       if (!isa<ConstantInt>(LR))
10842         return false;
10843 
10844       auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
10845 
10846       // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
10847       // then a SCEV for the numerator already exists and matches with FoundLHS.
10848       auto *Numerator = getExistingSCEV(LL);
10849       if (!Numerator || Numerator->getType() != FoundLHS->getType())
10850         return false;
10851 
10852       // Make sure that the numerator matches with FoundLHS and the denominator
10853       // is positive.
10854       if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
10855         return false;
10856 
10857       auto *DTy = Denominator->getType();
10858       auto *FRHSTy = FoundRHS->getType();
10859       if (DTy->isPointerTy() != FRHSTy->isPointerTy())
10860         // One of types is a pointer and another one is not. We cannot extend
10861         // them properly to a wider type, so let us just reject this case.
10862         // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
10863         // to avoid this check.
10864         return false;
10865 
10866       // Given that:
10867       // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
10868       auto *WTy = getWiderType(DTy, FRHSTy);
10869       auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
10870       auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
10871 
10872       // Try to prove the following rule:
10873       // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
10874       // For example, given that FoundLHS > 2. It means that FoundLHS is at
10875       // least 3. If we divide it by Denominator < 4, we will have at least 1.
10876       auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
10877       if (isKnownNonPositive(RHS) &&
10878           IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
10879         return true;
10880 
10881       // Try to prove the following rule:
10882       // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
10883       // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
10884       // If we divide it by Denominator > 2, then:
10885       // 1. If FoundLHS is negative, then the result is 0.
10886       // 2. If FoundLHS is non-negative, then the result is non-negative.
10887       // Anyways, the result is non-negative.
10888       auto *MinusOne = getMinusOne(WTy);
10889       auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
10890       if (isKnownNegative(RHS) &&
10891           IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
10892         return true;
10893     }
10894   }
10895 
10896   // If our expression contained SCEVUnknown Phis, and we split it down and now
10897   // need to prove something for them, try to prove the predicate for every
10898   // possible incoming values of those Phis.
10899   if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1))
10900     return true;
10901 
10902   return false;
10903 }
10904 
10905 static bool isKnownPredicateExtendIdiom(ICmpInst::Predicate Pred,
10906                                         const SCEV *LHS, const SCEV *RHS) {
10907   // zext x u<= sext x, sext x s<= zext x
10908   switch (Pred) {
10909   case ICmpInst::ICMP_SGE:
10910     std::swap(LHS, RHS);
10911     LLVM_FALLTHROUGH;
10912   case ICmpInst::ICMP_SLE: {
10913     // If operand >=s 0 then ZExt == SExt.  If operand <s 0 then SExt <s ZExt.
10914     const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(LHS);
10915     const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(RHS);
10916     if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand())
10917       return true;
10918     break;
10919   }
10920   case ICmpInst::ICMP_UGE:
10921     std::swap(LHS, RHS);
10922     LLVM_FALLTHROUGH;
10923   case ICmpInst::ICMP_ULE: {
10924     // If operand >=s 0 then ZExt == SExt.  If operand <s 0 then ZExt <u SExt.
10925     const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS);
10926     const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(RHS);
10927     if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand())
10928       return true;
10929     break;
10930   }
10931   default:
10932     break;
10933   };
10934   return false;
10935 }
10936 
10937 bool
10938 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred,
10939                                            const SCEV *LHS, const SCEV *RHS) {
10940   return isKnownPredicateExtendIdiom(Pred, LHS, RHS) ||
10941          isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
10942          IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
10943          IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
10944          isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
10945 }
10946 
10947 bool
10948 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
10949                                              const SCEV *LHS, const SCEV *RHS,
10950                                              const SCEV *FoundLHS,
10951                                              const SCEV *FoundRHS) {
10952   switch (Pred) {
10953   default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
10954   case ICmpInst::ICMP_EQ:
10955   case ICmpInst::ICMP_NE:
10956     if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
10957       return true;
10958     break;
10959   case ICmpInst::ICMP_SLT:
10960   case ICmpInst::ICMP_SLE:
10961     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
10962         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS))
10963       return true;
10964     break;
10965   case ICmpInst::ICMP_SGT:
10966   case ICmpInst::ICMP_SGE:
10967     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
10968         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS))
10969       return true;
10970     break;
10971   case ICmpInst::ICMP_ULT:
10972   case ICmpInst::ICMP_ULE:
10973     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
10974         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS))
10975       return true;
10976     break;
10977   case ICmpInst::ICMP_UGT:
10978   case ICmpInst::ICMP_UGE:
10979     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
10980         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS))
10981       return true;
10982     break;
10983   }
10984 
10985   // Maybe it can be proved via operations?
10986   if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
10987     return true;
10988 
10989   return false;
10990 }
10991 
10992 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
10993                                                      const SCEV *LHS,
10994                                                      const SCEV *RHS,
10995                                                      const SCEV *FoundLHS,
10996                                                      const SCEV *FoundRHS) {
10997   if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
10998     // The restriction on `FoundRHS` be lifted easily -- it exists only to
10999     // reduce the compile time impact of this optimization.
11000     return false;
11001 
11002   Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
11003   if (!Addend)
11004     return false;
11005 
11006   const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
11007 
11008   // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
11009   // antecedent "`FoundLHS` `Pred` `FoundRHS`".
11010   ConstantRange FoundLHSRange =
11011       ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS);
11012 
11013   // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
11014   ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
11015 
11016   // We can also compute the range of values for `LHS` that satisfy the
11017   // consequent, "`LHS` `Pred` `RHS`":
11018   const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
11019   ConstantRange SatisfyingLHSRange =
11020       ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS);
11021 
11022   // The antecedent implies the consequent if every value of `LHS` that
11023   // satisfies the antecedent also satisfies the consequent.
11024   return SatisfyingLHSRange.contains(LHSRange);
11025 }
11026 
11027 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
11028                                          bool IsSigned, bool NoWrap) {
11029   assert(isKnownPositive(Stride) && "Positive stride expected!");
11030 
11031   if (NoWrap) return false;
11032 
11033   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
11034   const SCEV *One = getOne(Stride->getType());
11035 
11036   if (IsSigned) {
11037     APInt MaxRHS = getSignedRangeMax(RHS);
11038     APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
11039     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
11040 
11041     // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
11042     return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS);
11043   }
11044 
11045   APInt MaxRHS = getUnsignedRangeMax(RHS);
11046   APInt MaxValue = APInt::getMaxValue(BitWidth);
11047   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
11048 
11049   // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
11050   return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS);
11051 }
11052 
11053 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
11054                                          bool IsSigned, bool NoWrap) {
11055   if (NoWrap) return false;
11056 
11057   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
11058   const SCEV *One = getOne(Stride->getType());
11059 
11060   if (IsSigned) {
11061     APInt MinRHS = getSignedRangeMin(RHS);
11062     APInt MinValue = APInt::getSignedMinValue(BitWidth);
11063     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
11064 
11065     // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
11066     return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS);
11067   }
11068 
11069   APInt MinRHS = getUnsignedRangeMin(RHS);
11070   APInt MinValue = APInt::getMinValue(BitWidth);
11071   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
11072 
11073   // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
11074   return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS);
11075 }
11076 
11077 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step,
11078                                             bool Equality) {
11079   const SCEV *One = getOne(Step->getType());
11080   Delta = Equality ? getAddExpr(Delta, Step)
11081                    : getAddExpr(Delta, getMinusSCEV(Step, One));
11082   return getUDivExpr(Delta, Step);
11083 }
11084 
11085 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start,
11086                                                     const SCEV *Stride,
11087                                                     const SCEV *End,
11088                                                     unsigned BitWidth,
11089                                                     bool IsSigned) {
11090 
11091   assert(!isKnownNonPositive(Stride) &&
11092          "Stride is expected strictly positive!");
11093   // Calculate the maximum backedge count based on the range of values
11094   // permitted by Start, End, and Stride.
11095   const SCEV *MaxBECount;
11096   APInt MinStart =
11097       IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start);
11098 
11099   APInt StrideForMaxBECount =
11100       IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride);
11101 
11102   // We already know that the stride is positive, so we paper over conservatism
11103   // in our range computation by forcing StrideForMaxBECount to be at least one.
11104   // In theory this is unnecessary, but we expect MaxBECount to be a
11105   // SCEVConstant, and (udiv <constant> 0) is not constant folded by SCEV (there
11106   // is nothing to constant fold it to).
11107   APInt One(BitWidth, 1, IsSigned);
11108   StrideForMaxBECount = APIntOps::smax(One, StrideForMaxBECount);
11109 
11110   APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth)
11111                             : APInt::getMaxValue(BitWidth);
11112   APInt Limit = MaxValue - (StrideForMaxBECount - 1);
11113 
11114   // Although End can be a MAX expression we estimate MaxEnd considering only
11115   // the case End = RHS of the loop termination condition. This is safe because
11116   // in the other case (End - Start) is zero, leading to a zero maximum backedge
11117   // taken count.
11118   APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit)
11119                           : APIntOps::umin(getUnsignedRangeMax(End), Limit);
11120 
11121   MaxBECount = computeBECount(getConstant(MaxEnd - MinStart) /* Delta */,
11122                               getConstant(StrideForMaxBECount) /* Step */,
11123                               false /* Equality */);
11124 
11125   return MaxBECount;
11126 }
11127 
11128 ScalarEvolution::ExitLimit
11129 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
11130                                   const Loop *L, bool IsSigned,
11131                                   bool ControlsExit, bool AllowPredicates) {
11132   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
11133 
11134   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
11135   bool PredicatedIV = false;
11136 
11137   if (!IV && AllowPredicates) {
11138     // Try to make this an AddRec using runtime tests, in the first X
11139     // iterations of this loop, where X is the SCEV expression found by the
11140     // algorithm below.
11141     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
11142     PredicatedIV = true;
11143   }
11144 
11145   // Avoid weird loops
11146   if (!IV || IV->getLoop() != L || !IV->isAffine())
11147     return getCouldNotCompute();
11148 
11149   bool NoWrap = ControlsExit &&
11150                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
11151 
11152   const SCEV *Stride = IV->getStepRecurrence(*this);
11153 
11154   bool PositiveStride = isKnownPositive(Stride);
11155 
11156   // Avoid negative or zero stride values.
11157   if (!PositiveStride) {
11158     // We can compute the correct backedge taken count for loops with unknown
11159     // strides if we can prove that the loop is not an infinite loop with side
11160     // effects. Here's the loop structure we are trying to handle -
11161     //
11162     // i = start
11163     // do {
11164     //   A[i] = i;
11165     //   i += s;
11166     // } while (i < end);
11167     //
11168     // The backedge taken count for such loops is evaluated as -
11169     // (max(end, start + stride) - start - 1) /u stride
11170     //
11171     // The additional preconditions that we need to check to prove correctness
11172     // of the above formula is as follows -
11173     //
11174     // a) IV is either nuw or nsw depending upon signedness (indicated by the
11175     //    NoWrap flag).
11176     // b) loop is single exit with no side effects.
11177     //
11178     //
11179     // Precondition a) implies that if the stride is negative, this is a single
11180     // trip loop. The backedge taken count formula reduces to zero in this case.
11181     //
11182     // Precondition b) implies that the unknown stride cannot be zero otherwise
11183     // we have UB.
11184     //
11185     // The positive stride case is the same as isKnownPositive(Stride) returning
11186     // true (original behavior of the function).
11187     //
11188     // We want to make sure that the stride is truly unknown as there are edge
11189     // cases where ScalarEvolution propagates no wrap flags to the
11190     // post-increment/decrement IV even though the increment/decrement operation
11191     // itself is wrapping. The computed backedge taken count may be wrong in
11192     // such cases. This is prevented by checking that the stride is not known to
11193     // be either positive or non-positive. For example, no wrap flags are
11194     // propagated to the post-increment IV of this loop with a trip count of 2 -
11195     //
11196     // unsigned char i;
11197     // for(i=127; i<128; i+=129)
11198     //   A[i] = i;
11199     //
11200     if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) ||
11201         !loopHasNoSideEffects(L))
11202       return getCouldNotCompute();
11203   } else if (!Stride->isOne() &&
11204              doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap))
11205     // Avoid proven overflow cases: this will ensure that the backedge taken
11206     // count will not generate any unsigned overflow. Relaxed no-overflow
11207     // conditions exploit NoWrapFlags, allowing to optimize in presence of
11208     // undefined behaviors like the case of C language.
11209     return getCouldNotCompute();
11210 
11211   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT
11212                                       : ICmpInst::ICMP_ULT;
11213   const SCEV *Start = IV->getStart();
11214   const SCEV *End = RHS;
11215   // When the RHS is not invariant, we do not know the end bound of the loop and
11216   // cannot calculate the ExactBECount needed by ExitLimit. However, we can
11217   // calculate the MaxBECount, given the start, stride and max value for the end
11218   // bound of the loop (RHS), and the fact that IV does not overflow (which is
11219   // checked above).
11220   if (!isLoopInvariant(RHS, L)) {
11221     const SCEV *MaxBECount = computeMaxBECountForLT(
11222         Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
11223     return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount,
11224                      false /*MaxOrZero*/, Predicates);
11225   }
11226   // If the backedge is taken at least once, then it will be taken
11227   // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start
11228   // is the LHS value of the less-than comparison the first time it is evaluated
11229   // and End is the RHS.
11230   const SCEV *BECountIfBackedgeTaken =
11231     computeBECount(getMinusSCEV(End, Start), Stride, false);
11232   // If the loop entry is guarded by the result of the backedge test of the
11233   // first loop iteration, then we know the backedge will be taken at least
11234   // once and so the backedge taken count is as above. If not then we use the
11235   // expression (max(End,Start)-Start)/Stride to describe the backedge count,
11236   // as if the backedge is taken at least once max(End,Start) is End and so the
11237   // result is as above, and if not max(End,Start) is Start so we get a backedge
11238   // count of zero.
11239   const SCEV *BECount;
11240   if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS))
11241     BECount = BECountIfBackedgeTaken;
11242   else {
11243     // If we know that RHS >= Start in the context of loop, then we know that
11244     // max(RHS, Start) = RHS at this point.
11245     if (isLoopEntryGuardedByCond(
11246             L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, RHS, Start))
11247       End = RHS;
11248     else
11249       End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
11250     BECount = computeBECount(getMinusSCEV(End, Start), Stride, false);
11251   }
11252 
11253   const SCEV *MaxBECount;
11254   bool MaxOrZero = false;
11255   if (isa<SCEVConstant>(BECount))
11256     MaxBECount = BECount;
11257   else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) {
11258     // If we know exactly how many times the backedge will be taken if it's
11259     // taken at least once, then the backedge count will either be that or
11260     // zero.
11261     MaxBECount = BECountIfBackedgeTaken;
11262     MaxOrZero = true;
11263   } else {
11264     MaxBECount = computeMaxBECountForLT(
11265         Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
11266   }
11267 
11268   if (isa<SCEVCouldNotCompute>(MaxBECount) &&
11269       !isa<SCEVCouldNotCompute>(BECount))
11270     MaxBECount = getConstant(getUnsignedRangeMax(BECount));
11271 
11272   return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates);
11273 }
11274 
11275 ScalarEvolution::ExitLimit
11276 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
11277                                      const Loop *L, bool IsSigned,
11278                                      bool ControlsExit, bool AllowPredicates) {
11279   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
11280   // We handle only IV > Invariant
11281   if (!isLoopInvariant(RHS, L))
11282     return getCouldNotCompute();
11283 
11284   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
11285   if (!IV && AllowPredicates)
11286     // Try to make this an AddRec using runtime tests, in the first X
11287     // iterations of this loop, where X is the SCEV expression found by the
11288     // algorithm below.
11289     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
11290 
11291   // Avoid weird loops
11292   if (!IV || IV->getLoop() != L || !IV->isAffine())
11293     return getCouldNotCompute();
11294 
11295   bool NoWrap = ControlsExit &&
11296                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
11297 
11298   const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
11299 
11300   // Avoid negative or zero stride values
11301   if (!isKnownPositive(Stride))
11302     return getCouldNotCompute();
11303 
11304   // Avoid proven overflow cases: this will ensure that the backedge taken count
11305   // will not generate any unsigned overflow. Relaxed no-overflow conditions
11306   // exploit NoWrapFlags, allowing to optimize in presence of undefined
11307   // behaviors like the case of C language.
11308   if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap))
11309     return getCouldNotCompute();
11310 
11311   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT
11312                                       : ICmpInst::ICMP_UGT;
11313 
11314   const SCEV *Start = IV->getStart();
11315   const SCEV *End = RHS;
11316   if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) {
11317     // If we know that Start >= RHS in the context of loop, then we know that
11318     // min(RHS, Start) = RHS at this point.
11319     if (isLoopEntryGuardedByCond(
11320             L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, RHS))
11321       End = RHS;
11322     else
11323       End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
11324   }
11325 
11326   const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false);
11327 
11328   APInt MaxStart = IsSigned ? getSignedRangeMax(Start)
11329                             : getUnsignedRangeMax(Start);
11330 
11331   APInt MinStride = IsSigned ? getSignedRangeMin(Stride)
11332                              : getUnsignedRangeMin(Stride);
11333 
11334   unsigned BitWidth = getTypeSizeInBits(LHS->getType());
11335   APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
11336                          : APInt::getMinValue(BitWidth) + (MinStride - 1);
11337 
11338   // Although End can be a MIN expression we estimate MinEnd considering only
11339   // the case End = RHS. This is safe because in the other case (Start - End)
11340   // is zero, leading to a zero maximum backedge taken count.
11341   APInt MinEnd =
11342     IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit)
11343              : APIntOps::umax(getUnsignedRangeMin(RHS), Limit);
11344 
11345   const SCEV *MaxBECount = isa<SCEVConstant>(BECount)
11346                                ? BECount
11347                                : computeBECount(getConstant(MaxStart - MinEnd),
11348                                                 getConstant(MinStride), false);
11349 
11350   if (isa<SCEVCouldNotCompute>(MaxBECount))
11351     MaxBECount = BECount;
11352 
11353   return ExitLimit(BECount, MaxBECount, false, Predicates);
11354 }
11355 
11356 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range,
11357                                                     ScalarEvolution &SE) const {
11358   if (Range.isFullSet())  // Infinite loop.
11359     return SE.getCouldNotCompute();
11360 
11361   // If the start is a non-zero constant, shift the range to simplify things.
11362   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
11363     if (!SC->getValue()->isZero()) {
11364       SmallVector<const SCEV *, 4> Operands(operands());
11365       Operands[0] = SE.getZero(SC->getType());
11366       const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
11367                                              getNoWrapFlags(FlagNW));
11368       if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
11369         return ShiftedAddRec->getNumIterationsInRange(
11370             Range.subtract(SC->getAPInt()), SE);
11371       // This is strange and shouldn't happen.
11372       return SE.getCouldNotCompute();
11373     }
11374 
11375   // The only time we can solve this is when we have all constant indices.
11376   // Otherwise, we cannot determine the overflow conditions.
11377   if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
11378     return SE.getCouldNotCompute();
11379 
11380   // Okay at this point we know that all elements of the chrec are constants and
11381   // that the start element is zero.
11382 
11383   // First check to see if the range contains zero.  If not, the first
11384   // iteration exits.
11385   unsigned BitWidth = SE.getTypeSizeInBits(getType());
11386   if (!Range.contains(APInt(BitWidth, 0)))
11387     return SE.getZero(getType());
11388 
11389   if (isAffine()) {
11390     // If this is an affine expression then we have this situation:
11391     //   Solve {0,+,A} in Range  ===  Ax in Range
11392 
11393     // We know that zero is in the range.  If A is positive then we know that
11394     // the upper value of the range must be the first possible exit value.
11395     // If A is negative then the lower of the range is the last possible loop
11396     // value.  Also note that we already checked for a full range.
11397     APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
11398     APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower();
11399 
11400     // The exit value should be (End+A)/A.
11401     APInt ExitVal = (End + A).udiv(A);
11402     ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
11403 
11404     // Evaluate at the exit value.  If we really did fall out of the valid
11405     // range, then we computed our trip count, otherwise wrap around or other
11406     // things must have happened.
11407     ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
11408     if (Range.contains(Val->getValue()))
11409       return SE.getCouldNotCompute();  // Something strange happened
11410 
11411     // Ensure that the previous value is in the range.  This is a sanity check.
11412     assert(Range.contains(
11413            EvaluateConstantChrecAtConstant(this,
11414            ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&
11415            "Linear scev computation is off in a bad way!");
11416     return SE.getConstant(ExitValue);
11417   }
11418 
11419   if (isQuadratic()) {
11420     if (auto S = SolveQuadraticAddRecRange(this, Range, SE))
11421       return SE.getConstant(S.getValue());
11422   }
11423 
11424   return SE.getCouldNotCompute();
11425 }
11426 
11427 const SCEVAddRecExpr *
11428 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const {
11429   assert(getNumOperands() > 1 && "AddRec with zero step?");
11430   // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)),
11431   // but in this case we cannot guarantee that the value returned will be an
11432   // AddRec because SCEV does not have a fixed point where it stops
11433   // simplification: it is legal to return ({rec1} + {rec2}). For example, it
11434   // may happen if we reach arithmetic depth limit while simplifying. So we
11435   // construct the returned value explicitly.
11436   SmallVector<const SCEV *, 3> Ops;
11437   // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and
11438   // (this + Step) is {A+B,+,B+C,+...,+,N}.
11439   for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i)
11440     Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1)));
11441   // We know that the last operand is not a constant zero (otherwise it would
11442   // have been popped out earlier). This guarantees us that if the result has
11443   // the same last operand, then it will also not be popped out, meaning that
11444   // the returned value will be an AddRec.
11445   const SCEV *Last = getOperand(getNumOperands() - 1);
11446   assert(!Last->isZero() && "Recurrency with zero step?");
11447   Ops.push_back(Last);
11448   return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(),
11449                                                SCEV::FlagAnyWrap));
11450 }
11451 
11452 // Return true when S contains at least an undef value.
11453 static inline bool containsUndefs(const SCEV *S) {
11454   return SCEVExprContains(S, [](const SCEV *S) {
11455     if (const auto *SU = dyn_cast<SCEVUnknown>(S))
11456       return isa<UndefValue>(SU->getValue());
11457     return false;
11458   });
11459 }
11460 
11461 namespace {
11462 
11463 // Collect all steps of SCEV expressions.
11464 struct SCEVCollectStrides {
11465   ScalarEvolution &SE;
11466   SmallVectorImpl<const SCEV *> &Strides;
11467 
11468   SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S)
11469       : SE(SE), Strides(S) {}
11470 
11471   bool follow(const SCEV *S) {
11472     if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
11473       Strides.push_back(AR->getStepRecurrence(SE));
11474     return true;
11475   }
11476 
11477   bool isDone() const { return false; }
11478 };
11479 
11480 // Collect all SCEVUnknown and SCEVMulExpr expressions.
11481 struct SCEVCollectTerms {
11482   SmallVectorImpl<const SCEV *> &Terms;
11483 
11484   SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) : Terms(T) {}
11485 
11486   bool follow(const SCEV *S) {
11487     if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) ||
11488         isa<SCEVSignExtendExpr>(S)) {
11489       if (!containsUndefs(S))
11490         Terms.push_back(S);
11491 
11492       // Stop recursion: once we collected a term, do not walk its operands.
11493       return false;
11494     }
11495 
11496     // Keep looking.
11497     return true;
11498   }
11499 
11500   bool isDone() const { return false; }
11501 };
11502 
11503 // Check if a SCEV contains an AddRecExpr.
11504 struct SCEVHasAddRec {
11505   bool &ContainsAddRec;
11506 
11507   SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) {
11508     ContainsAddRec = false;
11509   }
11510 
11511   bool follow(const SCEV *S) {
11512     if (isa<SCEVAddRecExpr>(S)) {
11513       ContainsAddRec = true;
11514 
11515       // Stop recursion: once we collected a term, do not walk its operands.
11516       return false;
11517     }
11518 
11519     // Keep looking.
11520     return true;
11521   }
11522 
11523   bool isDone() const { return false; }
11524 };
11525 
11526 // Find factors that are multiplied with an expression that (possibly as a
11527 // subexpression) contains an AddRecExpr. In the expression:
11528 //
11529 //  8 * (100 +  %p * %q * (%a + {0, +, 1}_loop))
11530 //
11531 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)"
11532 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size
11533 // parameters as they form a product with an induction variable.
11534 //
11535 // This collector expects all array size parameters to be in the same MulExpr.
11536 // It might be necessary to later add support for collecting parameters that are
11537 // spread over different nested MulExpr.
11538 struct SCEVCollectAddRecMultiplies {
11539   SmallVectorImpl<const SCEV *> &Terms;
11540   ScalarEvolution &SE;
11541 
11542   SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE)
11543       : Terms(T), SE(SE) {}
11544 
11545   bool follow(const SCEV *S) {
11546     if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) {
11547       bool HasAddRec = false;
11548       SmallVector<const SCEV *, 0> Operands;
11549       for (auto Op : Mul->operands()) {
11550         const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op);
11551         if (Unknown && !isa<CallInst>(Unknown->getValue())) {
11552           Operands.push_back(Op);
11553         } else if (Unknown) {
11554           HasAddRec = true;
11555         } else {
11556           bool ContainsAddRec = false;
11557           SCEVHasAddRec ContiansAddRec(ContainsAddRec);
11558           visitAll(Op, ContiansAddRec);
11559           HasAddRec |= ContainsAddRec;
11560         }
11561       }
11562       if (Operands.size() == 0)
11563         return true;
11564 
11565       if (!HasAddRec)
11566         return false;
11567 
11568       Terms.push_back(SE.getMulExpr(Operands));
11569       // Stop recursion: once we collected a term, do not walk its operands.
11570       return false;
11571     }
11572 
11573     // Keep looking.
11574     return true;
11575   }
11576 
11577   bool isDone() const { return false; }
11578 };
11579 
11580 } // end anonymous namespace
11581 
11582 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in
11583 /// two places:
11584 ///   1) The strides of AddRec expressions.
11585 ///   2) Unknowns that are multiplied with AddRec expressions.
11586 void ScalarEvolution::collectParametricTerms(const SCEV *Expr,
11587     SmallVectorImpl<const SCEV *> &Terms) {
11588   SmallVector<const SCEV *, 4> Strides;
11589   SCEVCollectStrides StrideCollector(*this, Strides);
11590   visitAll(Expr, StrideCollector);
11591 
11592   LLVM_DEBUG({
11593     dbgs() << "Strides:\n";
11594     for (const SCEV *S : Strides)
11595       dbgs() << *S << "\n";
11596   });
11597 
11598   for (const SCEV *S : Strides) {
11599     SCEVCollectTerms TermCollector(Terms);
11600     visitAll(S, TermCollector);
11601   }
11602 
11603   LLVM_DEBUG({
11604     dbgs() << "Terms:\n";
11605     for (const SCEV *T : Terms)
11606       dbgs() << *T << "\n";
11607   });
11608 
11609   SCEVCollectAddRecMultiplies MulCollector(Terms, *this);
11610   visitAll(Expr, MulCollector);
11611 }
11612 
11613 static bool findArrayDimensionsRec(ScalarEvolution &SE,
11614                                    SmallVectorImpl<const SCEV *> &Terms,
11615                                    SmallVectorImpl<const SCEV *> &Sizes) {
11616   int Last = Terms.size() - 1;
11617   const SCEV *Step = Terms[Last];
11618 
11619   // End of recursion.
11620   if (Last == 0) {
11621     if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) {
11622       SmallVector<const SCEV *, 2> Qs;
11623       for (const SCEV *Op : M->operands())
11624         if (!isa<SCEVConstant>(Op))
11625           Qs.push_back(Op);
11626 
11627       Step = SE.getMulExpr(Qs);
11628     }
11629 
11630     Sizes.push_back(Step);
11631     return true;
11632   }
11633 
11634   for (const SCEV *&Term : Terms) {
11635     // Normalize the terms before the next call to findArrayDimensionsRec.
11636     const SCEV *Q, *R;
11637     SCEVDivision::divide(SE, Term, Step, &Q, &R);
11638 
11639     // Bail out when GCD does not evenly divide one of the terms.
11640     if (!R->isZero())
11641       return false;
11642 
11643     Term = Q;
11644   }
11645 
11646   // Remove all SCEVConstants.
11647   erase_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); });
11648 
11649   if (Terms.size() > 0)
11650     if (!findArrayDimensionsRec(SE, Terms, Sizes))
11651       return false;
11652 
11653   Sizes.push_back(Step);
11654   return true;
11655 }
11656 
11657 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter.
11658 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) {
11659   for (const SCEV *T : Terms)
11660     if (SCEVExprContains(T, [](const SCEV *S) { return isa<SCEVUnknown>(S); }))
11661       return true;
11662 
11663   return false;
11664 }
11665 
11666 // Return the number of product terms in S.
11667 static inline int numberOfTerms(const SCEV *S) {
11668   if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S))
11669     return Expr->getNumOperands();
11670   return 1;
11671 }
11672 
11673 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) {
11674   if (isa<SCEVConstant>(T))
11675     return nullptr;
11676 
11677   if (isa<SCEVUnknown>(T))
11678     return T;
11679 
11680   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) {
11681     SmallVector<const SCEV *, 2> Factors;
11682     for (const SCEV *Op : M->operands())
11683       if (!isa<SCEVConstant>(Op))
11684         Factors.push_back(Op);
11685 
11686     return SE.getMulExpr(Factors);
11687   }
11688 
11689   return T;
11690 }
11691 
11692 /// Return the size of an element read or written by Inst.
11693 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
11694   Type *Ty;
11695   if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
11696     Ty = Store->getValueOperand()->getType();
11697   else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
11698     Ty = Load->getType();
11699   else
11700     return nullptr;
11701 
11702   Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
11703   return getSizeOfExpr(ETy, Ty);
11704 }
11705 
11706 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
11707                                           SmallVectorImpl<const SCEV *> &Sizes,
11708                                           const SCEV *ElementSize) {
11709   if (Terms.size() < 1 || !ElementSize)
11710     return;
11711 
11712   // Early return when Terms do not contain parameters: we do not delinearize
11713   // non parametric SCEVs.
11714   if (!containsParameters(Terms))
11715     return;
11716 
11717   LLVM_DEBUG({
11718     dbgs() << "Terms:\n";
11719     for (const SCEV *T : Terms)
11720       dbgs() << *T << "\n";
11721   });
11722 
11723   // Remove duplicates.
11724   array_pod_sort(Terms.begin(), Terms.end());
11725   Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end());
11726 
11727   // Put larger terms first.
11728   llvm::sort(Terms, [](const SCEV *LHS, const SCEV *RHS) {
11729     return numberOfTerms(LHS) > numberOfTerms(RHS);
11730   });
11731 
11732   // Try to divide all terms by the element size. If term is not divisible by
11733   // element size, proceed with the original term.
11734   for (const SCEV *&Term : Terms) {
11735     const SCEV *Q, *R;
11736     SCEVDivision::divide(*this, Term, ElementSize, &Q, &R);
11737     if (!Q->isZero())
11738       Term = Q;
11739   }
11740 
11741   SmallVector<const SCEV *, 4> NewTerms;
11742 
11743   // Remove constant factors.
11744   for (const SCEV *T : Terms)
11745     if (const SCEV *NewT = removeConstantFactors(*this, T))
11746       NewTerms.push_back(NewT);
11747 
11748   LLVM_DEBUG({
11749     dbgs() << "Terms after sorting:\n";
11750     for (const SCEV *T : NewTerms)
11751       dbgs() << *T << "\n";
11752   });
11753 
11754   if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) {
11755     Sizes.clear();
11756     return;
11757   }
11758 
11759   // The last element to be pushed into Sizes is the size of an element.
11760   Sizes.push_back(ElementSize);
11761 
11762   LLVM_DEBUG({
11763     dbgs() << "Sizes:\n";
11764     for (const SCEV *S : Sizes)
11765       dbgs() << *S << "\n";
11766   });
11767 }
11768 
11769 void ScalarEvolution::computeAccessFunctions(
11770     const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts,
11771     SmallVectorImpl<const SCEV *> &Sizes) {
11772   // Early exit in case this SCEV is not an affine multivariate function.
11773   if (Sizes.empty())
11774     return;
11775 
11776   if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr))
11777     if (!AR->isAffine())
11778       return;
11779 
11780   const SCEV *Res = Expr;
11781   int Last = Sizes.size() - 1;
11782   for (int i = Last; i >= 0; i--) {
11783     const SCEV *Q, *R;
11784     SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R);
11785 
11786     LLVM_DEBUG({
11787       dbgs() << "Res: " << *Res << "\n";
11788       dbgs() << "Sizes[i]: " << *Sizes[i] << "\n";
11789       dbgs() << "Res divided by Sizes[i]:\n";
11790       dbgs() << "Quotient: " << *Q << "\n";
11791       dbgs() << "Remainder: " << *R << "\n";
11792     });
11793 
11794     Res = Q;
11795 
11796     // Do not record the last subscript corresponding to the size of elements in
11797     // the array.
11798     if (i == Last) {
11799 
11800       // Bail out if the remainder is too complex.
11801       if (isa<SCEVAddRecExpr>(R)) {
11802         Subscripts.clear();
11803         Sizes.clear();
11804         return;
11805       }
11806 
11807       continue;
11808     }
11809 
11810     // Record the access function for the current subscript.
11811     Subscripts.push_back(R);
11812   }
11813 
11814   // Also push in last position the remainder of the last division: it will be
11815   // the access function of the innermost dimension.
11816   Subscripts.push_back(Res);
11817 
11818   std::reverse(Subscripts.begin(), Subscripts.end());
11819 
11820   LLVM_DEBUG({
11821     dbgs() << "Subscripts:\n";
11822     for (const SCEV *S : Subscripts)
11823       dbgs() << *S << "\n";
11824   });
11825 }
11826 
11827 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and
11828 /// sizes of an array access. Returns the remainder of the delinearization that
11829 /// is the offset start of the array.  The SCEV->delinearize algorithm computes
11830 /// the multiples of SCEV coefficients: that is a pattern matching of sub
11831 /// expressions in the stride and base of a SCEV corresponding to the
11832 /// computation of a GCD (greatest common divisor) of base and stride.  When
11833 /// SCEV->delinearize fails, it returns the SCEV unchanged.
11834 ///
11835 /// For example: when analyzing the memory access A[i][j][k] in this loop nest
11836 ///
11837 ///  void foo(long n, long m, long o, double A[n][m][o]) {
11838 ///
11839 ///    for (long i = 0; i < n; i++)
11840 ///      for (long j = 0; j < m; j++)
11841 ///        for (long k = 0; k < o; k++)
11842 ///          A[i][j][k] = 1.0;
11843 ///  }
11844 ///
11845 /// the delinearization input is the following AddRec SCEV:
11846 ///
11847 ///  AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k>
11848 ///
11849 /// From this SCEV, we are able to say that the base offset of the access is %A
11850 /// because it appears as an offset that does not divide any of the strides in
11851 /// the loops:
11852 ///
11853 ///  CHECK: Base offset: %A
11854 ///
11855 /// and then SCEV->delinearize determines the size of some of the dimensions of
11856 /// the array as these are the multiples by which the strides are happening:
11857 ///
11858 ///  CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes.
11859 ///
11860 /// Note that the outermost dimension remains of UnknownSize because there are
11861 /// no strides that would help identifying the size of the last dimension: when
11862 /// the array has been statically allocated, one could compute the size of that
11863 /// dimension by dividing the overall size of the array by the size of the known
11864 /// dimensions: %m * %o * 8.
11865 ///
11866 /// Finally delinearize provides the access functions for the array reference
11867 /// that does correspond to A[i][j][k] of the above C testcase:
11868 ///
11869 ///  CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>]
11870 ///
11871 /// The testcases are checking the output of a function pass:
11872 /// DelinearizationPass that walks through all loads and stores of a function
11873 /// asking for the SCEV of the memory access with respect to all enclosing
11874 /// loops, calling SCEV->delinearize on that and printing the results.
11875 void ScalarEvolution::delinearize(const SCEV *Expr,
11876                                  SmallVectorImpl<const SCEV *> &Subscripts,
11877                                  SmallVectorImpl<const SCEV *> &Sizes,
11878                                  const SCEV *ElementSize) {
11879   // First step: collect parametric terms.
11880   SmallVector<const SCEV *, 4> Terms;
11881   collectParametricTerms(Expr, Terms);
11882 
11883   if (Terms.empty())
11884     return;
11885 
11886   // Second step: find subscript sizes.
11887   findArrayDimensions(Terms, Sizes, ElementSize);
11888 
11889   if (Sizes.empty())
11890     return;
11891 
11892   // Third step: compute the access functions for each subscript.
11893   computeAccessFunctions(Expr, Subscripts, Sizes);
11894 
11895   if (Subscripts.empty())
11896     return;
11897 
11898   LLVM_DEBUG({
11899     dbgs() << "succeeded to delinearize " << *Expr << "\n";
11900     dbgs() << "ArrayDecl[UnknownSize]";
11901     for (const SCEV *S : Sizes)
11902       dbgs() << "[" << *S << "]";
11903 
11904     dbgs() << "\nArrayRef";
11905     for (const SCEV *S : Subscripts)
11906       dbgs() << "[" << *S << "]";
11907     dbgs() << "\n";
11908   });
11909 }
11910 
11911 bool ScalarEvolution::getIndexExpressionsFromGEP(
11912     const GetElementPtrInst *GEP, SmallVectorImpl<const SCEV *> &Subscripts,
11913     SmallVectorImpl<int> &Sizes) {
11914   assert(Subscripts.empty() && Sizes.empty() &&
11915          "Expected output lists to be empty on entry to this function.");
11916   assert(GEP && "getIndexExpressionsFromGEP called with a null GEP");
11917   Type *Ty = GEP->getPointerOperandType();
11918   bool DroppedFirstDim = false;
11919   for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
11920     const SCEV *Expr = getSCEV(GEP->getOperand(i));
11921     if (i == 1) {
11922       if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
11923         Ty = PtrTy->getElementType();
11924       } else if (auto *ArrayTy = dyn_cast<ArrayType>(Ty)) {
11925         Ty = ArrayTy->getElementType();
11926       } else {
11927         Subscripts.clear();
11928         Sizes.clear();
11929         return false;
11930       }
11931       if (auto *Const = dyn_cast<SCEVConstant>(Expr))
11932         if (Const->getValue()->isZero()) {
11933           DroppedFirstDim = true;
11934           continue;
11935         }
11936       Subscripts.push_back(Expr);
11937       continue;
11938     }
11939 
11940     auto *ArrayTy = dyn_cast<ArrayType>(Ty);
11941     if (!ArrayTy) {
11942       Subscripts.clear();
11943       Sizes.clear();
11944       return false;
11945     }
11946 
11947     Subscripts.push_back(Expr);
11948     if (!(DroppedFirstDim && i == 2))
11949       Sizes.push_back(ArrayTy->getNumElements());
11950 
11951     Ty = ArrayTy->getElementType();
11952   }
11953   return !Subscripts.empty();
11954 }
11955 
11956 //===----------------------------------------------------------------------===//
11957 //                   SCEVCallbackVH Class Implementation
11958 //===----------------------------------------------------------------------===//
11959 
11960 void ScalarEvolution::SCEVCallbackVH::deleted() {
11961   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
11962   if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
11963     SE->ConstantEvolutionLoopExitValue.erase(PN);
11964   SE->eraseValueFromMap(getValPtr());
11965   // this now dangles!
11966 }
11967 
11968 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
11969   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
11970 
11971   // Forget all the expressions associated with users of the old value,
11972   // so that future queries will recompute the expressions using the new
11973   // value.
11974   Value *Old = getValPtr();
11975   SmallVector<User *, 16> Worklist(Old->users());
11976   SmallPtrSet<User *, 8> Visited;
11977   while (!Worklist.empty()) {
11978     User *U = Worklist.pop_back_val();
11979     // Deleting the Old value will cause this to dangle. Postpone
11980     // that until everything else is done.
11981     if (U == Old)
11982       continue;
11983     if (!Visited.insert(U).second)
11984       continue;
11985     if (PHINode *PN = dyn_cast<PHINode>(U))
11986       SE->ConstantEvolutionLoopExitValue.erase(PN);
11987     SE->eraseValueFromMap(U);
11988     llvm::append_range(Worklist, U->users());
11989   }
11990   // Delete the Old value.
11991   if (PHINode *PN = dyn_cast<PHINode>(Old))
11992     SE->ConstantEvolutionLoopExitValue.erase(PN);
11993   SE->eraseValueFromMap(Old);
11994   // this now dangles!
11995 }
11996 
11997 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
11998   : CallbackVH(V), SE(se) {}
11999 
12000 //===----------------------------------------------------------------------===//
12001 //                   ScalarEvolution Class Implementation
12002 //===----------------------------------------------------------------------===//
12003 
12004 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
12005                                  AssumptionCache &AC, DominatorTree &DT,
12006                                  LoopInfo &LI)
12007     : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
12008       CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64),
12009       LoopDispositions(64), BlockDispositions(64) {
12010   // To use guards for proving predicates, we need to scan every instruction in
12011   // relevant basic blocks, and not just terminators.  Doing this is a waste of
12012   // time if the IR does not actually contain any calls to
12013   // @llvm.experimental.guard, so do a quick check and remember this beforehand.
12014   //
12015   // This pessimizes the case where a pass that preserves ScalarEvolution wants
12016   // to _add_ guards to the module when there weren't any before, and wants
12017   // ScalarEvolution to optimize based on those guards.  For now we prefer to be
12018   // efficient in lieu of being smart in that rather obscure case.
12019 
12020   auto *GuardDecl = F.getParent()->getFunction(
12021       Intrinsic::getName(Intrinsic::experimental_guard));
12022   HasGuards = GuardDecl && !GuardDecl->use_empty();
12023 }
12024 
12025 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
12026     : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT),
12027       LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
12028       ValueExprMap(std::move(Arg.ValueExprMap)),
12029       PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
12030       PendingPhiRanges(std::move(Arg.PendingPhiRanges)),
12031       PendingMerges(std::move(Arg.PendingMerges)),
12032       MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)),
12033       BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
12034       PredicatedBackedgeTakenCounts(
12035           std::move(Arg.PredicatedBackedgeTakenCounts)),
12036       ConstantEvolutionLoopExitValue(
12037           std::move(Arg.ConstantEvolutionLoopExitValue)),
12038       ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
12039       LoopDispositions(std::move(Arg.LoopDispositions)),
12040       LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
12041       BlockDispositions(std::move(Arg.BlockDispositions)),
12042       UnsignedRanges(std::move(Arg.UnsignedRanges)),
12043       SignedRanges(std::move(Arg.SignedRanges)),
12044       UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
12045       UniquePreds(std::move(Arg.UniquePreds)),
12046       SCEVAllocator(std::move(Arg.SCEVAllocator)),
12047       LoopUsers(std::move(Arg.LoopUsers)),
12048       PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)),
12049       FirstUnknown(Arg.FirstUnknown) {
12050   Arg.FirstUnknown = nullptr;
12051 }
12052 
12053 ScalarEvolution::~ScalarEvolution() {
12054   // Iterate through all the SCEVUnknown instances and call their
12055   // destructors, so that they release their references to their values.
12056   for (SCEVUnknown *U = FirstUnknown; U;) {
12057     SCEVUnknown *Tmp = U;
12058     U = U->Next;
12059     Tmp->~SCEVUnknown();
12060   }
12061   FirstUnknown = nullptr;
12062 
12063   ExprValueMap.clear();
12064   ValueExprMap.clear();
12065   HasRecMap.clear();
12066 
12067   // Free any extra memory created for ExitNotTakenInfo in the unlikely event
12068   // that a loop had multiple computable exits.
12069   for (auto &BTCI : BackedgeTakenCounts)
12070     BTCI.second.clear();
12071   for (auto &BTCI : PredicatedBackedgeTakenCounts)
12072     BTCI.second.clear();
12073 
12074   assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
12075   assert(PendingPhiRanges.empty() && "getRangeRef garbage");
12076   assert(PendingMerges.empty() && "isImpliedViaMerge garbage");
12077   assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
12078   assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
12079 }
12080 
12081 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
12082   return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
12083 }
12084 
12085 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
12086                           const Loop *L) {
12087   // Print all inner loops first
12088   for (Loop *I : *L)
12089     PrintLoopInfo(OS, SE, I);
12090 
12091   OS << "Loop ";
12092   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12093   OS << ": ";
12094 
12095   SmallVector<BasicBlock *, 8> ExitingBlocks;
12096   L->getExitingBlocks(ExitingBlocks);
12097   if (ExitingBlocks.size() != 1)
12098     OS << "<multiple exits> ";
12099 
12100   if (SE->hasLoopInvariantBackedgeTakenCount(L))
12101     OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L) << "\n";
12102   else
12103     OS << "Unpredictable backedge-taken count.\n";
12104 
12105   if (ExitingBlocks.size() > 1)
12106     for (BasicBlock *ExitingBlock : ExitingBlocks) {
12107       OS << "  exit count for " << ExitingBlock->getName() << ": "
12108          << *SE->getExitCount(L, ExitingBlock) << "\n";
12109     }
12110 
12111   OS << "Loop ";
12112   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12113   OS << ": ";
12114 
12115   if (!isa<SCEVCouldNotCompute>(SE->getConstantMaxBackedgeTakenCount(L))) {
12116     OS << "max backedge-taken count is " << *SE->getConstantMaxBackedgeTakenCount(L);
12117     if (SE->isBackedgeTakenCountMaxOrZero(L))
12118       OS << ", actual taken count either this or zero.";
12119   } else {
12120     OS << "Unpredictable max backedge-taken count. ";
12121   }
12122 
12123   OS << "\n"
12124         "Loop ";
12125   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12126   OS << ": ";
12127 
12128   SCEVUnionPredicate Pred;
12129   auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred);
12130   if (!isa<SCEVCouldNotCompute>(PBT)) {
12131     OS << "Predicated backedge-taken count is " << *PBT << "\n";
12132     OS << " Predicates:\n";
12133     Pred.print(OS, 4);
12134   } else {
12135     OS << "Unpredictable predicated backedge-taken count. ";
12136   }
12137   OS << "\n";
12138 
12139   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
12140     OS << "Loop ";
12141     L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12142     OS << ": ";
12143     OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
12144   }
12145 }
12146 
12147 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) {
12148   switch (LD) {
12149   case ScalarEvolution::LoopVariant:
12150     return "Variant";
12151   case ScalarEvolution::LoopInvariant:
12152     return "Invariant";
12153   case ScalarEvolution::LoopComputable:
12154     return "Computable";
12155   }
12156   llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!");
12157 }
12158 
12159 void ScalarEvolution::print(raw_ostream &OS) const {
12160   // ScalarEvolution's implementation of the print method is to print
12161   // out SCEV values of all instructions that are interesting. Doing
12162   // this potentially causes it to create new SCEV objects though,
12163   // which technically conflicts with the const qualifier. This isn't
12164   // observable from outside the class though, so casting away the
12165   // const isn't dangerous.
12166   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
12167 
12168   if (ClassifyExpressions) {
12169     OS << "Classifying expressions for: ";
12170     F.printAsOperand(OS, /*PrintType=*/false);
12171     OS << "\n";
12172     for (Instruction &I : instructions(F))
12173       if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
12174         OS << I << '\n';
12175         OS << "  -->  ";
12176         const SCEV *SV = SE.getSCEV(&I);
12177         SV->print(OS);
12178         if (!isa<SCEVCouldNotCompute>(SV)) {
12179           OS << " U: ";
12180           SE.getUnsignedRange(SV).print(OS);
12181           OS << " S: ";
12182           SE.getSignedRange(SV).print(OS);
12183         }
12184 
12185         const Loop *L = LI.getLoopFor(I.getParent());
12186 
12187         const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
12188         if (AtUse != SV) {
12189           OS << "  -->  ";
12190           AtUse->print(OS);
12191           if (!isa<SCEVCouldNotCompute>(AtUse)) {
12192             OS << " U: ";
12193             SE.getUnsignedRange(AtUse).print(OS);
12194             OS << " S: ";
12195             SE.getSignedRange(AtUse).print(OS);
12196           }
12197         }
12198 
12199         if (L) {
12200           OS << "\t\t" "Exits: ";
12201           const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
12202           if (!SE.isLoopInvariant(ExitValue, L)) {
12203             OS << "<<Unknown>>";
12204           } else {
12205             OS << *ExitValue;
12206           }
12207 
12208           bool First = true;
12209           for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
12210             if (First) {
12211               OS << "\t\t" "LoopDispositions: { ";
12212               First = false;
12213             } else {
12214               OS << ", ";
12215             }
12216 
12217             Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12218             OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter));
12219           }
12220 
12221           for (auto *InnerL : depth_first(L)) {
12222             if (InnerL == L)
12223               continue;
12224             if (First) {
12225               OS << "\t\t" "LoopDispositions: { ";
12226               First = false;
12227             } else {
12228               OS << ", ";
12229             }
12230 
12231             InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12232             OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL));
12233           }
12234 
12235           OS << " }";
12236         }
12237 
12238         OS << "\n";
12239       }
12240   }
12241 
12242   OS << "Determining loop execution counts for: ";
12243   F.printAsOperand(OS, /*PrintType=*/false);
12244   OS << "\n";
12245   for (Loop *I : LI)
12246     PrintLoopInfo(OS, &SE, I);
12247 }
12248 
12249 ScalarEvolution::LoopDisposition
12250 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
12251   auto &Values = LoopDispositions[S];
12252   for (auto &V : Values) {
12253     if (V.getPointer() == L)
12254       return V.getInt();
12255   }
12256   Values.emplace_back(L, LoopVariant);
12257   LoopDisposition D = computeLoopDisposition(S, L);
12258   auto &Values2 = LoopDispositions[S];
12259   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
12260     if (V.getPointer() == L) {
12261       V.setInt(D);
12262       break;
12263     }
12264   }
12265   return D;
12266 }
12267 
12268 ScalarEvolution::LoopDisposition
12269 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
12270   switch (S->getSCEVType()) {
12271   case scConstant:
12272     return LoopInvariant;
12273   case scPtrToInt:
12274   case scTruncate:
12275   case scZeroExtend:
12276   case scSignExtend:
12277     return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
12278   case scAddRecExpr: {
12279     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
12280 
12281     // If L is the addrec's loop, it's computable.
12282     if (AR->getLoop() == L)
12283       return LoopComputable;
12284 
12285     // Add recurrences are never invariant in the function-body (null loop).
12286     if (!L)
12287       return LoopVariant;
12288 
12289     // Everything that is not defined at loop entry is variant.
12290     if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader()))
12291       return LoopVariant;
12292     assert(!L->contains(AR->getLoop()) && "Containing loop's header does not"
12293            " dominate the contained loop's header?");
12294 
12295     // This recurrence is invariant w.r.t. L if AR's loop contains L.
12296     if (AR->getLoop()->contains(L))
12297       return LoopInvariant;
12298 
12299     // This recurrence is variant w.r.t. L if any of its operands
12300     // are variant.
12301     for (auto *Op : AR->operands())
12302       if (!isLoopInvariant(Op, L))
12303         return LoopVariant;
12304 
12305     // Otherwise it's loop-invariant.
12306     return LoopInvariant;
12307   }
12308   case scAddExpr:
12309   case scMulExpr:
12310   case scUMaxExpr:
12311   case scSMaxExpr:
12312   case scUMinExpr:
12313   case scSMinExpr: {
12314     bool HasVarying = false;
12315     for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) {
12316       LoopDisposition D = getLoopDisposition(Op, L);
12317       if (D == LoopVariant)
12318         return LoopVariant;
12319       if (D == LoopComputable)
12320         HasVarying = true;
12321     }
12322     return HasVarying ? LoopComputable : LoopInvariant;
12323   }
12324   case scUDivExpr: {
12325     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
12326     LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
12327     if (LD == LoopVariant)
12328       return LoopVariant;
12329     LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
12330     if (RD == LoopVariant)
12331       return LoopVariant;
12332     return (LD == LoopInvariant && RD == LoopInvariant) ?
12333            LoopInvariant : LoopComputable;
12334   }
12335   case scUnknown:
12336     // All non-instruction values are loop invariant.  All instructions are loop
12337     // invariant if they are not contained in the specified loop.
12338     // Instructions are never considered invariant in the function body
12339     // (null loop) because they are defined within the "loop".
12340     if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
12341       return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
12342     return LoopInvariant;
12343   case scCouldNotCompute:
12344     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
12345   }
12346   llvm_unreachable("Unknown SCEV kind!");
12347 }
12348 
12349 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
12350   return getLoopDisposition(S, L) == LoopInvariant;
12351 }
12352 
12353 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
12354   return getLoopDisposition(S, L) == LoopComputable;
12355 }
12356 
12357 ScalarEvolution::BlockDisposition
12358 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
12359   auto &Values = BlockDispositions[S];
12360   for (auto &V : Values) {
12361     if (V.getPointer() == BB)
12362       return V.getInt();
12363   }
12364   Values.emplace_back(BB, DoesNotDominateBlock);
12365   BlockDisposition D = computeBlockDisposition(S, BB);
12366   auto &Values2 = BlockDispositions[S];
12367   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
12368     if (V.getPointer() == BB) {
12369       V.setInt(D);
12370       break;
12371     }
12372   }
12373   return D;
12374 }
12375 
12376 ScalarEvolution::BlockDisposition
12377 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
12378   switch (S->getSCEVType()) {
12379   case scConstant:
12380     return ProperlyDominatesBlock;
12381   case scPtrToInt:
12382   case scTruncate:
12383   case scZeroExtend:
12384   case scSignExtend:
12385     return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
12386   case scAddRecExpr: {
12387     // This uses a "dominates" query instead of "properly dominates" query
12388     // to test for proper dominance too, because the instruction which
12389     // produces the addrec's value is a PHI, and a PHI effectively properly
12390     // dominates its entire containing block.
12391     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
12392     if (!DT.dominates(AR->getLoop()->getHeader(), BB))
12393       return DoesNotDominateBlock;
12394 
12395     // Fall through into SCEVNAryExpr handling.
12396     LLVM_FALLTHROUGH;
12397   }
12398   case scAddExpr:
12399   case scMulExpr:
12400   case scUMaxExpr:
12401   case scSMaxExpr:
12402   case scUMinExpr:
12403   case scSMinExpr: {
12404     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
12405     bool Proper = true;
12406     for (const SCEV *NAryOp : NAry->operands()) {
12407       BlockDisposition D = getBlockDisposition(NAryOp, BB);
12408       if (D == DoesNotDominateBlock)
12409         return DoesNotDominateBlock;
12410       if (D == DominatesBlock)
12411         Proper = false;
12412     }
12413     return Proper ? ProperlyDominatesBlock : DominatesBlock;
12414   }
12415   case scUDivExpr: {
12416     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
12417     const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
12418     BlockDisposition LD = getBlockDisposition(LHS, BB);
12419     if (LD == DoesNotDominateBlock)
12420       return DoesNotDominateBlock;
12421     BlockDisposition RD = getBlockDisposition(RHS, BB);
12422     if (RD == DoesNotDominateBlock)
12423       return DoesNotDominateBlock;
12424     return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
12425       ProperlyDominatesBlock : DominatesBlock;
12426   }
12427   case scUnknown:
12428     if (Instruction *I =
12429           dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
12430       if (I->getParent() == BB)
12431         return DominatesBlock;
12432       if (DT.properlyDominates(I->getParent(), BB))
12433         return ProperlyDominatesBlock;
12434       return DoesNotDominateBlock;
12435     }
12436     return ProperlyDominatesBlock;
12437   case scCouldNotCompute:
12438     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
12439   }
12440   llvm_unreachable("Unknown SCEV kind!");
12441 }
12442 
12443 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
12444   return getBlockDisposition(S, BB) >= DominatesBlock;
12445 }
12446 
12447 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
12448   return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
12449 }
12450 
12451 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
12452   return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; });
12453 }
12454 
12455 bool ScalarEvolution::ExitLimit::hasOperand(const SCEV *S) const {
12456   auto IsS = [&](const SCEV *X) { return S == X; };
12457   auto ContainsS = [&](const SCEV *X) {
12458     return !isa<SCEVCouldNotCompute>(X) && SCEVExprContains(X, IsS);
12459   };
12460   return ContainsS(ExactNotTaken) || ContainsS(MaxNotTaken);
12461 }
12462 
12463 void
12464 ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
12465   ValuesAtScopes.erase(S);
12466   LoopDispositions.erase(S);
12467   BlockDispositions.erase(S);
12468   UnsignedRanges.erase(S);
12469   SignedRanges.erase(S);
12470   ExprValueMap.erase(S);
12471   HasRecMap.erase(S);
12472   MinTrailingZerosCache.erase(S);
12473 
12474   for (auto I = PredicatedSCEVRewrites.begin();
12475        I != PredicatedSCEVRewrites.end();) {
12476     std::pair<const SCEV *, const Loop *> Entry = I->first;
12477     if (Entry.first == S)
12478       PredicatedSCEVRewrites.erase(I++);
12479     else
12480       ++I;
12481   }
12482 
12483   auto RemoveSCEVFromBackedgeMap =
12484       [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
12485         for (auto I = Map.begin(), E = Map.end(); I != E;) {
12486           BackedgeTakenInfo &BEInfo = I->second;
12487           if (BEInfo.hasOperand(S, this)) {
12488             BEInfo.clear();
12489             Map.erase(I++);
12490           } else
12491             ++I;
12492         }
12493       };
12494 
12495   RemoveSCEVFromBackedgeMap(BackedgeTakenCounts);
12496   RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts);
12497 }
12498 
12499 void
12500 ScalarEvolution::getUsedLoops(const SCEV *S,
12501                               SmallPtrSetImpl<const Loop *> &LoopsUsed) {
12502   struct FindUsedLoops {
12503     FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed)
12504         : LoopsUsed(LoopsUsed) {}
12505     SmallPtrSetImpl<const Loop *> &LoopsUsed;
12506     bool follow(const SCEV *S) {
12507       if (auto *AR = dyn_cast<SCEVAddRecExpr>(S))
12508         LoopsUsed.insert(AR->getLoop());
12509       return true;
12510     }
12511 
12512     bool isDone() const { return false; }
12513   };
12514 
12515   FindUsedLoops F(LoopsUsed);
12516   SCEVTraversal<FindUsedLoops>(F).visitAll(S);
12517 }
12518 
12519 void ScalarEvolution::addToLoopUseLists(const SCEV *S) {
12520   SmallPtrSet<const Loop *, 8> LoopsUsed;
12521   getUsedLoops(S, LoopsUsed);
12522   for (auto *L : LoopsUsed)
12523     LoopUsers[L].push_back(S);
12524 }
12525 
12526 void ScalarEvolution::verify() const {
12527   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
12528   ScalarEvolution SE2(F, TLI, AC, DT, LI);
12529 
12530   SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end());
12531 
12532   // Map's SCEV expressions from one ScalarEvolution "universe" to another.
12533   struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> {
12534     SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {}
12535 
12536     const SCEV *visitConstant(const SCEVConstant *Constant) {
12537       return SE.getConstant(Constant->getAPInt());
12538     }
12539 
12540     const SCEV *visitUnknown(const SCEVUnknown *Expr) {
12541       return SE.getUnknown(Expr->getValue());
12542     }
12543 
12544     const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
12545       return SE.getCouldNotCompute();
12546     }
12547   };
12548 
12549   SCEVMapper SCM(SE2);
12550 
12551   while (!LoopStack.empty()) {
12552     auto *L = LoopStack.pop_back_val();
12553     llvm::append_range(LoopStack, *L);
12554 
12555     auto *CurBECount = SCM.visit(
12556         const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L));
12557     auto *NewBECount = SE2.getBackedgeTakenCount(L);
12558 
12559     if (CurBECount == SE2.getCouldNotCompute() ||
12560         NewBECount == SE2.getCouldNotCompute()) {
12561       // NB! This situation is legal, but is very suspicious -- whatever pass
12562       // change the loop to make a trip count go from could not compute to
12563       // computable or vice-versa *should have* invalidated SCEV.  However, we
12564       // choose not to assert here (for now) since we don't want false
12565       // positives.
12566       continue;
12567     }
12568 
12569     if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) {
12570       // SCEV treats "undef" as an unknown but consistent value (i.e. it does
12571       // not propagate undef aggressively).  This means we can (and do) fail
12572       // verification in cases where a transform makes the trip count of a loop
12573       // go from "undef" to "undef+1" (say).  The transform is fine, since in
12574       // both cases the loop iterates "undef" times, but SCEV thinks we
12575       // increased the trip count of the loop by 1 incorrectly.
12576       continue;
12577     }
12578 
12579     if (SE.getTypeSizeInBits(CurBECount->getType()) >
12580         SE.getTypeSizeInBits(NewBECount->getType()))
12581       NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType());
12582     else if (SE.getTypeSizeInBits(CurBECount->getType()) <
12583              SE.getTypeSizeInBits(NewBECount->getType()))
12584       CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType());
12585 
12586     const SCEV *Delta = SE2.getMinusSCEV(CurBECount, NewBECount);
12587 
12588     // Unless VerifySCEVStrict is set, we only compare constant deltas.
12589     if ((VerifySCEVStrict || isa<SCEVConstant>(Delta)) && !Delta->isZero()) {
12590       dbgs() << "Trip Count for " << *L << " Changed!\n";
12591       dbgs() << "Old: " << *CurBECount << "\n";
12592       dbgs() << "New: " << *NewBECount << "\n";
12593       dbgs() << "Delta: " << *Delta << "\n";
12594       std::abort();
12595     }
12596   }
12597 
12598   // Collect all valid loops currently in LoopInfo.
12599   SmallPtrSet<Loop *, 32> ValidLoops;
12600   SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end());
12601   while (!Worklist.empty()) {
12602     Loop *L = Worklist.pop_back_val();
12603     if (ValidLoops.contains(L))
12604       continue;
12605     ValidLoops.insert(L);
12606     Worklist.append(L->begin(), L->end());
12607   }
12608   // Check for SCEV expressions referencing invalid/deleted loops.
12609   for (auto &KV : ValueExprMap) {
12610     auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second);
12611     if (!AR)
12612       continue;
12613     assert(ValidLoops.contains(AR->getLoop()) &&
12614            "AddRec references invalid loop");
12615   }
12616 }
12617 
12618 bool ScalarEvolution::invalidate(
12619     Function &F, const PreservedAnalyses &PA,
12620     FunctionAnalysisManager::Invalidator &Inv) {
12621   // Invalidate the ScalarEvolution object whenever it isn't preserved or one
12622   // of its dependencies is invalidated.
12623   auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
12624   return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
12625          Inv.invalidate<AssumptionAnalysis>(F, PA) ||
12626          Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
12627          Inv.invalidate<LoopAnalysis>(F, PA);
12628 }
12629 
12630 AnalysisKey ScalarEvolutionAnalysis::Key;
12631 
12632 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
12633                                              FunctionAnalysisManager &AM) {
12634   return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F),
12635                          AM.getResult<AssumptionAnalysis>(F),
12636                          AM.getResult<DominatorTreeAnalysis>(F),
12637                          AM.getResult<LoopAnalysis>(F));
12638 }
12639 
12640 PreservedAnalyses
12641 ScalarEvolutionVerifierPass::run(Function &F, FunctionAnalysisManager &AM) {
12642   AM.getResult<ScalarEvolutionAnalysis>(F).verify();
12643   return PreservedAnalyses::all();
12644 }
12645 
12646 PreservedAnalyses
12647 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
12648   // For compatibility with opt's -analyze feature under legacy pass manager
12649   // which was not ported to NPM. This keeps tests using
12650   // update_analyze_test_checks.py working.
12651   OS << "Printing analysis 'Scalar Evolution Analysis' for function '"
12652      << F.getName() << "':\n";
12653   AM.getResult<ScalarEvolutionAnalysis>(F).print(OS);
12654   return PreservedAnalyses::all();
12655 }
12656 
12657 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
12658                       "Scalar Evolution Analysis", false, true)
12659 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
12660 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
12661 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
12662 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
12663 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
12664                     "Scalar Evolution Analysis", false, true)
12665 
12666 char ScalarEvolutionWrapperPass::ID = 0;
12667 
12668 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
12669   initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
12670 }
12671 
12672 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
12673   SE.reset(new ScalarEvolution(
12674       F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F),
12675       getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
12676       getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
12677       getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
12678   return false;
12679 }
12680 
12681 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
12682 
12683 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
12684   SE->print(OS);
12685 }
12686 
12687 void ScalarEvolutionWrapperPass::verifyAnalysis() const {
12688   if (!VerifySCEV)
12689     return;
12690 
12691   SE->verify();
12692 }
12693 
12694 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
12695   AU.setPreservesAll();
12696   AU.addRequiredTransitive<AssumptionCacheTracker>();
12697   AU.addRequiredTransitive<LoopInfoWrapperPass>();
12698   AU.addRequiredTransitive<DominatorTreeWrapperPass>();
12699   AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
12700 }
12701 
12702 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS,
12703                                                         const SCEV *RHS) {
12704   FoldingSetNodeID ID;
12705   assert(LHS->getType() == RHS->getType() &&
12706          "Type mismatch between LHS and RHS");
12707   // Unique this node based on the arguments
12708   ID.AddInteger(SCEVPredicate::P_Equal);
12709   ID.AddPointer(LHS);
12710   ID.AddPointer(RHS);
12711   void *IP = nullptr;
12712   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
12713     return S;
12714   SCEVEqualPredicate *Eq = new (SCEVAllocator)
12715       SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS);
12716   UniquePreds.InsertNode(Eq, IP);
12717   return Eq;
12718 }
12719 
12720 const SCEVPredicate *ScalarEvolution::getWrapPredicate(
12721     const SCEVAddRecExpr *AR,
12722     SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
12723   FoldingSetNodeID ID;
12724   // Unique this node based on the arguments
12725   ID.AddInteger(SCEVPredicate::P_Wrap);
12726   ID.AddPointer(AR);
12727   ID.AddInteger(AddedFlags);
12728   void *IP = nullptr;
12729   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
12730     return S;
12731   auto *OF = new (SCEVAllocator)
12732       SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
12733   UniquePreds.InsertNode(OF, IP);
12734   return OF;
12735 }
12736 
12737 namespace {
12738 
12739 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
12740 public:
12741 
12742   /// Rewrites \p S in the context of a loop L and the SCEV predication
12743   /// infrastructure.
12744   ///
12745   /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
12746   /// equivalences present in \p Pred.
12747   ///
12748   /// If \p NewPreds is non-null, rewrite is free to add further predicates to
12749   /// \p NewPreds such that the result will be an AddRecExpr.
12750   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
12751                              SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
12752                              SCEVUnionPredicate *Pred) {
12753     SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
12754     return Rewriter.visit(S);
12755   }
12756 
12757   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
12758     if (Pred) {
12759       auto ExprPreds = Pred->getPredicatesForExpr(Expr);
12760       for (auto *Pred : ExprPreds)
12761         if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred))
12762           if (IPred->getLHS() == Expr)
12763             return IPred->getRHS();
12764     }
12765     return convertToAddRecWithPreds(Expr);
12766   }
12767 
12768   const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
12769     const SCEV *Operand = visit(Expr->getOperand());
12770     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
12771     if (AR && AR->getLoop() == L && AR->isAffine()) {
12772       // This couldn't be folded because the operand didn't have the nuw
12773       // flag. Add the nusw flag as an assumption that we could make.
12774       const SCEV *Step = AR->getStepRecurrence(SE);
12775       Type *Ty = Expr->getType();
12776       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
12777         return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
12778                                 SE.getSignExtendExpr(Step, Ty), L,
12779                                 AR->getNoWrapFlags());
12780     }
12781     return SE.getZeroExtendExpr(Operand, Expr->getType());
12782   }
12783 
12784   const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
12785     const SCEV *Operand = visit(Expr->getOperand());
12786     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
12787     if (AR && AR->getLoop() == L && AR->isAffine()) {
12788       // This couldn't be folded because the operand didn't have the nsw
12789       // flag. Add the nssw flag as an assumption that we could make.
12790       const SCEV *Step = AR->getStepRecurrence(SE);
12791       Type *Ty = Expr->getType();
12792       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
12793         return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
12794                                 SE.getSignExtendExpr(Step, Ty), L,
12795                                 AR->getNoWrapFlags());
12796     }
12797     return SE.getSignExtendExpr(Operand, Expr->getType());
12798   }
12799 
12800 private:
12801   explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE,
12802                         SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
12803                         SCEVUnionPredicate *Pred)
12804       : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
12805 
12806   bool addOverflowAssumption(const SCEVPredicate *P) {
12807     if (!NewPreds) {
12808       // Check if we've already made this assumption.
12809       return Pred && Pred->implies(P);
12810     }
12811     NewPreds->insert(P);
12812     return true;
12813   }
12814 
12815   bool addOverflowAssumption(const SCEVAddRecExpr *AR,
12816                              SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
12817     auto *A = SE.getWrapPredicate(AR, AddedFlags);
12818     return addOverflowAssumption(A);
12819   }
12820 
12821   // If \p Expr represents a PHINode, we try to see if it can be represented
12822   // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible
12823   // to add this predicate as a runtime overflow check, we return the AddRec.
12824   // If \p Expr does not meet these conditions (is not a PHI node, or we
12825   // couldn't create an AddRec for it, or couldn't add the predicate), we just
12826   // return \p Expr.
12827   const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) {
12828     if (!isa<PHINode>(Expr->getValue()))
12829       return Expr;
12830     Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
12831     PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr);
12832     if (!PredicatedRewrite)
12833       return Expr;
12834     for (auto *P : PredicatedRewrite->second){
12835       // Wrap predicates from outer loops are not supported.
12836       if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) {
12837         auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr());
12838         if (L != AR->getLoop())
12839           return Expr;
12840       }
12841       if (!addOverflowAssumption(P))
12842         return Expr;
12843     }
12844     return PredicatedRewrite->first;
12845   }
12846 
12847   SmallPtrSetImpl<const SCEVPredicate *> *NewPreds;
12848   SCEVUnionPredicate *Pred;
12849   const Loop *L;
12850 };
12851 
12852 } // end anonymous namespace
12853 
12854 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
12855                                                    SCEVUnionPredicate &Preds) {
12856   return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
12857 }
12858 
12859 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates(
12860     const SCEV *S, const Loop *L,
12861     SmallPtrSetImpl<const SCEVPredicate *> &Preds) {
12862   SmallPtrSet<const SCEVPredicate *, 4> TransformPreds;
12863   S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
12864   auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
12865 
12866   if (!AddRec)
12867     return nullptr;
12868 
12869   // Since the transformation was successful, we can now transfer the SCEV
12870   // predicates.
12871   for (auto *P : TransformPreds)
12872     Preds.insert(P);
12873 
12874   return AddRec;
12875 }
12876 
12877 /// SCEV predicates
12878 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
12879                              SCEVPredicateKind Kind)
12880     : FastID(ID), Kind(Kind) {}
12881 
12882 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID,
12883                                        const SCEV *LHS, const SCEV *RHS)
12884     : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {
12885   assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match");
12886   assert(LHS != RHS && "LHS and RHS are the same SCEV");
12887 }
12888 
12889 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const {
12890   const auto *Op = dyn_cast<SCEVEqualPredicate>(N);
12891 
12892   if (!Op)
12893     return false;
12894 
12895   return Op->LHS == LHS && Op->RHS == RHS;
12896 }
12897 
12898 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; }
12899 
12900 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; }
12901 
12902 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const {
12903   OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
12904 }
12905 
12906 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
12907                                      const SCEVAddRecExpr *AR,
12908                                      IncrementWrapFlags Flags)
12909     : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
12910 
12911 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; }
12912 
12913 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const {
12914   const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
12915 
12916   return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags;
12917 }
12918 
12919 bool SCEVWrapPredicate::isAlwaysTrue() const {
12920   SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
12921   IncrementWrapFlags IFlags = Flags;
12922 
12923   if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
12924     IFlags = clearFlags(IFlags, IncrementNSSW);
12925 
12926   return IFlags == IncrementAnyWrap;
12927 }
12928 
12929 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
12930   OS.indent(Depth) << *getExpr() << " Added Flags: ";
12931   if (SCEVWrapPredicate::IncrementNUSW & getFlags())
12932     OS << "<nusw>";
12933   if (SCEVWrapPredicate::IncrementNSSW & getFlags())
12934     OS << "<nssw>";
12935   OS << "\n";
12936 }
12937 
12938 SCEVWrapPredicate::IncrementWrapFlags
12939 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR,
12940                                    ScalarEvolution &SE) {
12941   IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
12942   SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
12943 
12944   // We can safely transfer the NSW flag as NSSW.
12945   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
12946     ImpliedFlags = IncrementNSSW;
12947 
12948   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
12949     // If the increment is positive, the SCEV NUW flag will also imply the
12950     // WrapPredicate NUSW flag.
12951     if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
12952       if (Step->getValue()->getValue().isNonNegative())
12953         ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
12954   }
12955 
12956   return ImpliedFlags;
12957 }
12958 
12959 /// Union predicates don't get cached so create a dummy set ID for it.
12960 SCEVUnionPredicate::SCEVUnionPredicate()
12961     : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {}
12962 
12963 bool SCEVUnionPredicate::isAlwaysTrue() const {
12964   return all_of(Preds,
12965                 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
12966 }
12967 
12968 ArrayRef<const SCEVPredicate *>
12969 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) {
12970   auto I = SCEVToPreds.find(Expr);
12971   if (I == SCEVToPreds.end())
12972     return ArrayRef<const SCEVPredicate *>();
12973   return I->second;
12974 }
12975 
12976 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
12977   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
12978     return all_of(Set->Preds,
12979                   [this](const SCEVPredicate *I) { return this->implies(I); });
12980 
12981   auto ScevPredsIt = SCEVToPreds.find(N->getExpr());
12982   if (ScevPredsIt == SCEVToPreds.end())
12983     return false;
12984   auto &SCEVPreds = ScevPredsIt->second;
12985 
12986   return any_of(SCEVPreds,
12987                 [N](const SCEVPredicate *I) { return I->implies(N); });
12988 }
12989 
12990 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; }
12991 
12992 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
12993   for (auto Pred : Preds)
12994     Pred->print(OS, Depth);
12995 }
12996 
12997 void SCEVUnionPredicate::add(const SCEVPredicate *N) {
12998   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
12999     for (auto Pred : Set->Preds)
13000       add(Pred);
13001     return;
13002   }
13003 
13004   if (implies(N))
13005     return;
13006 
13007   const SCEV *Key = N->getExpr();
13008   assert(Key && "Only SCEVUnionPredicate doesn't have an "
13009                 " associated expression!");
13010 
13011   SCEVToPreds[Key].push_back(N);
13012   Preds.push_back(N);
13013 }
13014 
13015 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
13016                                                      Loop &L)
13017     : SE(SE), L(L) {}
13018 
13019 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
13020   const SCEV *Expr = SE.getSCEV(V);
13021   RewriteEntry &Entry = RewriteMap[Expr];
13022 
13023   // If we already have an entry and the version matches, return it.
13024   if (Entry.second && Generation == Entry.first)
13025     return Entry.second;
13026 
13027   // We found an entry but it's stale. Rewrite the stale entry
13028   // according to the current predicate.
13029   if (Entry.second)
13030     Expr = Entry.second;
13031 
13032   const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds);
13033   Entry = {Generation, NewSCEV};
13034 
13035   return NewSCEV;
13036 }
13037 
13038 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() {
13039   if (!BackedgeCount) {
13040     SCEVUnionPredicate BackedgePred;
13041     BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred);
13042     addPredicate(BackedgePred);
13043   }
13044   return BackedgeCount;
13045 }
13046 
13047 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
13048   if (Preds.implies(&Pred))
13049     return;
13050   Preds.add(&Pred);
13051   updateGeneration();
13052 }
13053 
13054 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const {
13055   return Preds;
13056 }
13057 
13058 void PredicatedScalarEvolution::updateGeneration() {
13059   // If the generation number wrapped recompute everything.
13060   if (++Generation == 0) {
13061     for (auto &II : RewriteMap) {
13062       const SCEV *Rewritten = II.second.second;
13063       II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)};
13064     }
13065   }
13066 }
13067 
13068 void PredicatedScalarEvolution::setNoOverflow(
13069     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
13070   const SCEV *Expr = getSCEV(V);
13071   const auto *AR = cast<SCEVAddRecExpr>(Expr);
13072 
13073   auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE);
13074 
13075   // Clear the statically implied flags.
13076   Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags);
13077   addPredicate(*SE.getWrapPredicate(AR, Flags));
13078 
13079   auto II = FlagsMap.insert({V, Flags});
13080   if (!II.second)
13081     II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second);
13082 }
13083 
13084 bool PredicatedScalarEvolution::hasNoOverflow(
13085     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
13086   const SCEV *Expr = getSCEV(V);
13087   const auto *AR = cast<SCEVAddRecExpr>(Expr);
13088 
13089   Flags = SCEVWrapPredicate::clearFlags(
13090       Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
13091 
13092   auto II = FlagsMap.find(V);
13093 
13094   if (II != FlagsMap.end())
13095     Flags = SCEVWrapPredicate::clearFlags(Flags, II->second);
13096 
13097   return Flags == SCEVWrapPredicate::IncrementAnyWrap;
13098 }
13099 
13100 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) {
13101   const SCEV *Expr = this->getSCEV(V);
13102   SmallPtrSet<const SCEVPredicate *, 4> NewPreds;
13103   auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
13104 
13105   if (!New)
13106     return nullptr;
13107 
13108   for (auto *P : NewPreds)
13109     Preds.add(P);
13110 
13111   updateGeneration();
13112   RewriteMap[SE.getSCEV(V)] = {Generation, New};
13113   return New;
13114 }
13115 
13116 PredicatedScalarEvolution::PredicatedScalarEvolution(
13117     const PredicatedScalarEvolution &Init)
13118     : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds),
13119       Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
13120   for (auto I : Init.FlagsMap)
13121     FlagsMap.insert(I);
13122 }
13123 
13124 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const {
13125   // For each block.
13126   for (auto *BB : L.getBlocks())
13127     for (auto &I : *BB) {
13128       if (!SE.isSCEVable(I.getType()))
13129         continue;
13130 
13131       auto *Expr = SE.getSCEV(&I);
13132       auto II = RewriteMap.find(Expr);
13133 
13134       if (II == RewriteMap.end())
13135         continue;
13136 
13137       // Don't print things that are not interesting.
13138       if (II->second.second == Expr)
13139         continue;
13140 
13141       OS.indent(Depth) << "[PSE]" << I << ":\n";
13142       OS.indent(Depth + 2) << *Expr << "\n";
13143       OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
13144     }
13145 }
13146 
13147 // Match the mathematical pattern A - (A / B) * B, where A and B can be
13148 // arbitrary expressions. Also match zext (trunc A to iB) to iY, which is used
13149 // for URem with constant power-of-2 second operands.
13150 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is
13151 // 4, A / B becomes X / 8).
13152 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS,
13153                                 const SCEV *&RHS) {
13154   // Try to match 'zext (trunc A to iB) to iY', which is used
13155   // for URem with constant power-of-2 second operands. Make sure the size of
13156   // the operand A matches the size of the whole expressions.
13157   if (const auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(Expr))
13158     if (const auto *Trunc = dyn_cast<SCEVTruncateExpr>(ZExt->getOperand(0))) {
13159       LHS = Trunc->getOperand();
13160       // Bail out if the type of the LHS is larger than the type of the
13161       // expression for now.
13162       if (getTypeSizeInBits(LHS->getType()) >
13163           getTypeSizeInBits(Expr->getType()))
13164         return false;
13165       if (LHS->getType() != Expr->getType())
13166         LHS = getZeroExtendExpr(LHS, Expr->getType());
13167       RHS = getConstant(APInt(getTypeSizeInBits(Expr->getType()), 1)
13168                         << getTypeSizeInBits(Trunc->getType()));
13169       return true;
13170     }
13171   const auto *Add = dyn_cast<SCEVAddExpr>(Expr);
13172   if (Add == nullptr || Add->getNumOperands() != 2)
13173     return false;
13174 
13175   const SCEV *A = Add->getOperand(1);
13176   const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0));
13177 
13178   if (Mul == nullptr)
13179     return false;
13180 
13181   const auto MatchURemWithDivisor = [&](const SCEV *B) {
13182     // (SomeExpr + (-(SomeExpr / B) * B)).
13183     if (Expr == getURemExpr(A, B)) {
13184       LHS = A;
13185       RHS = B;
13186       return true;
13187     }
13188     return false;
13189   };
13190 
13191   // (SomeExpr + (-1 * (SomeExpr / B) * B)).
13192   if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0)))
13193     return MatchURemWithDivisor(Mul->getOperand(1)) ||
13194            MatchURemWithDivisor(Mul->getOperand(2));
13195 
13196   // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)).
13197   if (Mul->getNumOperands() == 2)
13198     return MatchURemWithDivisor(Mul->getOperand(1)) ||
13199            MatchURemWithDivisor(Mul->getOperand(0)) ||
13200            MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) ||
13201            MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0)));
13202   return false;
13203 }
13204 
13205 const SCEV *
13206 ScalarEvolution::computeSymbolicMaxBackedgeTakenCount(const Loop *L) {
13207   SmallVector<BasicBlock*, 16> ExitingBlocks;
13208   L->getExitingBlocks(ExitingBlocks);
13209 
13210   // Form an expression for the maximum exit count possible for this loop. We
13211   // merge the max and exact information to approximate a version of
13212   // getConstantMaxBackedgeTakenCount which isn't restricted to just constants.
13213   SmallVector<const SCEV*, 4> ExitCounts;
13214   for (BasicBlock *ExitingBB : ExitingBlocks) {
13215     const SCEV *ExitCount = getExitCount(L, ExitingBB);
13216     if (isa<SCEVCouldNotCompute>(ExitCount))
13217       ExitCount = getExitCount(L, ExitingBB,
13218                                   ScalarEvolution::ConstantMaximum);
13219     if (!isa<SCEVCouldNotCompute>(ExitCount)) {
13220       assert(DT.dominates(ExitingBB, L->getLoopLatch()) &&
13221              "We should only have known counts for exiting blocks that "
13222              "dominate latch!");
13223       ExitCounts.push_back(ExitCount);
13224     }
13225   }
13226   if (ExitCounts.empty())
13227     return getCouldNotCompute();
13228   return getUMinFromMismatchedTypes(ExitCounts);
13229 }
13230 
13231 /// This rewriter is similar to SCEVParameterRewriter (it replaces SCEVUnknown
13232 /// components following the Map (Value -> SCEV)), but skips AddRecExpr because
13233 /// we cannot guarantee that the replacement is loop invariant in the loop of
13234 /// the AddRec.
13235 class SCEVLoopGuardRewriter : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> {
13236   ValueToSCEVMapTy &Map;
13237 
13238 public:
13239   SCEVLoopGuardRewriter(ScalarEvolution &SE, ValueToSCEVMapTy &M)
13240       : SCEVRewriteVisitor(SE), Map(M) {}
13241 
13242   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; }
13243 
13244   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
13245     auto I = Map.find(Expr->getValue());
13246     if (I == Map.end())
13247       return Expr;
13248     return I->second;
13249   }
13250 };
13251 
13252 const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) {
13253   auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS,
13254                               const SCEV *RHS, ValueToSCEVMapTy &RewriteMap) {
13255     // If we have LHS == 0, check if LHS is computing a property of some unknown
13256     // SCEV %v which we can rewrite %v to express explicitly.
13257     const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS);
13258     if (Predicate == CmpInst::ICMP_EQ && RHSC &&
13259         RHSC->getValue()->isNullValue()) {
13260       // If LHS is A % B, i.e. A % B == 0, rewrite A to (A /u B) * B to
13261       // explicitly express that.
13262       const SCEV *URemLHS = nullptr;
13263       const SCEV *URemRHS = nullptr;
13264       if (matchURem(LHS, URemLHS, URemRHS)) {
13265         if (const SCEVUnknown *LHSUnknown = dyn_cast<SCEVUnknown>(URemLHS)) {
13266           Value *V = LHSUnknown->getValue();
13267           auto Multiple =
13268               getMulExpr(getUDivExpr(URemLHS, URemRHS), URemRHS,
13269                          (SCEV::NoWrapFlags)(SCEV::FlagNUW | SCEV::FlagNSW));
13270           RewriteMap[V] = Multiple;
13271           return;
13272         }
13273       }
13274     }
13275 
13276     if (!isa<SCEVUnknown>(LHS)) {
13277       std::swap(LHS, RHS);
13278       Predicate = CmpInst::getSwappedPredicate(Predicate);
13279     }
13280 
13281     // For now, limit to conditions that provide information about unknown
13282     // expressions.
13283     auto *LHSUnknown = dyn_cast<SCEVUnknown>(LHS);
13284     if (!LHSUnknown)
13285       return;
13286 
13287     // TODO: use information from more predicates.
13288     switch (Predicate) {
13289     case CmpInst::ICMP_ULT: {
13290       if (!containsAddRecurrence(RHS)) {
13291         const SCEV *Base = LHS;
13292         auto I = RewriteMap.find(LHSUnknown->getValue());
13293         if (I != RewriteMap.end())
13294           Base = I->second;
13295 
13296         RewriteMap[LHSUnknown->getValue()] =
13297             getUMinExpr(Base, getMinusSCEV(RHS, getOne(RHS->getType())));
13298       }
13299       break;
13300     }
13301     case CmpInst::ICMP_ULE: {
13302       if (!containsAddRecurrence(RHS)) {
13303         const SCEV *Base = LHS;
13304         auto I = RewriteMap.find(LHSUnknown->getValue());
13305         if (I != RewriteMap.end())
13306           Base = I->second;
13307         RewriteMap[LHSUnknown->getValue()] = getUMinExpr(Base, RHS);
13308       }
13309       break;
13310     }
13311     case CmpInst::ICMP_EQ:
13312       if (isa<SCEVConstant>(RHS))
13313         RewriteMap[LHSUnknown->getValue()] = RHS;
13314       break;
13315     case CmpInst::ICMP_NE:
13316       if (isa<SCEVConstant>(RHS) &&
13317           cast<SCEVConstant>(RHS)->getValue()->isNullValue())
13318         RewriteMap[LHSUnknown->getValue()] =
13319             getUMaxExpr(LHS, getOne(RHS->getType()));
13320       break;
13321     default:
13322       break;
13323     }
13324   };
13325   // Starting at the loop predecessor, climb up the predecessor chain, as long
13326   // as there are predecessors that can be found that have unique successors
13327   // leading to the original header.
13328   // TODO: share this logic with isLoopEntryGuardedByCond.
13329   ValueToSCEVMapTy RewriteMap;
13330   for (std::pair<const BasicBlock *, const BasicBlock *> Pair(
13331            L->getLoopPredecessor(), L->getHeader());
13332        Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
13333 
13334     const BranchInst *LoopEntryPredicate =
13335         dyn_cast<BranchInst>(Pair.first->getTerminator());
13336     if (!LoopEntryPredicate || LoopEntryPredicate->isUnconditional())
13337       continue;
13338 
13339     // TODO: use information from more complex conditions, e.g. AND expressions.
13340     auto *Cmp = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
13341     if (!Cmp)
13342       continue;
13343 
13344     auto Predicate = Cmp->getPredicate();
13345     if (LoopEntryPredicate->getSuccessor(1) == Pair.second)
13346       Predicate = CmpInst::getInversePredicate(Predicate);
13347     CollectCondition(Predicate, getSCEV(Cmp->getOperand(0)),
13348                      getSCEV(Cmp->getOperand(1)), RewriteMap);
13349   }
13350 
13351   // Also collect information from assumptions dominating the loop.
13352   for (auto &AssumeVH : AC.assumptions()) {
13353     if (!AssumeVH)
13354       continue;
13355     auto *AssumeI = cast<CallInst>(AssumeVH);
13356     auto *Cmp = dyn_cast<ICmpInst>(AssumeI->getOperand(0));
13357     if (!Cmp || !DT.dominates(AssumeI, L->getHeader()))
13358       continue;
13359     CollectCondition(Cmp->getPredicate(), getSCEV(Cmp->getOperand(0)),
13360                      getSCEV(Cmp->getOperand(1)), RewriteMap);
13361   }
13362 
13363   if (RewriteMap.empty())
13364     return Expr;
13365   SCEVLoopGuardRewriter Rewriter(*this, RewriteMap);
13366   return Rewriter.visit(Expr);
13367 }
13368