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   assert(!getDataLayout().isNonIntegralPointerType(Op->getType()) &&
1057          "Source pointer type must be integral for ptrtoint!");
1058 
1059   // What would be an ID for such a SCEV cast expression?
1060   FoldingSetNodeID ID;
1061   ID.AddInteger(scPtrToInt);
1062   ID.AddPointer(Op);
1063 
1064   void *IP = nullptr;
1065 
1066   // Is there already an expression for such a cast?
1067   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1068     return getTruncateOrZeroExtend(S, Ty);
1069 
1070   // If not, is this expression something we can't reduce any further?
1071   if (auto *U = dyn_cast<SCEVUnknown>(Op)) {
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 
1078     // Perform some basic constant folding. If the operand of the ptr2int cast
1079     // is a null pointer, don't create a ptr2int SCEV expression (that will be
1080     // left as-is), but produce a zero constant.
1081     // NOTE: We could handle a more general case, but lack motivational cases.
1082     if (isa<ConstantPointerNull>(U->getValue()))
1083       return getZero(Ty);
1084 
1085     // Create an explicit cast node.
1086     // We can reuse the existing insert position since if we get here,
1087     // we won't have made any changes which would invalidate it.
1088     SCEV *S = new (SCEVAllocator)
1089         SCEVPtrToIntExpr(ID.Intern(SCEVAllocator), Op, IntPtrTy);
1090     UniqueSCEVs.InsertNode(S, IP);
1091     addToLoopUseLists(S);
1092     return getTruncateOrZeroExtend(S, Ty);
1093   }
1094 
1095   assert(Depth == 0 &&
1096          "getPtrToIntExpr() should not self-recurse for non-SCEVUnknown's.");
1097 
1098   // Otherwise, we've got some expression that is more complex than just a
1099   // single SCEVUnknown. But we don't want to have a SCEVPtrToIntExpr of an
1100   // arbitrary expression, we want to have SCEVPtrToIntExpr of an SCEVUnknown
1101   // only, and the expressions must otherwise be integer-typed.
1102   // So sink the cast down to the SCEVUnknown's.
1103 
1104   /// The SCEVPtrToIntSinkingRewriter takes a scalar evolution expression,
1105   /// which computes a pointer-typed value, and rewrites the whole expression
1106   /// tree so that *all* the computations are done on integers, and the only
1107   /// pointer-typed operands in the expression are SCEVUnknown.
1108   class SCEVPtrToIntSinkingRewriter
1109       : public SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter> {
1110     using Base = SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter>;
1111 
1112   public:
1113     SCEVPtrToIntSinkingRewriter(ScalarEvolution &SE) : SCEVRewriteVisitor(SE) {}
1114 
1115     static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE) {
1116       SCEVPtrToIntSinkingRewriter Rewriter(SE);
1117       return Rewriter.visit(Scev);
1118     }
1119 
1120     const SCEV *visit(const SCEV *S) {
1121       Type *STy = S->getType();
1122       // If the expression is not pointer-typed, just keep it as-is.
1123       if (!STy->isPointerTy())
1124         return S;
1125       // Else, recursively sink the cast down into it.
1126       return Base::visit(S);
1127     }
1128 
1129     const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
1130       SmallVector<const SCEV *, 2> Operands;
1131       bool Changed = false;
1132       for (auto *Op : Expr->operands()) {
1133         Operands.push_back(visit(Op));
1134         Changed |= Op != Operands.back();
1135       }
1136       return !Changed ? Expr : SE.getAddExpr(Operands, Expr->getNoWrapFlags());
1137     }
1138 
1139     const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
1140       SmallVector<const SCEV *, 2> Operands;
1141       bool Changed = false;
1142       for (auto *Op : Expr->operands()) {
1143         Operands.push_back(visit(Op));
1144         Changed |= Op != Operands.back();
1145       }
1146       return !Changed ? Expr : SE.getMulExpr(Operands, Expr->getNoWrapFlags());
1147     }
1148 
1149     const SCEV *visitUnknown(const SCEVUnknown *Expr) {
1150       Type *ExprPtrTy = Expr->getType();
1151       assert(ExprPtrTy->isPointerTy() &&
1152              "Should only reach pointer-typed SCEVUnknown's.");
1153       Type *ExprIntPtrTy = SE.getDataLayout().getIntPtrType(ExprPtrTy);
1154       return SE.getPtrToIntExpr(Expr, ExprIntPtrTy, /*Depth=*/1);
1155     }
1156   };
1157 
1158   // And actually perform the cast sinking.
1159   const SCEV *IntOp = SCEVPtrToIntSinkingRewriter::rewrite(Op, *this);
1160   assert(IntOp->getType()->isIntegerTy() &&
1161          "We must have succeeded in sinking the cast, "
1162          "and ending up with an integer-typed expression!");
1163   return getTruncateOrZeroExtend(IntOp, Ty);
1164 }
1165 
1166 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, Type *Ty,
1167                                              unsigned Depth) {
1168   assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1169          "This is not a truncating conversion!");
1170   assert(isSCEVable(Ty) &&
1171          "This is not a conversion to a SCEVable type!");
1172   Ty = getEffectiveSCEVType(Ty);
1173 
1174   FoldingSetNodeID ID;
1175   ID.AddInteger(scTruncate);
1176   ID.AddPointer(Op);
1177   ID.AddPointer(Ty);
1178   void *IP = nullptr;
1179   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1180 
1181   // Fold if the operand is constant.
1182   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1183     return getConstant(
1184       cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1185 
1186   // trunc(trunc(x)) --> trunc(x)
1187   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
1188     return getTruncateExpr(ST->getOperand(), Ty, Depth + 1);
1189 
1190   // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1191   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1192     return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1);
1193 
1194   // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1195   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1196     return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1);
1197 
1198   if (Depth > MaxCastDepth) {
1199     SCEV *S =
1200         new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty);
1201     UniqueSCEVs.InsertNode(S, IP);
1202     addToLoopUseLists(S);
1203     return S;
1204   }
1205 
1206   // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and
1207   // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN),
1208   // if after transforming we have at most one truncate, not counting truncates
1209   // that replace other casts.
1210   if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) {
1211     auto *CommOp = cast<SCEVCommutativeExpr>(Op);
1212     SmallVector<const SCEV *, 4> Operands;
1213     unsigned numTruncs = 0;
1214     for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2;
1215          ++i) {
1216       const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1);
1217       if (!isa<SCEVIntegralCastExpr>(CommOp->getOperand(i)) &&
1218           isa<SCEVTruncateExpr>(S))
1219         numTruncs++;
1220       Operands.push_back(S);
1221     }
1222     if (numTruncs < 2) {
1223       if (isa<SCEVAddExpr>(Op))
1224         return getAddExpr(Operands);
1225       else if (isa<SCEVMulExpr>(Op))
1226         return getMulExpr(Operands);
1227       else
1228         llvm_unreachable("Unexpected SCEV type for Op.");
1229     }
1230     // Although we checked in the beginning that ID is not in the cache, it is
1231     // possible that during recursion and different modification ID was inserted
1232     // into the cache. So if we find it, just return it.
1233     if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1234       return S;
1235   }
1236 
1237   // If the input value is a chrec scev, truncate the chrec's operands.
1238   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1239     SmallVector<const SCEV *, 4> Operands;
1240     for (const SCEV *Op : AddRec->operands())
1241       Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1));
1242     return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1243   }
1244 
1245   // Return zero if truncating to known zeros.
1246   uint32_t MinTrailingZeros = GetMinTrailingZeros(Op);
1247   if (MinTrailingZeros >= getTypeSizeInBits(Ty))
1248     return getZero(Ty);
1249 
1250   // The cast wasn't folded; create an explicit cast node. We can reuse
1251   // the existing insert position since if we get here, we won't have
1252   // made any changes which would invalidate it.
1253   SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1254                                                  Op, Ty);
1255   UniqueSCEVs.InsertNode(S, IP);
1256   addToLoopUseLists(S);
1257   return S;
1258 }
1259 
1260 // Get the limit of a recurrence such that incrementing by Step cannot cause
1261 // signed overflow as long as the value of the recurrence within the
1262 // loop does not exceed this limit before incrementing.
1263 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1264                                                  ICmpInst::Predicate *Pred,
1265                                                  ScalarEvolution *SE) {
1266   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1267   if (SE->isKnownPositive(Step)) {
1268     *Pred = ICmpInst::ICMP_SLT;
1269     return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1270                            SE->getSignedRangeMax(Step));
1271   }
1272   if (SE->isKnownNegative(Step)) {
1273     *Pred = ICmpInst::ICMP_SGT;
1274     return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1275                            SE->getSignedRangeMin(Step));
1276   }
1277   return nullptr;
1278 }
1279 
1280 // Get the limit of a recurrence such that incrementing by Step cannot cause
1281 // unsigned overflow as long as the value of the recurrence within the loop does
1282 // not exceed this limit before incrementing.
1283 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1284                                                    ICmpInst::Predicate *Pred,
1285                                                    ScalarEvolution *SE) {
1286   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1287   *Pred = ICmpInst::ICMP_ULT;
1288 
1289   return SE->getConstant(APInt::getMinValue(BitWidth) -
1290                          SE->getUnsignedRangeMax(Step));
1291 }
1292 
1293 namespace {
1294 
1295 struct ExtendOpTraitsBase {
1296   typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *,
1297                                                           unsigned);
1298 };
1299 
1300 // Used to make code generic over signed and unsigned overflow.
1301 template <typename ExtendOp> struct ExtendOpTraits {
1302   // Members present:
1303   //
1304   // static const SCEV::NoWrapFlags WrapType;
1305   //
1306   // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1307   //
1308   // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1309   //                                           ICmpInst::Predicate *Pred,
1310   //                                           ScalarEvolution *SE);
1311 };
1312 
1313 template <>
1314 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1315   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1316 
1317   static const GetExtendExprTy GetExtendExpr;
1318 
1319   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1320                                              ICmpInst::Predicate *Pred,
1321                                              ScalarEvolution *SE) {
1322     return getSignedOverflowLimitForStep(Step, Pred, SE);
1323   }
1324 };
1325 
1326 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1327     SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr;
1328 
1329 template <>
1330 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1331   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1332 
1333   static const GetExtendExprTy GetExtendExpr;
1334 
1335   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1336                                              ICmpInst::Predicate *Pred,
1337                                              ScalarEvolution *SE) {
1338     return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1339   }
1340 };
1341 
1342 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1343     SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr;
1344 
1345 } // end anonymous namespace
1346 
1347 // The recurrence AR has been shown to have no signed/unsigned wrap or something
1348 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1349 // easily prove NSW/NUW for its preincrement or postincrement sibling. This
1350 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1351 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1352 // expression "Step + sext/zext(PreIncAR)" is congruent with
1353 // "sext/zext(PostIncAR)"
1354 template <typename ExtendOpTy>
1355 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1356                                         ScalarEvolution *SE, unsigned Depth) {
1357   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1358   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1359 
1360   const Loop *L = AR->getLoop();
1361   const SCEV *Start = AR->getStart();
1362   const SCEV *Step = AR->getStepRecurrence(*SE);
1363 
1364   // Check for a simple looking step prior to loop entry.
1365   const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1366   if (!SA)
1367     return nullptr;
1368 
1369   // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1370   // subtraction is expensive. For this purpose, perform a quick and dirty
1371   // difference, by checking for Step in the operand list.
1372   SmallVector<const SCEV *, 4> DiffOps;
1373   for (const SCEV *Op : SA->operands())
1374     if (Op != Step)
1375       DiffOps.push_back(Op);
1376 
1377   if (DiffOps.size() == SA->getNumOperands())
1378     return nullptr;
1379 
1380   // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1381   // `Step`:
1382 
1383   // 1. NSW/NUW flags on the step increment.
1384   auto PreStartFlags =
1385     ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
1386   const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1387   const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1388       SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1389 
1390   // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1391   // "S+X does not sign/unsign-overflow".
1392   //
1393 
1394   const SCEV *BECount = SE->getBackedgeTakenCount(L);
1395   if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1396       !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1397     return PreStart;
1398 
1399   // 2. Direct overflow check on the step operation's expression.
1400   unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1401   Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1402   const SCEV *OperandExtendedStart =
1403       SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
1404                      (SE->*GetExtendExpr)(Step, WideTy, Depth));
1405   if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
1406     if (PreAR && AR->getNoWrapFlags(WrapType)) {
1407       // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1408       // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1409       // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`.  Cache this fact.
1410       SE->setNoWrapFlags(const_cast<SCEVAddRecExpr *>(PreAR), WrapType);
1411     }
1412     return PreStart;
1413   }
1414 
1415   // 3. Loop precondition.
1416   ICmpInst::Predicate Pred;
1417   const SCEV *OverflowLimit =
1418       ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1419 
1420   if (OverflowLimit &&
1421       SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1422     return PreStart;
1423 
1424   return nullptr;
1425 }
1426 
1427 // Get the normalized zero or sign extended expression for this AddRec's Start.
1428 template <typename ExtendOpTy>
1429 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1430                                         ScalarEvolution *SE,
1431                                         unsigned Depth) {
1432   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1433 
1434   const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth);
1435   if (!PreStart)
1436     return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth);
1437 
1438   return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty,
1439                                              Depth),
1440                         (SE->*GetExtendExpr)(PreStart, Ty, Depth));
1441 }
1442 
1443 // Try to prove away overflow by looking at "nearby" add recurrences.  A
1444 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1445 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1446 //
1447 // Formally:
1448 //
1449 //     {S,+,X} == {S-T,+,X} + T
1450 //  => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1451 //
1452 // If ({S-T,+,X} + T) does not overflow  ... (1)
1453 //
1454 //  RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1455 //
1456 // If {S-T,+,X} does not overflow  ... (2)
1457 //
1458 //  RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1459 //      == {Ext(S-T)+Ext(T),+,Ext(X)}
1460 //
1461 // If (S-T)+T does not overflow  ... (3)
1462 //
1463 //  RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1464 //      == {Ext(S),+,Ext(X)} == LHS
1465 //
1466 // Thus, if (1), (2) and (3) are true for some T, then
1467 //   Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1468 //
1469 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1470 // does not overflow" restricted to the 0th iteration.  Therefore we only need
1471 // to check for (1) and (2).
1472 //
1473 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1474 // is `Delta` (defined below).
1475 template <typename ExtendOpTy>
1476 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1477                                                 const SCEV *Step,
1478                                                 const Loop *L) {
1479   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1480 
1481   // We restrict `Start` to a constant to prevent SCEV from spending too much
1482   // time here.  It is correct (but more expensive) to continue with a
1483   // non-constant `Start` and do a general SCEV subtraction to compute
1484   // `PreStart` below.
1485   const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1486   if (!StartC)
1487     return false;
1488 
1489   APInt StartAI = StartC->getAPInt();
1490 
1491   for (unsigned Delta : {-2, -1, 1, 2}) {
1492     const SCEV *PreStart = getConstant(StartAI - Delta);
1493 
1494     FoldingSetNodeID ID;
1495     ID.AddInteger(scAddRecExpr);
1496     ID.AddPointer(PreStart);
1497     ID.AddPointer(Step);
1498     ID.AddPointer(L);
1499     void *IP = nullptr;
1500     const auto *PreAR =
1501       static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1502 
1503     // Give up if we don't already have the add recurrence we need because
1504     // actually constructing an add recurrence is relatively expensive.
1505     if (PreAR && PreAR->getNoWrapFlags(WrapType)) {  // proves (2)
1506       const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1507       ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1508       const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1509           DeltaS, &Pred, this);
1510       if (Limit && isKnownPredicate(Pred, PreAR, Limit))  // proves (1)
1511         return true;
1512     }
1513   }
1514 
1515   return false;
1516 }
1517 
1518 // Finds an integer D for an expression (C + x + y + ...) such that the top
1519 // level addition in (D + (C - D + x + y + ...)) would not wrap (signed or
1520 // unsigned) and the number of trailing zeros of (C - D + x + y + ...) is
1521 // maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and
1522 // the (C + x + y + ...) expression is \p WholeAddExpr.
1523 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE,
1524                                             const SCEVConstant *ConstantTerm,
1525                                             const SCEVAddExpr *WholeAddExpr) {
1526   const APInt &C = ConstantTerm->getAPInt();
1527   const unsigned BitWidth = C.getBitWidth();
1528   // Find number of trailing zeros of (x + y + ...) w/o the C first:
1529   uint32_t TZ = BitWidth;
1530   for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I)
1531     TZ = std::min(TZ, SE.GetMinTrailingZeros(WholeAddExpr->getOperand(I)));
1532   if (TZ) {
1533     // Set D to be as many least significant bits of C as possible while still
1534     // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap:
1535     return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C;
1536   }
1537   return APInt(BitWidth, 0);
1538 }
1539 
1540 // Finds an integer D for an affine AddRec expression {C,+,x} such that the top
1541 // level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the
1542 // number of trailing zeros of (C - D + x * n) is maximized, where C is the \p
1543 // ConstantStart, x is an arbitrary \p Step, and n is the loop trip count.
1544 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE,
1545                                             const APInt &ConstantStart,
1546                                             const SCEV *Step) {
1547   const unsigned BitWidth = ConstantStart.getBitWidth();
1548   const uint32_t TZ = SE.GetMinTrailingZeros(Step);
1549   if (TZ)
1550     return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth)
1551                          : ConstantStart;
1552   return APInt(BitWidth, 0);
1553 }
1554 
1555 const SCEV *
1556 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1557   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1558          "This is not an extending conversion!");
1559   assert(isSCEVable(Ty) &&
1560          "This is not a conversion to a SCEVable type!");
1561   Ty = getEffectiveSCEVType(Ty);
1562 
1563   // Fold if the operand is constant.
1564   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1565     return getConstant(
1566       cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
1567 
1568   // zext(zext(x)) --> zext(x)
1569   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1570     return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1571 
1572   // Before doing any expensive analysis, check to see if we've already
1573   // computed a SCEV for this Op and Ty.
1574   FoldingSetNodeID ID;
1575   ID.AddInteger(scZeroExtend);
1576   ID.AddPointer(Op);
1577   ID.AddPointer(Ty);
1578   void *IP = nullptr;
1579   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1580   if (Depth > MaxCastDepth) {
1581     SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1582                                                      Op, Ty);
1583     UniqueSCEVs.InsertNode(S, IP);
1584     addToLoopUseLists(S);
1585     return S;
1586   }
1587 
1588   // zext(trunc(x)) --> zext(x) or x or trunc(x)
1589   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1590     // It's possible the bits taken off by the truncate were all zero bits. If
1591     // so, we should be able to simplify this further.
1592     const SCEV *X = ST->getOperand();
1593     ConstantRange CR = getUnsignedRange(X);
1594     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1595     unsigned NewBits = getTypeSizeInBits(Ty);
1596     if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1597             CR.zextOrTrunc(NewBits)))
1598       return getTruncateOrZeroExtend(X, Ty, Depth);
1599   }
1600 
1601   // If the input value is a chrec scev, and we can prove that the value
1602   // did not overflow the old, smaller, value, we can zero extend all of the
1603   // operands (often constants).  This allows analysis of something like
1604   // this:  for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1605   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1606     if (AR->isAffine()) {
1607       const SCEV *Start = AR->getStart();
1608       const SCEV *Step = AR->getStepRecurrence(*this);
1609       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1610       const Loop *L = AR->getLoop();
1611 
1612       if (!AR->hasNoUnsignedWrap()) {
1613         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1614         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1615       }
1616 
1617       // If we have special knowledge that this addrec won't overflow,
1618       // we don't need to do any further analysis.
1619       if (AR->hasNoUnsignedWrap())
1620         return getAddRecExpr(
1621             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1622             getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1623 
1624       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1625       // Note that this serves two purposes: It filters out loops that are
1626       // simply not analyzable, and it covers the case where this code is
1627       // being called from within backedge-taken count analysis, such that
1628       // attempting to ask for the backedge-taken count would likely result
1629       // in infinite recursion. In the later case, the analysis code will
1630       // cope with a conservative value, and it will take care to purge
1631       // that value once it has finished.
1632       const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
1633       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1634         // Manually compute the final value for AR, checking for overflow.
1635 
1636         // Check whether the backedge-taken count can be losslessly casted to
1637         // the addrec's type. The count is always unsigned.
1638         const SCEV *CastedMaxBECount =
1639             getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
1640         const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
1641             CastedMaxBECount, MaxBECount->getType(), Depth);
1642         if (MaxBECount == RecastedMaxBECount) {
1643           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1644           // Check whether Start+Step*MaxBECount has no unsigned overflow.
1645           const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step,
1646                                         SCEV::FlagAnyWrap, Depth + 1);
1647           const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul,
1648                                                           SCEV::FlagAnyWrap,
1649                                                           Depth + 1),
1650                                                WideTy, Depth + 1);
1651           const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
1652           const SCEV *WideMaxBECount =
1653             getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1654           const SCEV *OperandExtendedAdd =
1655             getAddExpr(WideStart,
1656                        getMulExpr(WideMaxBECount,
1657                                   getZeroExtendExpr(Step, WideTy, Depth + 1),
1658                                   SCEV::FlagAnyWrap, Depth + 1),
1659                        SCEV::FlagAnyWrap, Depth + 1);
1660           if (ZAdd == OperandExtendedAdd) {
1661             // Cache knowledge of AR NUW, which is propagated to this AddRec.
1662             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1663             // Return the expression with the addrec on the outside.
1664             return getAddRecExpr(
1665                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1666                                                          Depth + 1),
1667                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1668                 AR->getNoWrapFlags());
1669           }
1670           // Similar to above, only this time treat the step value as signed.
1671           // This covers loops that count down.
1672           OperandExtendedAdd =
1673             getAddExpr(WideStart,
1674                        getMulExpr(WideMaxBECount,
1675                                   getSignExtendExpr(Step, WideTy, Depth + 1),
1676                                   SCEV::FlagAnyWrap, Depth + 1),
1677                        SCEV::FlagAnyWrap, Depth + 1);
1678           if (ZAdd == OperandExtendedAdd) {
1679             // Cache knowledge of AR NW, which is propagated to this AddRec.
1680             // Negative step causes unsigned wrap, but it still can't self-wrap.
1681             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1682             // Return the expression with the addrec on the outside.
1683             return getAddRecExpr(
1684                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1685                                                          Depth + 1),
1686                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1687                 AR->getNoWrapFlags());
1688           }
1689         }
1690       }
1691 
1692       // Normally, in the cases we can prove no-overflow via a
1693       // backedge guarding condition, we can also compute a backedge
1694       // taken count for the loop.  The exceptions are assumptions and
1695       // guards present in the loop -- SCEV is not great at exploiting
1696       // these to compute max backedge taken counts, but can still use
1697       // these to prove lack of overflow.  Use this fact to avoid
1698       // doing extra work that may not pay off.
1699       if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1700           !AC.assumptions().empty()) {
1701 
1702         auto NewFlags = proveNoUnsignedWrapViaInduction(AR);
1703         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1704         if (AR->hasNoUnsignedWrap()) {
1705           // Same as nuw case above - duplicated here to avoid a compile time
1706           // issue.  It's not clear that the order of checks does matter, but
1707           // it's one of two issue possible causes for a change which was
1708           // reverted.  Be conservative for the moment.
1709           return getAddRecExpr(
1710                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1711                                                          Depth + 1),
1712                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1713                 AR->getNoWrapFlags());
1714         }
1715 
1716         // For a negative step, we can extend the operands iff doing so only
1717         // traverses values in the range zext([0,UINT_MAX]).
1718         if (isKnownNegative(Step)) {
1719           const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1720                                       getSignedRangeMin(Step));
1721           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1722               isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) {
1723             // Cache knowledge of AR NW, which is propagated to this
1724             // AddRec.  Negative step causes unsigned wrap, but it
1725             // still can't self-wrap.
1726             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1727             // Return the expression with the addrec on the outside.
1728             return getAddRecExpr(
1729                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1730                                                          Depth + 1),
1731                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1732                 AR->getNoWrapFlags());
1733           }
1734         }
1735       }
1736 
1737       // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw>
1738       // if D + (C - D + Step * n) could be proven to not unsigned wrap
1739       // where D maximizes the number of trailing zeros of (C - D + Step * n)
1740       if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
1741         const APInt &C = SC->getAPInt();
1742         const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
1743         if (D != 0) {
1744           const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1745           const SCEV *SResidual =
1746               getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
1747           const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1748           return getAddExpr(SZExtD, SZExtR,
1749                             (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1750                             Depth + 1);
1751         }
1752       }
1753 
1754       if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1755         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1756         return getAddRecExpr(
1757             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1758             getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1759       }
1760     }
1761 
1762   // zext(A % B) --> zext(A) % zext(B)
1763   {
1764     const SCEV *LHS;
1765     const SCEV *RHS;
1766     if (matchURem(Op, LHS, RHS))
1767       return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1),
1768                          getZeroExtendExpr(RHS, Ty, Depth + 1));
1769   }
1770 
1771   // zext(A / B) --> zext(A) / zext(B).
1772   if (auto *Div = dyn_cast<SCEVUDivExpr>(Op))
1773     return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1),
1774                        getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1));
1775 
1776   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1777     // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1778     if (SA->hasNoUnsignedWrap()) {
1779       // If the addition does not unsign overflow then we can, by definition,
1780       // commute the zero extension with the addition operation.
1781       SmallVector<const SCEV *, 4> Ops;
1782       for (const auto *Op : SA->operands())
1783         Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1784       return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1);
1785     }
1786 
1787     // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...))
1788     // if D + (C - D + x + y + ...) could be proven to not unsigned wrap
1789     // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1790     //
1791     // Often address arithmetics contain expressions like
1792     // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))).
1793     // This transformation is useful while proving that such expressions are
1794     // equal or differ by a small constant amount, see LoadStoreVectorizer pass.
1795     if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1796       const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1797       if (D != 0) {
1798         const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1799         const SCEV *SResidual =
1800             getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth);
1801         const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1802         return getAddExpr(SZExtD, SZExtR,
1803                           (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1804                           Depth + 1);
1805       }
1806     }
1807   }
1808 
1809   if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) {
1810     // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw>
1811     if (SM->hasNoUnsignedWrap()) {
1812       // If the multiply does not unsign overflow then we can, by definition,
1813       // commute the zero extension with the multiply operation.
1814       SmallVector<const SCEV *, 4> Ops;
1815       for (const auto *Op : SM->operands())
1816         Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1817       return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1);
1818     }
1819 
1820     // zext(2^K * (trunc X to iN)) to iM ->
1821     // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw>
1822     //
1823     // Proof:
1824     //
1825     //     zext(2^K * (trunc X to iN)) to iM
1826     //   = zext((trunc X to iN) << K) to iM
1827     //   = zext((trunc X to i{N-K}) << K)<nuw> to iM
1828     //     (because shl removes the top K bits)
1829     //   = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM
1830     //   = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>.
1831     //
1832     if (SM->getNumOperands() == 2)
1833       if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0)))
1834         if (MulLHS->getAPInt().isPowerOf2())
1835           if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) {
1836             int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) -
1837                                MulLHS->getAPInt().logBase2();
1838             Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits);
1839             return getMulExpr(
1840                 getZeroExtendExpr(MulLHS, Ty),
1841                 getZeroExtendExpr(
1842                     getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty),
1843                 SCEV::FlagNUW, Depth + 1);
1844           }
1845   }
1846 
1847   // The cast wasn't folded; create an explicit cast node.
1848   // Recompute the insert position, as it may have been invalidated.
1849   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1850   SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1851                                                    Op, Ty);
1852   UniqueSCEVs.InsertNode(S, IP);
1853   addToLoopUseLists(S);
1854   return S;
1855 }
1856 
1857 const SCEV *
1858 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1859   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1860          "This is not an extending conversion!");
1861   assert(isSCEVable(Ty) &&
1862          "This is not a conversion to a SCEVable type!");
1863   Ty = getEffectiveSCEVType(Ty);
1864 
1865   // Fold if the operand is constant.
1866   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1867     return getConstant(
1868       cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
1869 
1870   // sext(sext(x)) --> sext(x)
1871   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1872     return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1);
1873 
1874   // sext(zext(x)) --> zext(x)
1875   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1876     return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1877 
1878   // Before doing any expensive analysis, check to see if we've already
1879   // computed a SCEV for this Op and Ty.
1880   FoldingSetNodeID ID;
1881   ID.AddInteger(scSignExtend);
1882   ID.AddPointer(Op);
1883   ID.AddPointer(Ty);
1884   void *IP = nullptr;
1885   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1886   // Limit recursion depth.
1887   if (Depth > MaxCastDepth) {
1888     SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1889                                                      Op, Ty);
1890     UniqueSCEVs.InsertNode(S, IP);
1891     addToLoopUseLists(S);
1892     return S;
1893   }
1894 
1895   // sext(trunc(x)) --> sext(x) or x or trunc(x)
1896   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1897     // It's possible the bits taken off by the truncate were all sign bits. If
1898     // so, we should be able to simplify this further.
1899     const SCEV *X = ST->getOperand();
1900     ConstantRange CR = getSignedRange(X);
1901     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1902     unsigned NewBits = getTypeSizeInBits(Ty);
1903     if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1904             CR.sextOrTrunc(NewBits)))
1905       return getTruncateOrSignExtend(X, Ty, Depth);
1906   }
1907 
1908   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1909     // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1910     if (SA->hasNoSignedWrap()) {
1911       // If the addition does not sign overflow then we can, by definition,
1912       // commute the sign extension with the addition operation.
1913       SmallVector<const SCEV *, 4> Ops;
1914       for (const auto *Op : SA->operands())
1915         Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1));
1916       return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1);
1917     }
1918 
1919     // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...))
1920     // if D + (C - D + x + y + ...) could be proven to not signed wrap
1921     // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1922     //
1923     // For instance, this will bring two seemingly different expressions:
1924     //     1 + sext(5 + 20 * %x + 24 * %y)  and
1925     //         sext(6 + 20 * %x + 24 * %y)
1926     // to the same form:
1927     //     2 + sext(4 + 20 * %x + 24 * %y)
1928     if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1929       const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1930       if (D != 0) {
1931         const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
1932         const SCEV *SResidual =
1933             getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth);
1934         const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
1935         return getAddExpr(SSExtD, SSExtR,
1936                           (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1937                           Depth + 1);
1938       }
1939     }
1940   }
1941   // If the input value is a chrec scev, and we can prove that the value
1942   // did not overflow the old, smaller, value, we can sign extend all of the
1943   // operands (often constants).  This allows analysis of something like
1944   // this:  for (signed char X = 0; X < 100; ++X) { int Y = X; }
1945   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1946     if (AR->isAffine()) {
1947       const SCEV *Start = AR->getStart();
1948       const SCEV *Step = AR->getStepRecurrence(*this);
1949       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1950       const Loop *L = AR->getLoop();
1951 
1952       if (!AR->hasNoSignedWrap()) {
1953         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1954         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1955       }
1956 
1957       // If we have special knowledge that this addrec won't overflow,
1958       // we don't need to do any further analysis.
1959       if (AR->hasNoSignedWrap())
1960         return getAddRecExpr(
1961             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
1962             getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW);
1963 
1964       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1965       // Note that this serves two purposes: It filters out loops that are
1966       // simply not analyzable, and it covers the case where this code is
1967       // being called from within backedge-taken count analysis, such that
1968       // attempting to ask for the backedge-taken count would likely result
1969       // in infinite recursion. In the later case, the analysis code will
1970       // cope with a conservative value, and it will take care to purge
1971       // that value once it has finished.
1972       const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
1973       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1974         // Manually compute the final value for AR, checking for
1975         // overflow.
1976 
1977         // Check whether the backedge-taken count can be losslessly casted to
1978         // the addrec's type. The count is always unsigned.
1979         const SCEV *CastedMaxBECount =
1980             getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
1981         const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
1982             CastedMaxBECount, MaxBECount->getType(), Depth);
1983         if (MaxBECount == RecastedMaxBECount) {
1984           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1985           // Check whether Start+Step*MaxBECount has no signed overflow.
1986           const SCEV *SMul = getMulExpr(CastedMaxBECount, Step,
1987                                         SCEV::FlagAnyWrap, Depth + 1);
1988           const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul,
1989                                                           SCEV::FlagAnyWrap,
1990                                                           Depth + 1),
1991                                                WideTy, Depth + 1);
1992           const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
1993           const SCEV *WideMaxBECount =
1994             getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1995           const SCEV *OperandExtendedAdd =
1996             getAddExpr(WideStart,
1997                        getMulExpr(WideMaxBECount,
1998                                   getSignExtendExpr(Step, WideTy, Depth + 1),
1999                                   SCEV::FlagAnyWrap, Depth + 1),
2000                        SCEV::FlagAnyWrap, Depth + 1);
2001           if (SAdd == OperandExtendedAdd) {
2002             // Cache knowledge of AR NSW, which is propagated to this AddRec.
2003             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2004             // Return the expression with the addrec on the outside.
2005             return getAddRecExpr(
2006                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
2007                                                          Depth + 1),
2008                 getSignExtendExpr(Step, Ty, Depth + 1), L,
2009                 AR->getNoWrapFlags());
2010           }
2011           // Similar to above, only this time treat the step value as unsigned.
2012           // This covers loops that count up with an unsigned step.
2013           OperandExtendedAdd =
2014             getAddExpr(WideStart,
2015                        getMulExpr(WideMaxBECount,
2016                                   getZeroExtendExpr(Step, WideTy, Depth + 1),
2017                                   SCEV::FlagAnyWrap, Depth + 1),
2018                        SCEV::FlagAnyWrap, Depth + 1);
2019           if (SAdd == OperandExtendedAdd) {
2020             // If AR wraps around then
2021             //
2022             //    abs(Step) * MaxBECount > unsigned-max(AR->getType())
2023             // => SAdd != OperandExtendedAdd
2024             //
2025             // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
2026             // (SAdd == OperandExtendedAdd => AR is NW)
2027 
2028             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
2029 
2030             // Return the expression with the addrec on the outside.
2031             return getAddRecExpr(
2032                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
2033                                                          Depth + 1),
2034                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
2035                 AR->getNoWrapFlags());
2036           }
2037         }
2038       }
2039 
2040       auto NewFlags = proveNoSignedWrapViaInduction(AR);
2041       setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
2042       if (AR->hasNoSignedWrap()) {
2043         // Same as nsw case above - duplicated here to avoid a compile time
2044         // issue.  It's not clear that the order of checks does matter, but
2045         // it's one of two issue possible causes for a change which was
2046         // reverted.  Be conservative for the moment.
2047         return getAddRecExpr(
2048             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2049             getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2050       }
2051 
2052       // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw>
2053       // if D + (C - D + Step * n) could be proven to not signed wrap
2054       // where D maximizes the number of trailing zeros of (C - D + Step * n)
2055       if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
2056         const APInt &C = SC->getAPInt();
2057         const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
2058         if (D != 0) {
2059           const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
2060           const SCEV *SResidual =
2061               getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
2062           const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
2063           return getAddExpr(SSExtD, SSExtR,
2064                             (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
2065                             Depth + 1);
2066         }
2067       }
2068 
2069       if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
2070         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2071         return getAddRecExpr(
2072             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2073             getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2074       }
2075     }
2076 
2077   // If the input value is provably positive and we could not simplify
2078   // away the sext build a zext instead.
2079   if (isKnownNonNegative(Op))
2080     return getZeroExtendExpr(Op, Ty, Depth + 1);
2081 
2082   // The cast wasn't folded; create an explicit cast node.
2083   // Recompute the insert position, as it may have been invalidated.
2084   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2085   SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
2086                                                    Op, Ty);
2087   UniqueSCEVs.InsertNode(S, IP);
2088   addToLoopUseLists(S);
2089   return S;
2090 }
2091 
2092 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
2093 /// unspecified bits out to the given type.
2094 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
2095                                               Type *Ty) {
2096   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
2097          "This is not an extending conversion!");
2098   assert(isSCEVable(Ty) &&
2099          "This is not a conversion to a SCEVable type!");
2100   Ty = getEffectiveSCEVType(Ty);
2101 
2102   // Sign-extend negative constants.
2103   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
2104     if (SC->getAPInt().isNegative())
2105       return getSignExtendExpr(Op, Ty);
2106 
2107   // Peel off a truncate cast.
2108   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
2109     const SCEV *NewOp = T->getOperand();
2110     if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
2111       return getAnyExtendExpr(NewOp, Ty);
2112     return getTruncateOrNoop(NewOp, Ty);
2113   }
2114 
2115   // Next try a zext cast. If the cast is folded, use it.
2116   const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2117   if (!isa<SCEVZeroExtendExpr>(ZExt))
2118     return ZExt;
2119 
2120   // Next try a sext cast. If the cast is folded, use it.
2121   const SCEV *SExt = getSignExtendExpr(Op, Ty);
2122   if (!isa<SCEVSignExtendExpr>(SExt))
2123     return SExt;
2124 
2125   // Force the cast to be folded into the operands of an addrec.
2126   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2127     SmallVector<const SCEV *, 4> Ops;
2128     for (const SCEV *Op : AR->operands())
2129       Ops.push_back(getAnyExtendExpr(Op, Ty));
2130     return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2131   }
2132 
2133   // If the expression is obviously signed, use the sext cast value.
2134   if (isa<SCEVSMaxExpr>(Op))
2135     return SExt;
2136 
2137   // Absent any other information, use the zext cast value.
2138   return ZExt;
2139 }
2140 
2141 /// Process the given Ops list, which is a list of operands to be added under
2142 /// the given scale, update the given map. This is a helper function for
2143 /// getAddRecExpr. As an example of what it does, given a sequence of operands
2144 /// that would form an add expression like this:
2145 ///
2146 ///    m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2147 ///
2148 /// where A and B are constants, update the map with these values:
2149 ///
2150 ///    (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2151 ///
2152 /// and add 13 + A*B*29 to AccumulatedConstant.
2153 /// This will allow getAddRecExpr to produce this:
2154 ///
2155 ///    13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2156 ///
2157 /// This form often exposes folding opportunities that are hidden in
2158 /// the original operand list.
2159 ///
2160 /// Return true iff it appears that any interesting folding opportunities
2161 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
2162 /// the common case where no interesting opportunities are present, and
2163 /// is also used as a check to avoid infinite recursion.
2164 static bool
2165 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
2166                              SmallVectorImpl<const SCEV *> &NewOps,
2167                              APInt &AccumulatedConstant,
2168                              const SCEV *const *Ops, size_t NumOperands,
2169                              const APInt &Scale,
2170                              ScalarEvolution &SE) {
2171   bool Interesting = false;
2172 
2173   // Iterate over the add operands. They are sorted, with constants first.
2174   unsigned i = 0;
2175   while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2176     ++i;
2177     // Pull a buried constant out to the outside.
2178     if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2179       Interesting = true;
2180     AccumulatedConstant += Scale * C->getAPInt();
2181   }
2182 
2183   // Next comes everything else. We're especially interested in multiplies
2184   // here, but they're in the middle, so just visit the rest with one loop.
2185   for (; i != NumOperands; ++i) {
2186     const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
2187     if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2188       APInt NewScale =
2189           Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2190       if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2191         // A multiplication of a constant with another add; recurse.
2192         const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2193         Interesting |=
2194           CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2195                                        Add->op_begin(), Add->getNumOperands(),
2196                                        NewScale, SE);
2197       } else {
2198         // A multiplication of a constant with some other value. Update
2199         // the map.
2200         SmallVector<const SCEV *, 4> MulOps(drop_begin(Mul->operands()));
2201         const SCEV *Key = SE.getMulExpr(MulOps);
2202         auto Pair = M.insert({Key, NewScale});
2203         if (Pair.second) {
2204           NewOps.push_back(Pair.first->first);
2205         } else {
2206           Pair.first->second += NewScale;
2207           // The map already had an entry for this value, which may indicate
2208           // a folding opportunity.
2209           Interesting = true;
2210         }
2211       }
2212     } else {
2213       // An ordinary operand. Update the map.
2214       std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
2215           M.insert({Ops[i], Scale});
2216       if (Pair.second) {
2217         NewOps.push_back(Pair.first->first);
2218       } else {
2219         Pair.first->second += Scale;
2220         // The map already had an entry for this value, which may indicate
2221         // a folding opportunity.
2222         Interesting = true;
2223       }
2224     }
2225   }
2226 
2227   return Interesting;
2228 }
2229 
2230 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2231 // `OldFlags' as can't-wrap behavior.  Infer a more aggressive set of
2232 // can't-overflow flags for the operation if possible.
2233 static SCEV::NoWrapFlags
2234 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
2235                       const ArrayRef<const SCEV *> Ops,
2236                       SCEV::NoWrapFlags Flags) {
2237   using namespace std::placeholders;
2238 
2239   using OBO = OverflowingBinaryOperator;
2240 
2241   bool CanAnalyze =
2242       Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
2243   (void)CanAnalyze;
2244   assert(CanAnalyze && "don't call from other places!");
2245 
2246   int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2247   SCEV::NoWrapFlags SignOrUnsignWrap =
2248       ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2249 
2250   // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2251   auto IsKnownNonNegative = [&](const SCEV *S) {
2252     return SE->isKnownNonNegative(S);
2253   };
2254 
2255   if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2256     Flags =
2257         ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
2258 
2259   SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2260 
2261   if (SignOrUnsignWrap != SignOrUnsignMask &&
2262       (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 &&
2263       isa<SCEVConstant>(Ops[0])) {
2264 
2265     auto Opcode = [&] {
2266       switch (Type) {
2267       case scAddExpr:
2268         return Instruction::Add;
2269       case scMulExpr:
2270         return Instruction::Mul;
2271       default:
2272         llvm_unreachable("Unexpected SCEV op.");
2273       }
2274     }();
2275 
2276     const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2277 
2278     // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow.
2279     if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2280       auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2281           Opcode, C, OBO::NoSignedWrap);
2282       if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2283         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2284     }
2285 
2286     // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow.
2287     if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2288       auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2289           Opcode, C, OBO::NoUnsignedWrap);
2290       if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2291         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2292     }
2293   }
2294 
2295   return Flags;
2296 }
2297 
2298 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) {
2299   return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader());
2300 }
2301 
2302 /// Get a canonical add expression, or something simpler if possible.
2303 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2304                                         SCEV::NoWrapFlags OrigFlags,
2305                                         unsigned Depth) {
2306   assert(!(OrigFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2307          "only nuw or nsw allowed");
2308   assert(!Ops.empty() && "Cannot get empty add!");
2309   if (Ops.size() == 1) return Ops[0];
2310 #ifndef NDEBUG
2311   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2312   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2313     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2314            "SCEVAddExpr operand types don't match!");
2315 #endif
2316 
2317   // Sort by complexity, this groups all similar expression types together.
2318   GroupByComplexity(Ops, &LI, DT);
2319 
2320   // If there are any constants, fold them together.
2321   unsigned Idx = 0;
2322   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2323     ++Idx;
2324     assert(Idx < Ops.size());
2325     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2326       // We found two constants, fold them together!
2327       Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
2328       if (Ops.size() == 2) return Ops[0];
2329       Ops.erase(Ops.begin()+1);  // Erase the folded element
2330       LHSC = cast<SCEVConstant>(Ops[0]);
2331     }
2332 
2333     // If we are left with a constant zero being added, strip it off.
2334     if (LHSC->getValue()->isZero()) {
2335       Ops.erase(Ops.begin());
2336       --Idx;
2337     }
2338 
2339     if (Ops.size() == 1) return Ops[0];
2340   }
2341 
2342   // Delay expensive flag strengthening until necessary.
2343   auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) {
2344     return StrengthenNoWrapFlags(this, scAddExpr, Ops, OrigFlags);
2345   };
2346 
2347   // Limit recursion calls depth.
2348   if (Depth > MaxArithDepth || hasHugeExpression(Ops))
2349     return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
2350 
2351   if (SCEV *S = std::get<0>(findExistingSCEVInCache(scAddExpr, Ops))) {
2352     // Don't strengthen flags if we have no new information.
2353     SCEVAddExpr *Add = static_cast<SCEVAddExpr *>(S);
2354     if (Add->getNoWrapFlags(OrigFlags) != OrigFlags)
2355       Add->setNoWrapFlags(ComputeFlags(Ops));
2356     return S;
2357   }
2358 
2359   // Okay, check to see if the same value occurs in the operand list more than
2360   // once.  If so, merge them together into an multiply expression.  Since we
2361   // sorted the list, these values are required to be adjacent.
2362   Type *Ty = Ops[0]->getType();
2363   bool FoundMatch = false;
2364   for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2365     if (Ops[i] == Ops[i+1]) {      //  X + Y + Y  -->  X + Y*2
2366       // Scan ahead to count how many equal operands there are.
2367       unsigned Count = 2;
2368       while (i+Count != e && Ops[i+Count] == Ops[i])
2369         ++Count;
2370       // Merge the values into a multiply.
2371       const SCEV *Scale = getConstant(Ty, Count);
2372       const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1);
2373       if (Ops.size() == Count)
2374         return Mul;
2375       Ops[i] = Mul;
2376       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2377       --i; e -= Count - 1;
2378       FoundMatch = true;
2379     }
2380   if (FoundMatch)
2381     return getAddExpr(Ops, OrigFlags, Depth + 1);
2382 
2383   // Check for truncates. If all the operands are truncated from the same
2384   // type, see if factoring out the truncate would permit the result to be
2385   // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
2386   // if the contents of the resulting outer trunc fold to something simple.
2387   auto FindTruncSrcType = [&]() -> Type * {
2388     // We're ultimately looking to fold an addrec of truncs and muls of only
2389     // constants and truncs, so if we find any other types of SCEV
2390     // as operands of the addrec then we bail and return nullptr here.
2391     // Otherwise, we return the type of the operand of a trunc that we find.
2392     if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx]))
2393       return T->getOperand()->getType();
2394     if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2395       const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1);
2396       if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp))
2397         return T->getOperand()->getType();
2398     }
2399     return nullptr;
2400   };
2401   if (auto *SrcType = FindTruncSrcType()) {
2402     SmallVector<const SCEV *, 8> LargeOps;
2403     bool Ok = true;
2404     // Check all the operands to see if they can be represented in the
2405     // source type of the truncate.
2406     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2407       if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2408         if (T->getOperand()->getType() != SrcType) {
2409           Ok = false;
2410           break;
2411         }
2412         LargeOps.push_back(T->getOperand());
2413       } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2414         LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2415       } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
2416         SmallVector<const SCEV *, 8> LargeMulOps;
2417         for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2418           if (const SCEVTruncateExpr *T =
2419                 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2420             if (T->getOperand()->getType() != SrcType) {
2421               Ok = false;
2422               break;
2423             }
2424             LargeMulOps.push_back(T->getOperand());
2425           } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2426             LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2427           } else {
2428             Ok = false;
2429             break;
2430           }
2431         }
2432         if (Ok)
2433           LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1));
2434       } else {
2435         Ok = false;
2436         break;
2437       }
2438     }
2439     if (Ok) {
2440       // Evaluate the expression in the larger type.
2441       const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1);
2442       // If it folds to something simple, use it. Otherwise, don't.
2443       if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2444         return getTruncateExpr(Fold, Ty);
2445     }
2446   }
2447 
2448   // Skip past any other cast SCEVs.
2449   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2450     ++Idx;
2451 
2452   // If there are add operands they would be next.
2453   if (Idx < Ops.size()) {
2454     bool DeletedAdd = false;
2455     while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2456       if (Ops.size() > AddOpsInlineThreshold ||
2457           Add->getNumOperands() > AddOpsInlineThreshold)
2458         break;
2459       // If we have an add, expand the add operands onto the end of the operands
2460       // list.
2461       Ops.erase(Ops.begin()+Idx);
2462       Ops.append(Add->op_begin(), Add->op_end());
2463       DeletedAdd = true;
2464     }
2465 
2466     // If we deleted at least one add, we added operands to the end of the list,
2467     // and they are not necessarily sorted.  Recurse to resort and resimplify
2468     // any operands we just acquired.
2469     if (DeletedAdd)
2470       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2471   }
2472 
2473   // Skip over the add expression until we get to a multiply.
2474   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2475     ++Idx;
2476 
2477   // Check to see if there are any folding opportunities present with
2478   // operands multiplied by constant values.
2479   if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2480     uint64_t BitWidth = getTypeSizeInBits(Ty);
2481     DenseMap<const SCEV *, APInt> M;
2482     SmallVector<const SCEV *, 8> NewOps;
2483     APInt AccumulatedConstant(BitWidth, 0);
2484     if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2485                                      Ops.data(), Ops.size(),
2486                                      APInt(BitWidth, 1), *this)) {
2487       struct APIntCompare {
2488         bool operator()(const APInt &LHS, const APInt &RHS) const {
2489           return LHS.ult(RHS);
2490         }
2491       };
2492 
2493       // Some interesting folding opportunity is present, so its worthwhile to
2494       // re-generate the operands list. Group the operands by constant scale,
2495       // to avoid multiplying by the same constant scale multiple times.
2496       std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
2497       for (const SCEV *NewOp : NewOps)
2498         MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2499       // Re-generate the operands list.
2500       Ops.clear();
2501       if (AccumulatedConstant != 0)
2502         Ops.push_back(getConstant(AccumulatedConstant));
2503       for (auto &MulOp : MulOpLists)
2504         if (MulOp.first != 0)
2505           Ops.push_back(getMulExpr(
2506               getConstant(MulOp.first),
2507               getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1),
2508               SCEV::FlagAnyWrap, Depth + 1));
2509       if (Ops.empty())
2510         return getZero(Ty);
2511       if (Ops.size() == 1)
2512         return Ops[0];
2513       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2514     }
2515   }
2516 
2517   // If we are adding something to a multiply expression, make sure the
2518   // something is not already an operand of the multiply.  If so, merge it into
2519   // the multiply.
2520   for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2521     const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2522     for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2523       const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2524       if (isa<SCEVConstant>(MulOpSCEV))
2525         continue;
2526       for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
2527         if (MulOpSCEV == Ops[AddOp]) {
2528           // Fold W + X + (X * Y * Z)  -->  W + (X * ((Y*Z)+1))
2529           const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
2530           if (Mul->getNumOperands() != 2) {
2531             // If the multiply has more than two operands, we must get the
2532             // Y*Z term.
2533             SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2534                                                 Mul->op_begin()+MulOp);
2535             MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2536             InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2537           }
2538           SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul};
2539           const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2540           const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV,
2541                                             SCEV::FlagAnyWrap, Depth + 1);
2542           if (Ops.size() == 2) return OuterMul;
2543           if (AddOp < Idx) {
2544             Ops.erase(Ops.begin()+AddOp);
2545             Ops.erase(Ops.begin()+Idx-1);
2546           } else {
2547             Ops.erase(Ops.begin()+Idx);
2548             Ops.erase(Ops.begin()+AddOp-1);
2549           }
2550           Ops.push_back(OuterMul);
2551           return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2552         }
2553 
2554       // Check this multiply against other multiplies being added together.
2555       for (unsigned OtherMulIdx = Idx+1;
2556            OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2557            ++OtherMulIdx) {
2558         const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
2559         // If MulOp occurs in OtherMul, we can fold the two multiplies
2560         // together.
2561         for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2562              OMulOp != e; ++OMulOp)
2563           if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2564             // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
2565             const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
2566             if (Mul->getNumOperands() != 2) {
2567               SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2568                                                   Mul->op_begin()+MulOp);
2569               MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2570               InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2571             }
2572             const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
2573             if (OtherMul->getNumOperands() != 2) {
2574               SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
2575                                                   OtherMul->op_begin()+OMulOp);
2576               MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
2577               InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2578             }
2579             SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2};
2580             const SCEV *InnerMulSum =
2581                 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2582             const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum,
2583                                               SCEV::FlagAnyWrap, Depth + 1);
2584             if (Ops.size() == 2) return OuterMul;
2585             Ops.erase(Ops.begin()+Idx);
2586             Ops.erase(Ops.begin()+OtherMulIdx-1);
2587             Ops.push_back(OuterMul);
2588             return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2589           }
2590       }
2591     }
2592   }
2593 
2594   // If there are any add recurrences in the operands list, see if any other
2595   // added values are loop invariant.  If so, we can fold them into the
2596   // recurrence.
2597   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2598     ++Idx;
2599 
2600   // Scan over all recurrences, trying to fold loop invariants into them.
2601   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2602     // Scan all of the other operands to this add and add them to the vector if
2603     // they are loop invariant w.r.t. the recurrence.
2604     SmallVector<const SCEV *, 8> LIOps;
2605     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2606     const Loop *AddRecLoop = AddRec->getLoop();
2607     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2608       if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2609         LIOps.push_back(Ops[i]);
2610         Ops.erase(Ops.begin()+i);
2611         --i; --e;
2612       }
2613 
2614     // If we found some loop invariants, fold them into the recurrence.
2615     if (!LIOps.empty()) {
2616       // Compute nowrap flags for the addition of the loop-invariant ops and
2617       // the addrec. Temporarily push it as an operand for that purpose.
2618       LIOps.push_back(AddRec);
2619       SCEV::NoWrapFlags Flags = ComputeFlags(LIOps);
2620       LIOps.pop_back();
2621 
2622       //  NLI + LI + {Start,+,Step}  -->  NLI + {LI+Start,+,Step}
2623       LIOps.push_back(AddRec->getStart());
2624 
2625       SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands());
2626       // This follows from the fact that the no-wrap flags on the outer add
2627       // expression are applicable on the 0th iteration, when the add recurrence
2628       // will be equal to its start value.
2629       AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1);
2630 
2631       // Build the new addrec. Propagate the NUW and NSW flags if both the
2632       // outer add and the inner addrec are guaranteed to have no overflow.
2633       // Always propagate NW.
2634       Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2635       const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2636 
2637       // If all of the other operands were loop invariant, we are done.
2638       if (Ops.size() == 1) return NewRec;
2639 
2640       // Otherwise, add the folded AddRec by the non-invariant parts.
2641       for (unsigned i = 0;; ++i)
2642         if (Ops[i] == AddRec) {
2643           Ops[i] = NewRec;
2644           break;
2645         }
2646       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2647     }
2648 
2649     // Okay, if there weren't any loop invariants to be folded, check to see if
2650     // there are multiple AddRec's with the same loop induction variable being
2651     // added together.  If so, we can fold them.
2652     for (unsigned OtherIdx = Idx+1;
2653          OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2654          ++OtherIdx) {
2655       // We expect the AddRecExpr's to be sorted in reverse dominance order,
2656       // so that the 1st found AddRecExpr is dominated by all others.
2657       assert(DT.dominates(
2658            cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
2659            AddRec->getLoop()->getHeader()) &&
2660         "AddRecExprs are not sorted in reverse dominance order?");
2661       if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2662         // Other + {A,+,B}<L> + {C,+,D}<L>  -->  Other + {A+C,+,B+D}<L>
2663         SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands());
2664         for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2665              ++OtherIdx) {
2666           const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2667           if (OtherAddRec->getLoop() == AddRecLoop) {
2668             for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2669                  i != e; ++i) {
2670               if (i >= AddRecOps.size()) {
2671                 AddRecOps.append(OtherAddRec->op_begin()+i,
2672                                  OtherAddRec->op_end());
2673                 break;
2674               }
2675               SmallVector<const SCEV *, 2> TwoOps = {
2676                   AddRecOps[i], OtherAddRec->getOperand(i)};
2677               AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2678             }
2679             Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2680           }
2681         }
2682         // Step size has changed, so we cannot guarantee no self-wraparound.
2683         Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2684         return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2685       }
2686     }
2687 
2688     // Otherwise couldn't fold anything into this recurrence.  Move onto the
2689     // next one.
2690   }
2691 
2692   // Okay, it looks like we really DO need an add expr.  Check to see if we
2693   // already have one, otherwise create a new one.
2694   return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
2695 }
2696 
2697 const SCEV *
2698 ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops,
2699                                     SCEV::NoWrapFlags Flags) {
2700   FoldingSetNodeID ID;
2701   ID.AddInteger(scAddExpr);
2702   for (const SCEV *Op : Ops)
2703     ID.AddPointer(Op);
2704   void *IP = nullptr;
2705   SCEVAddExpr *S =
2706       static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2707   if (!S) {
2708     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2709     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2710     S = new (SCEVAllocator)
2711         SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
2712     UniqueSCEVs.InsertNode(S, IP);
2713     addToLoopUseLists(S);
2714   }
2715   S->setNoWrapFlags(Flags);
2716   return S;
2717 }
2718 
2719 const SCEV *
2720 ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops,
2721                                        const Loop *L, SCEV::NoWrapFlags Flags) {
2722   FoldingSetNodeID ID;
2723   ID.AddInteger(scAddRecExpr);
2724   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2725     ID.AddPointer(Ops[i]);
2726   ID.AddPointer(L);
2727   void *IP = nullptr;
2728   SCEVAddRecExpr *S =
2729       static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2730   if (!S) {
2731     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2732     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2733     S = new (SCEVAllocator)
2734         SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L);
2735     UniqueSCEVs.InsertNode(S, IP);
2736     addToLoopUseLists(S);
2737   }
2738   setNoWrapFlags(S, Flags);
2739   return S;
2740 }
2741 
2742 const SCEV *
2743 ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops,
2744                                     SCEV::NoWrapFlags Flags) {
2745   FoldingSetNodeID ID;
2746   ID.AddInteger(scMulExpr);
2747   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2748     ID.AddPointer(Ops[i]);
2749   void *IP = nullptr;
2750   SCEVMulExpr *S =
2751     static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2752   if (!S) {
2753     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2754     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2755     S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2756                                         O, Ops.size());
2757     UniqueSCEVs.InsertNode(S, IP);
2758     addToLoopUseLists(S);
2759   }
2760   S->setNoWrapFlags(Flags);
2761   return S;
2762 }
2763 
2764 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2765   uint64_t k = i*j;
2766   if (j > 1 && k / j != i) Overflow = true;
2767   return k;
2768 }
2769 
2770 /// Compute the result of "n choose k", the binomial coefficient.  If an
2771 /// intermediate computation overflows, Overflow will be set and the return will
2772 /// be garbage. Overflow is not cleared on absence of overflow.
2773 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2774   // We use the multiplicative formula:
2775   //     n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2776   // At each iteration, we take the n-th term of the numeral and divide by the
2777   // (k-n)th term of the denominator.  This division will always produce an
2778   // integral result, and helps reduce the chance of overflow in the
2779   // intermediate computations. However, we can still overflow even when the
2780   // final result would fit.
2781 
2782   if (n == 0 || n == k) return 1;
2783   if (k > n) return 0;
2784 
2785   if (k > n/2)
2786     k = n-k;
2787 
2788   uint64_t r = 1;
2789   for (uint64_t i = 1; i <= k; ++i) {
2790     r = umul_ov(r, n-(i-1), Overflow);
2791     r /= i;
2792   }
2793   return r;
2794 }
2795 
2796 /// Determine if any of the operands in this SCEV are a constant or if
2797 /// any of the add or multiply expressions in this SCEV contain a constant.
2798 static bool containsConstantInAddMulChain(const SCEV *StartExpr) {
2799   struct FindConstantInAddMulChain {
2800     bool FoundConstant = false;
2801 
2802     bool follow(const SCEV *S) {
2803       FoundConstant |= isa<SCEVConstant>(S);
2804       return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
2805     }
2806 
2807     bool isDone() const {
2808       return FoundConstant;
2809     }
2810   };
2811 
2812   FindConstantInAddMulChain F;
2813   SCEVTraversal<FindConstantInAddMulChain> ST(F);
2814   ST.visitAll(StartExpr);
2815   return F.FoundConstant;
2816 }
2817 
2818 /// Get a canonical multiply expression, or something simpler if possible.
2819 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
2820                                         SCEV::NoWrapFlags OrigFlags,
2821                                         unsigned Depth) {
2822   assert(OrigFlags == maskFlags(OrigFlags, SCEV::FlagNUW | SCEV::FlagNSW) &&
2823          "only nuw or nsw allowed");
2824   assert(!Ops.empty() && "Cannot get empty mul!");
2825   if (Ops.size() == 1) return Ops[0];
2826 #ifndef NDEBUG
2827   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2828   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2829     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2830            "SCEVMulExpr operand types don't match!");
2831 #endif
2832 
2833   // Sort by complexity, this groups all similar expression types together.
2834   GroupByComplexity(Ops, &LI, DT);
2835 
2836   // If there are any constants, fold them together.
2837   unsigned Idx = 0;
2838   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2839     ++Idx;
2840     assert(Idx < Ops.size());
2841     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2842       // We found two constants, fold them together!
2843       Ops[0] = getConstant(LHSC->getAPInt() * RHSC->getAPInt());
2844       if (Ops.size() == 2) return Ops[0];
2845       Ops.erase(Ops.begin()+1);  // Erase the folded element
2846       LHSC = cast<SCEVConstant>(Ops[0]);
2847     }
2848 
2849     // If we have a multiply of zero, it will always be zero.
2850     if (LHSC->getValue()->isZero())
2851       return LHSC;
2852 
2853     // If we are left with a constant one being multiplied, strip it off.
2854     if (LHSC->getValue()->isOne()) {
2855       Ops.erase(Ops.begin());
2856       --Idx;
2857     }
2858 
2859     if (Ops.size() == 1)
2860       return Ops[0];
2861   }
2862 
2863   // Delay expensive flag strengthening until necessary.
2864   auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) {
2865     return StrengthenNoWrapFlags(this, scMulExpr, Ops, OrigFlags);
2866   };
2867 
2868   // Limit recursion calls depth.
2869   if (Depth > MaxArithDepth || hasHugeExpression(Ops))
2870     return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
2871 
2872   if (SCEV *S = std::get<0>(findExistingSCEVInCache(scMulExpr, Ops))) {
2873     // Don't strengthen flags if we have no new information.
2874     SCEVMulExpr *Mul = static_cast<SCEVMulExpr *>(S);
2875     if (Mul->getNoWrapFlags(OrigFlags) != OrigFlags)
2876       Mul->setNoWrapFlags(ComputeFlags(Ops));
2877     return S;
2878   }
2879 
2880   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2881     if (Ops.size() == 2) {
2882       // C1*(C2+V) -> C1*C2 + C1*V
2883       if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
2884         // If any of Add's ops are Adds or Muls with a constant, apply this
2885         // transformation as well.
2886         //
2887         // TODO: There are some cases where this transformation is not
2888         // profitable; for example, Add = (C0 + X) * Y + Z.  Maybe the scope of
2889         // this transformation should be narrowed down.
2890         if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add))
2891           return getAddExpr(getMulExpr(LHSC, Add->getOperand(0),
2892                                        SCEV::FlagAnyWrap, Depth + 1),
2893                             getMulExpr(LHSC, Add->getOperand(1),
2894                                        SCEV::FlagAnyWrap, Depth + 1),
2895                             SCEV::FlagAnyWrap, Depth + 1);
2896 
2897       if (Ops[0]->isAllOnesValue()) {
2898         // If we have a mul by -1 of an add, try distributing the -1 among the
2899         // add operands.
2900         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
2901           SmallVector<const SCEV *, 4> NewOps;
2902           bool AnyFolded = false;
2903           for (const SCEV *AddOp : Add->operands()) {
2904             const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap,
2905                                          Depth + 1);
2906             if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
2907             NewOps.push_back(Mul);
2908           }
2909           if (AnyFolded)
2910             return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1);
2911         } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
2912           // Negation preserves a recurrence's no self-wrap property.
2913           SmallVector<const SCEV *, 4> Operands;
2914           for (const SCEV *AddRecOp : AddRec->operands())
2915             Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap,
2916                                           Depth + 1));
2917 
2918           return getAddRecExpr(Operands, AddRec->getLoop(),
2919                                AddRec->getNoWrapFlags(SCEV::FlagNW));
2920         }
2921       }
2922     }
2923   }
2924 
2925   // Skip over the add expression until we get to a multiply.
2926   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2927     ++Idx;
2928 
2929   // If there are mul operands inline them all into this expression.
2930   if (Idx < Ops.size()) {
2931     bool DeletedMul = false;
2932     while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2933       if (Ops.size() > MulOpsInlineThreshold)
2934         break;
2935       // If we have an mul, expand the mul operands onto the end of the
2936       // operands list.
2937       Ops.erase(Ops.begin()+Idx);
2938       Ops.append(Mul->op_begin(), Mul->op_end());
2939       DeletedMul = true;
2940     }
2941 
2942     // If we deleted at least one mul, we added operands to the end of the
2943     // list, and they are not necessarily sorted.  Recurse to resort and
2944     // resimplify any operands we just acquired.
2945     if (DeletedMul)
2946       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2947   }
2948 
2949   // If there are any add recurrences in the operands list, see if any other
2950   // added values are loop invariant.  If so, we can fold them into the
2951   // recurrence.
2952   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2953     ++Idx;
2954 
2955   // Scan over all recurrences, trying to fold loop invariants into them.
2956   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2957     // Scan all of the other operands to this mul and add them to the vector
2958     // if they are loop invariant w.r.t. the recurrence.
2959     SmallVector<const SCEV *, 8> LIOps;
2960     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2961     const Loop *AddRecLoop = AddRec->getLoop();
2962     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2963       if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2964         LIOps.push_back(Ops[i]);
2965         Ops.erase(Ops.begin()+i);
2966         --i; --e;
2967       }
2968 
2969     // If we found some loop invariants, fold them into the recurrence.
2970     if (!LIOps.empty()) {
2971       //  NLI * LI * {Start,+,Step}  -->  NLI * {LI*Start,+,LI*Step}
2972       SmallVector<const SCEV *, 4> NewOps;
2973       NewOps.reserve(AddRec->getNumOperands());
2974       const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1);
2975       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
2976         NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
2977                                     SCEV::FlagAnyWrap, Depth + 1));
2978 
2979       // Build the new addrec. Propagate the NUW and NSW flags if both the
2980       // outer mul and the inner addrec are guaranteed to have no overflow.
2981       //
2982       // No self-wrap cannot be guaranteed after changing the step size, but
2983       // will be inferred if either NUW or NSW is true.
2984       SCEV::NoWrapFlags Flags = ComputeFlags({Scale, AddRec});
2985       const SCEV *NewRec = getAddRecExpr(
2986           NewOps, AddRecLoop, AddRec->getNoWrapFlags(Flags));
2987 
2988       // If all of the other operands were loop invariant, we are done.
2989       if (Ops.size() == 1) return NewRec;
2990 
2991       // Otherwise, multiply the folded AddRec by the non-invariant parts.
2992       for (unsigned i = 0;; ++i)
2993         if (Ops[i] == AddRec) {
2994           Ops[i] = NewRec;
2995           break;
2996         }
2997       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2998     }
2999 
3000     // Okay, if there weren't any loop invariants to be folded, check to see
3001     // if there are multiple AddRec's with the same loop induction variable
3002     // being multiplied together.  If so, we can fold them.
3003 
3004     // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
3005     // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
3006     //       choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
3007     //   ]]],+,...up to x=2n}.
3008     // Note that the arguments to choose() are always integers with values
3009     // known at compile time, never SCEV objects.
3010     //
3011     // The implementation avoids pointless extra computations when the two
3012     // addrec's are of different length (mathematically, it's equivalent to
3013     // an infinite stream of zeros on the right).
3014     bool OpsModified = false;
3015     for (unsigned OtherIdx = Idx+1;
3016          OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
3017          ++OtherIdx) {
3018       const SCEVAddRecExpr *OtherAddRec =
3019         dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
3020       if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
3021         continue;
3022 
3023       // Limit max number of arguments to avoid creation of unreasonably big
3024       // SCEVAddRecs with very complex operands.
3025       if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
3026           MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec}))
3027         continue;
3028 
3029       bool Overflow = false;
3030       Type *Ty = AddRec->getType();
3031       bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
3032       SmallVector<const SCEV*, 7> AddRecOps;
3033       for (int x = 0, xe = AddRec->getNumOperands() +
3034              OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
3035         SmallVector <const SCEV *, 7> SumOps;
3036         for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
3037           uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
3038           for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
3039                  ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
3040                z < ze && !Overflow; ++z) {
3041             uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
3042             uint64_t Coeff;
3043             if (LargerThan64Bits)
3044               Coeff = umul_ov(Coeff1, Coeff2, Overflow);
3045             else
3046               Coeff = Coeff1*Coeff2;
3047             const SCEV *CoeffTerm = getConstant(Ty, Coeff);
3048             const SCEV *Term1 = AddRec->getOperand(y-z);
3049             const SCEV *Term2 = OtherAddRec->getOperand(z);
3050             SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2,
3051                                         SCEV::FlagAnyWrap, Depth + 1));
3052           }
3053         }
3054         if (SumOps.empty())
3055           SumOps.push_back(getZero(Ty));
3056         AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1));
3057       }
3058       if (!Overflow) {
3059         const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRecLoop,
3060                                               SCEV::FlagAnyWrap);
3061         if (Ops.size() == 2) return NewAddRec;
3062         Ops[Idx] = NewAddRec;
3063         Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
3064         OpsModified = true;
3065         AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
3066         if (!AddRec)
3067           break;
3068       }
3069     }
3070     if (OpsModified)
3071       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3072 
3073     // Otherwise couldn't fold anything into this recurrence.  Move onto the
3074     // next one.
3075   }
3076 
3077   // Okay, it looks like we really DO need an mul expr.  Check to see if we
3078   // already have one, otherwise create a new one.
3079   return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
3080 }
3081 
3082 /// Represents an unsigned remainder expression based on unsigned division.
3083 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS,
3084                                          const SCEV *RHS) {
3085   assert(getEffectiveSCEVType(LHS->getType()) ==
3086          getEffectiveSCEVType(RHS->getType()) &&
3087          "SCEVURemExpr operand types don't match!");
3088 
3089   // Short-circuit easy cases
3090   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3091     // If constant is one, the result is trivial
3092     if (RHSC->getValue()->isOne())
3093       return getZero(LHS->getType()); // X urem 1 --> 0
3094 
3095     // If constant is a power of two, fold into a zext(trunc(LHS)).
3096     if (RHSC->getAPInt().isPowerOf2()) {
3097       Type *FullTy = LHS->getType();
3098       Type *TruncTy =
3099           IntegerType::get(getContext(), RHSC->getAPInt().logBase2());
3100       return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy);
3101     }
3102   }
3103 
3104   // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
3105   const SCEV *UDiv = getUDivExpr(LHS, RHS);
3106   const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW);
3107   return getMinusSCEV(LHS, Mult, SCEV::FlagNUW);
3108 }
3109 
3110 /// Get a canonical unsigned division expression, or something simpler if
3111 /// possible.
3112 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
3113                                          const SCEV *RHS) {
3114   assert(getEffectiveSCEVType(LHS->getType()) ==
3115          getEffectiveSCEVType(RHS->getType()) &&
3116          "SCEVUDivExpr operand types don't match!");
3117 
3118   FoldingSetNodeID ID;
3119   ID.AddInteger(scUDivExpr);
3120   ID.AddPointer(LHS);
3121   ID.AddPointer(RHS);
3122   void *IP = nullptr;
3123   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
3124     return S;
3125 
3126   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3127     if (RHSC->getValue()->isOne())
3128       return LHS;                               // X udiv 1 --> x
3129     // If the denominator is zero, the result of the udiv is undefined. Don't
3130     // try to analyze it, because the resolution chosen here may differ from
3131     // the resolution chosen in other parts of the compiler.
3132     if (!RHSC->getValue()->isZero()) {
3133       // Determine if the division can be folded into the operands of
3134       // its operands.
3135       // TODO: Generalize this to non-constants by using known-bits information.
3136       Type *Ty = LHS->getType();
3137       unsigned LZ = RHSC->getAPInt().countLeadingZeros();
3138       unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
3139       // For non-power-of-two values, effectively round the value up to the
3140       // nearest power of two.
3141       if (!RHSC->getAPInt().isPowerOf2())
3142         ++MaxShiftAmt;
3143       IntegerType *ExtTy =
3144         IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
3145       if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
3146         if (const SCEVConstant *Step =
3147             dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
3148           // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
3149           const APInt &StepInt = Step->getAPInt();
3150           const APInt &DivInt = RHSC->getAPInt();
3151           if (!StepInt.urem(DivInt) &&
3152               getZeroExtendExpr(AR, ExtTy) ==
3153               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3154                             getZeroExtendExpr(Step, ExtTy),
3155                             AR->getLoop(), SCEV::FlagAnyWrap)) {
3156             SmallVector<const SCEV *, 4> Operands;
3157             for (const SCEV *Op : AR->operands())
3158               Operands.push_back(getUDivExpr(Op, RHS));
3159             return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
3160           }
3161           /// Get a canonical UDivExpr for a recurrence.
3162           /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
3163           // We can currently only fold X%N if X is constant.
3164           const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
3165           if (StartC && !DivInt.urem(StepInt) &&
3166               getZeroExtendExpr(AR, ExtTy) ==
3167               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3168                             getZeroExtendExpr(Step, ExtTy),
3169                             AR->getLoop(), SCEV::FlagAnyWrap)) {
3170             const APInt &StartInt = StartC->getAPInt();
3171             const APInt &StartRem = StartInt.urem(StepInt);
3172             if (StartRem != 0) {
3173               const SCEV *NewLHS =
3174                   getAddRecExpr(getConstant(StartInt - StartRem), Step,
3175                                 AR->getLoop(), SCEV::FlagNW);
3176               if (LHS != NewLHS) {
3177                 LHS = NewLHS;
3178 
3179                 // Reset the ID to include the new LHS, and check if it is
3180                 // already cached.
3181                 ID.clear();
3182                 ID.AddInteger(scUDivExpr);
3183                 ID.AddPointer(LHS);
3184                 ID.AddPointer(RHS);
3185                 IP = nullptr;
3186                 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
3187                   return S;
3188               }
3189             }
3190           }
3191         }
3192       // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
3193       if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
3194         SmallVector<const SCEV *, 4> Operands;
3195         for (const SCEV *Op : M->operands())
3196           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3197         if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
3198           // Find an operand that's safely divisible.
3199           for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3200             const SCEV *Op = M->getOperand(i);
3201             const SCEV *Div = getUDivExpr(Op, RHSC);
3202             if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
3203               Operands = SmallVector<const SCEV *, 4>(M->operands());
3204               Operands[i] = Div;
3205               return getMulExpr(Operands);
3206             }
3207           }
3208       }
3209 
3210       // (A/B)/C --> A/(B*C) if safe and B*C can be folded.
3211       if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) {
3212         if (auto *DivisorConstant =
3213                 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) {
3214           bool Overflow = false;
3215           APInt NewRHS =
3216               DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow);
3217           if (Overflow) {
3218             return getConstant(RHSC->getType(), 0, false);
3219           }
3220           return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS));
3221         }
3222       }
3223 
3224       // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
3225       if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
3226         SmallVector<const SCEV *, 4> Operands;
3227         for (const SCEV *Op : A->operands())
3228           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3229         if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
3230           Operands.clear();
3231           for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
3232             const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
3233             if (isa<SCEVUDivExpr>(Op) ||
3234                 getMulExpr(Op, RHS) != A->getOperand(i))
3235               break;
3236             Operands.push_back(Op);
3237           }
3238           if (Operands.size() == A->getNumOperands())
3239             return getAddExpr(Operands);
3240         }
3241       }
3242 
3243       // Fold if both operands are constant.
3244       if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
3245         Constant *LHSCV = LHSC->getValue();
3246         Constant *RHSCV = RHSC->getValue();
3247         return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
3248                                                                    RHSCV)));
3249       }
3250     }
3251   }
3252 
3253   // The Insertion Point (IP) might be invalid by now (due to UniqueSCEVs
3254   // changes). Make sure we get a new one.
3255   IP = nullptr;
3256   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3257   SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
3258                                              LHS, RHS);
3259   UniqueSCEVs.InsertNode(S, IP);
3260   addToLoopUseLists(S);
3261   return S;
3262 }
3263 
3264 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
3265   APInt A = C1->getAPInt().abs();
3266   APInt B = C2->getAPInt().abs();
3267   uint32_t ABW = A.getBitWidth();
3268   uint32_t BBW = B.getBitWidth();
3269 
3270   if (ABW > BBW)
3271     B = B.zext(ABW);
3272   else if (ABW < BBW)
3273     A = A.zext(BBW);
3274 
3275   return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B));
3276 }
3277 
3278 /// Get a canonical unsigned division expression, or something simpler if
3279 /// possible. There is no representation for an exact udiv in SCEV IR, but we
3280 /// can attempt to remove factors from the LHS and RHS.  We can't do this when
3281 /// it's not exact because the udiv may be clearing bits.
3282 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
3283                                               const SCEV *RHS) {
3284   // TODO: we could try to find factors in all sorts of things, but for now we
3285   // just deal with u/exact (multiply, constant). See SCEVDivision towards the
3286   // end of this file for inspiration.
3287 
3288   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
3289   if (!Mul || !Mul->hasNoUnsignedWrap())
3290     return getUDivExpr(LHS, RHS);
3291 
3292   if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
3293     // If the mulexpr multiplies by a constant, then that constant must be the
3294     // first element of the mulexpr.
3295     if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
3296       if (LHSCst == RHSCst) {
3297         SmallVector<const SCEV *, 2> Operands(drop_begin(Mul->operands()));
3298         return getMulExpr(Operands);
3299       }
3300 
3301       // We can't just assume that LHSCst divides RHSCst cleanly, it could be
3302       // that there's a factor provided by one of the other terms. We need to
3303       // check.
3304       APInt Factor = gcd(LHSCst, RHSCst);
3305       if (!Factor.isIntN(1)) {
3306         LHSCst =
3307             cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
3308         RHSCst =
3309             cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
3310         SmallVector<const SCEV *, 2> Operands;
3311         Operands.push_back(LHSCst);
3312         Operands.append(Mul->op_begin() + 1, Mul->op_end());
3313         LHS = getMulExpr(Operands);
3314         RHS = RHSCst;
3315         Mul = dyn_cast<SCEVMulExpr>(LHS);
3316         if (!Mul)
3317           return getUDivExactExpr(LHS, RHS);
3318       }
3319     }
3320   }
3321 
3322   for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3323     if (Mul->getOperand(i) == RHS) {
3324       SmallVector<const SCEV *, 2> Operands;
3325       Operands.append(Mul->op_begin(), Mul->op_begin() + i);
3326       Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
3327       return getMulExpr(Operands);
3328     }
3329   }
3330 
3331   return getUDivExpr(LHS, RHS);
3332 }
3333 
3334 /// Get an add recurrence expression for the specified loop.  Simplify the
3335 /// expression as much as possible.
3336 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
3337                                            const Loop *L,
3338                                            SCEV::NoWrapFlags Flags) {
3339   SmallVector<const SCEV *, 4> Operands;
3340   Operands.push_back(Start);
3341   if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3342     if (StepChrec->getLoop() == L) {
3343       Operands.append(StepChrec->op_begin(), StepChrec->op_end());
3344       return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
3345     }
3346 
3347   Operands.push_back(Step);
3348   return getAddRecExpr(Operands, L, Flags);
3349 }
3350 
3351 /// Get an add recurrence expression for the specified loop.  Simplify the
3352 /// expression as much as possible.
3353 const SCEV *
3354 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
3355                                const Loop *L, SCEV::NoWrapFlags Flags) {
3356   if (Operands.size() == 1) return Operands[0];
3357 #ifndef NDEBUG
3358   Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
3359   for (unsigned i = 1, e = Operands.size(); i != e; ++i)
3360     assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
3361            "SCEVAddRecExpr operand types don't match!");
3362   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3363     assert(isLoopInvariant(Operands[i], L) &&
3364            "SCEVAddRecExpr operand is not loop-invariant!");
3365 #endif
3366 
3367   if (Operands.back()->isZero()) {
3368     Operands.pop_back();
3369     return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0}  -->  X
3370   }
3371 
3372   // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and
3373   // use that information to infer NUW and NSW flags. However, computing a
3374   // BE count requires calling getAddRecExpr, so we may not yet have a
3375   // meaningful BE count at this point (and if we don't, we'd be stuck
3376   // with a SCEVCouldNotCompute as the cached BE count).
3377 
3378   Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
3379 
3380   // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3381   if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3382     const Loop *NestedLoop = NestedAR->getLoop();
3383     if (L->contains(NestedLoop)
3384             ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3385             : (!NestedLoop->contains(L) &&
3386                DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3387       SmallVector<const SCEV *, 4> NestedOperands(NestedAR->operands());
3388       Operands[0] = NestedAR->getStart();
3389       // AddRecs require their operands be loop-invariant with respect to their
3390       // loops. Don't perform this transformation if it would break this
3391       // requirement.
3392       bool AllInvariant = all_of(
3393           Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3394 
3395       if (AllInvariant) {
3396         // Create a recurrence for the outer loop with the same step size.
3397         //
3398         // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3399         // inner recurrence has the same property.
3400         SCEV::NoWrapFlags OuterFlags =
3401           maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3402 
3403         NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3404         AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3405           return isLoopInvariant(Op, NestedLoop);
3406         });
3407 
3408         if (AllInvariant) {
3409           // Ok, both add recurrences are valid after the transformation.
3410           //
3411           // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3412           // the outer recurrence has the same property.
3413           SCEV::NoWrapFlags InnerFlags =
3414             maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
3415           return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3416         }
3417       }
3418       // Reset Operands to its original state.
3419       Operands[0] = NestedAR;
3420     }
3421   }
3422 
3423   // Okay, it looks like we really DO need an addrec expr.  Check to see if we
3424   // already have one, otherwise create a new one.
3425   return getOrCreateAddRecExpr(Operands, L, Flags);
3426 }
3427 
3428 const SCEV *
3429 ScalarEvolution::getGEPExpr(GEPOperator *GEP,
3430                             const SmallVectorImpl<const SCEV *> &IndexExprs) {
3431   const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3432   // getSCEV(Base)->getType() has the same address space as Base->getType()
3433   // because SCEV::getType() preserves the address space.
3434   Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType());
3435   // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP
3436   // instruction to its SCEV, because the Instruction may be guarded by control
3437   // flow and the no-overflow bits may not be valid for the expression in any
3438   // context. This can be fixed similarly to how these flags are handled for
3439   // adds.
3440   SCEV::NoWrapFlags OffsetWrap =
3441       GEP->isInBounds() ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3442 
3443   Type *CurTy = GEP->getType();
3444   bool FirstIter = true;
3445   SmallVector<const SCEV *, 4> Offsets;
3446   for (const SCEV *IndexExpr : IndexExprs) {
3447     // Compute the (potentially symbolic) offset in bytes for this index.
3448     if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3449       // For a struct, add the member offset.
3450       ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3451       unsigned FieldNo = Index->getZExtValue();
3452       const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo);
3453       Offsets.push_back(FieldOffset);
3454 
3455       // Update CurTy to the type of the field at Index.
3456       CurTy = STy->getTypeAtIndex(Index);
3457     } else {
3458       // Update CurTy to its element type.
3459       if (FirstIter) {
3460         assert(isa<PointerType>(CurTy) &&
3461                "The first index of a GEP indexes a pointer");
3462         CurTy = GEP->getSourceElementType();
3463         FirstIter = false;
3464       } else {
3465         CurTy = GetElementPtrInst::getTypeAtIndex(CurTy, (uint64_t)0);
3466       }
3467       // For an array, add the element offset, explicitly scaled.
3468       const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy);
3469       // Getelementptr indices are signed.
3470       IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy);
3471 
3472       // Multiply the index by the element size to compute the element offset.
3473       const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, OffsetWrap);
3474       Offsets.push_back(LocalOffset);
3475     }
3476   }
3477 
3478   // Handle degenerate case of GEP without offsets.
3479   if (Offsets.empty())
3480     return BaseExpr;
3481 
3482   // Add the offsets together, assuming nsw if inbounds.
3483   const SCEV *Offset = getAddExpr(Offsets, OffsetWrap);
3484   // Add the base address and the offset. We cannot use the nsw flag, as the
3485   // base address is unsigned. However, if we know that the offset is
3486   // non-negative, we can use nuw.
3487   SCEV::NoWrapFlags BaseWrap = GEP->isInBounds() && isKnownNonNegative(Offset)
3488                                    ? SCEV::FlagNUW : SCEV::FlagAnyWrap;
3489   return getAddExpr(BaseExpr, Offset, BaseWrap);
3490 }
3491 
3492 std::tuple<SCEV *, FoldingSetNodeID, void *>
3493 ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType,
3494                                          ArrayRef<const SCEV *> Ops) {
3495   FoldingSetNodeID ID;
3496   void *IP = nullptr;
3497   ID.AddInteger(SCEVType);
3498   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3499     ID.AddPointer(Ops[i]);
3500   return std::tuple<SCEV *, FoldingSetNodeID, void *>(
3501       UniqueSCEVs.FindNodeOrInsertPos(ID, IP), std::move(ID), IP);
3502 }
3503 
3504 const SCEV *ScalarEvolution::getAbsExpr(const SCEV *Op, bool IsNSW) {
3505   SCEV::NoWrapFlags Flags = IsNSW ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3506   return getSMaxExpr(Op, getNegativeSCEV(Op, Flags));
3507 }
3508 
3509 const SCEV *ScalarEvolution::getMinMaxExpr(SCEVTypes Kind,
3510                                            SmallVectorImpl<const SCEV *> &Ops) {
3511   assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
3512   if (Ops.size() == 1) return Ops[0];
3513 #ifndef NDEBUG
3514   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3515   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3516     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3517            "Operand types don't match!");
3518 #endif
3519 
3520   bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr;
3521   bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr;
3522 
3523   // Sort by complexity, this groups all similar expression types together.
3524   GroupByComplexity(Ops, &LI, DT);
3525 
3526   // Check if we have created the same expression before.
3527   if (const SCEV *S = std::get<0>(findExistingSCEVInCache(Kind, Ops))) {
3528     return S;
3529   }
3530 
3531   // If there are any constants, fold them together.
3532   unsigned Idx = 0;
3533   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3534     ++Idx;
3535     assert(Idx < Ops.size());
3536     auto FoldOp = [&](const APInt &LHS, const APInt &RHS) {
3537       if (Kind == scSMaxExpr)
3538         return APIntOps::smax(LHS, RHS);
3539       else if (Kind == scSMinExpr)
3540         return APIntOps::smin(LHS, RHS);
3541       else if (Kind == scUMaxExpr)
3542         return APIntOps::umax(LHS, RHS);
3543       else if (Kind == scUMinExpr)
3544         return APIntOps::umin(LHS, RHS);
3545       llvm_unreachable("Unknown SCEV min/max opcode");
3546     };
3547 
3548     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3549       // We found two constants, fold them together!
3550       ConstantInt *Fold = ConstantInt::get(
3551           getContext(), FoldOp(LHSC->getAPInt(), RHSC->getAPInt()));
3552       Ops[0] = getConstant(Fold);
3553       Ops.erase(Ops.begin()+1);  // Erase the folded element
3554       if (Ops.size() == 1) return Ops[0];
3555       LHSC = cast<SCEVConstant>(Ops[0]);
3556     }
3557 
3558     bool IsMinV = LHSC->getValue()->isMinValue(IsSigned);
3559     bool IsMaxV = LHSC->getValue()->isMaxValue(IsSigned);
3560 
3561     if (IsMax ? IsMinV : IsMaxV) {
3562       // If we are left with a constant minimum(/maximum)-int, strip it off.
3563       Ops.erase(Ops.begin());
3564       --Idx;
3565     } else if (IsMax ? IsMaxV : IsMinV) {
3566       // If we have a max(/min) with a constant maximum(/minimum)-int,
3567       // it will always be the extremum.
3568       return LHSC;
3569     }
3570 
3571     if (Ops.size() == 1) return Ops[0];
3572   }
3573 
3574   // Find the first operation of the same kind
3575   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind)
3576     ++Idx;
3577 
3578   // Check to see if one of the operands is of the same kind. If so, expand its
3579   // operands onto our operand list, and recurse to simplify.
3580   if (Idx < Ops.size()) {
3581     bool DeletedAny = false;
3582     while (Ops[Idx]->getSCEVType() == Kind) {
3583       const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]);
3584       Ops.erase(Ops.begin()+Idx);
3585       Ops.append(SMME->op_begin(), SMME->op_end());
3586       DeletedAny = true;
3587     }
3588 
3589     if (DeletedAny)
3590       return getMinMaxExpr(Kind, Ops);
3591   }
3592 
3593   // Okay, check to see if the same value occurs in the operand list twice.  If
3594   // so, delete one.  Since we sorted the list, these values are required to
3595   // be adjacent.
3596   llvm::CmpInst::Predicate GEPred =
3597       IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
3598   llvm::CmpInst::Predicate LEPred =
3599       IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
3600   llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred;
3601   llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred;
3602   for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) {
3603     if (Ops[i] == Ops[i + 1] ||
3604         isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) {
3605       //  X op Y op Y  -->  X op Y
3606       //  X op Y       -->  X, if we know X, Y are ordered appropriately
3607       Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2);
3608       --i;
3609       --e;
3610     } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i],
3611                                                Ops[i + 1])) {
3612       //  X op Y       -->  Y, if we know X, Y are ordered appropriately
3613       Ops.erase(Ops.begin() + i, Ops.begin() + i + 1);
3614       --i;
3615       --e;
3616     }
3617   }
3618 
3619   if (Ops.size() == 1) return Ops[0];
3620 
3621   assert(!Ops.empty() && "Reduced smax down to nothing!");
3622 
3623   // Okay, it looks like we really DO need an expr.  Check to see if we
3624   // already have one, otherwise create a new one.
3625   const SCEV *ExistingSCEV;
3626   FoldingSetNodeID ID;
3627   void *IP;
3628   std::tie(ExistingSCEV, ID, IP) = findExistingSCEVInCache(Kind, Ops);
3629   if (ExistingSCEV)
3630     return ExistingSCEV;
3631   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3632   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3633   SCEV *S = new (SCEVAllocator)
3634       SCEVMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
3635 
3636   UniqueSCEVs.InsertNode(S, IP);
3637   addToLoopUseLists(S);
3638   return S;
3639 }
3640 
3641 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) {
3642   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3643   return getSMaxExpr(Ops);
3644 }
3645 
3646 const SCEV *ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3647   return getMinMaxExpr(scSMaxExpr, Ops);
3648 }
3649 
3650 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) {
3651   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3652   return getUMaxExpr(Ops);
3653 }
3654 
3655 const SCEV *ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3656   return getMinMaxExpr(scUMaxExpr, Ops);
3657 }
3658 
3659 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
3660                                          const SCEV *RHS) {
3661   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
3662   return getSMinExpr(Ops);
3663 }
3664 
3665 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) {
3666   return getMinMaxExpr(scSMinExpr, Ops);
3667 }
3668 
3669 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
3670                                          const SCEV *RHS) {
3671   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
3672   return getUMinExpr(Ops);
3673 }
3674 
3675 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops) {
3676   return getMinMaxExpr(scUMinExpr, Ops);
3677 }
3678 
3679 const SCEV *
3680 ScalarEvolution::getSizeOfScalableVectorExpr(Type *IntTy,
3681                                              ScalableVectorType *ScalableTy) {
3682   Constant *NullPtr = Constant::getNullValue(ScalableTy->getPointerTo());
3683   Constant *One = ConstantInt::get(IntTy, 1);
3684   Constant *GEP = ConstantExpr::getGetElementPtr(ScalableTy, NullPtr, One);
3685   // Note that the expression we created is the final expression, we don't
3686   // want to simplify it any further Also, if we call a normal getSCEV(),
3687   // we'll end up in an endless recursion. So just create an SCEVUnknown.
3688   return getUnknown(ConstantExpr::getPtrToInt(GEP, IntTy));
3689 }
3690 
3691 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
3692   if (auto *ScalableAllocTy = dyn_cast<ScalableVectorType>(AllocTy))
3693     return getSizeOfScalableVectorExpr(IntTy, ScalableAllocTy);
3694   // We can bypass creating a target-independent constant expression and then
3695   // folding it back into a ConstantInt. This is just a compile-time
3696   // optimization.
3697   return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
3698 }
3699 
3700 const SCEV *ScalarEvolution::getStoreSizeOfExpr(Type *IntTy, Type *StoreTy) {
3701   if (auto *ScalableStoreTy = dyn_cast<ScalableVectorType>(StoreTy))
3702     return getSizeOfScalableVectorExpr(IntTy, ScalableStoreTy);
3703   // We can bypass creating a target-independent constant expression and then
3704   // folding it back into a ConstantInt. This is just a compile-time
3705   // optimization.
3706   return getConstant(IntTy, getDataLayout().getTypeStoreSize(StoreTy));
3707 }
3708 
3709 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
3710                                              StructType *STy,
3711                                              unsigned FieldNo) {
3712   // We can bypass creating a target-independent constant expression and then
3713   // folding it back into a ConstantInt. This is just a compile-time
3714   // optimization.
3715   return getConstant(
3716       IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
3717 }
3718 
3719 const SCEV *ScalarEvolution::getUnknown(Value *V) {
3720   // Don't attempt to do anything other than create a SCEVUnknown object
3721   // here.  createSCEV only calls getUnknown after checking for all other
3722   // interesting possibilities, and any other code that calls getUnknown
3723   // is doing so in order to hide a value from SCEV canonicalization.
3724 
3725   FoldingSetNodeID ID;
3726   ID.AddInteger(scUnknown);
3727   ID.AddPointer(V);
3728   void *IP = nullptr;
3729   if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3730     assert(cast<SCEVUnknown>(S)->getValue() == V &&
3731            "Stale SCEVUnknown in uniquing map!");
3732     return S;
3733   }
3734   SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3735                                             FirstUnknown);
3736   FirstUnknown = cast<SCEVUnknown>(S);
3737   UniqueSCEVs.InsertNode(S, IP);
3738   return S;
3739 }
3740 
3741 //===----------------------------------------------------------------------===//
3742 //            Basic SCEV Analysis and PHI Idiom Recognition Code
3743 //
3744 
3745 /// Test if values of the given type are analyzable within the SCEV
3746 /// framework. This primarily includes integer types, and it can optionally
3747 /// include pointer types if the ScalarEvolution class has access to
3748 /// target-specific information.
3749 bool ScalarEvolution::isSCEVable(Type *Ty) const {
3750   // Integers and pointers are always SCEVable.
3751   return Ty->isIntOrPtrTy();
3752 }
3753 
3754 /// Return the size in bits of the specified type, for which isSCEVable must
3755 /// return true.
3756 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
3757   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3758   if (Ty->isPointerTy())
3759     return getDataLayout().getIndexTypeSizeInBits(Ty);
3760   return getDataLayout().getTypeSizeInBits(Ty);
3761 }
3762 
3763 /// Return a type with the same bitwidth as the given type and which represents
3764 /// how SCEV will treat the given type, for which isSCEVable must return
3765 /// true. For pointer types, this is the pointer index sized integer type.
3766 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
3767   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3768 
3769   if (Ty->isIntegerTy())
3770     return Ty;
3771 
3772   // The only other support type is pointer.
3773   assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
3774   return getDataLayout().getIndexType(Ty);
3775 }
3776 
3777 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const {
3778   return  getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
3779 }
3780 
3781 const SCEV *ScalarEvolution::getCouldNotCompute() {
3782   return CouldNotCompute.get();
3783 }
3784 
3785 bool ScalarEvolution::checkValidity(const SCEV *S) const {
3786   bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
3787     auto *SU = dyn_cast<SCEVUnknown>(S);
3788     return SU && SU->getValue() == nullptr;
3789   });
3790 
3791   return !ContainsNulls;
3792 }
3793 
3794 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
3795   HasRecMapType::iterator I = HasRecMap.find(S);
3796   if (I != HasRecMap.end())
3797     return I->second;
3798 
3799   bool FoundAddRec =
3800       SCEVExprContains(S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); });
3801   HasRecMap.insert({S, FoundAddRec});
3802   return FoundAddRec;
3803 }
3804 
3805 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}.
3806 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an
3807 /// offset I, then return {S', I}, else return {\p S, nullptr}.
3808 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) {
3809   const auto *Add = dyn_cast<SCEVAddExpr>(S);
3810   if (!Add)
3811     return {S, nullptr};
3812 
3813   if (Add->getNumOperands() != 2)
3814     return {S, nullptr};
3815 
3816   auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0));
3817   if (!ConstOp)
3818     return {S, nullptr};
3819 
3820   return {Add->getOperand(1), ConstOp->getValue()};
3821 }
3822 
3823 /// Return the ValueOffsetPair set for \p S. \p S can be represented
3824 /// by the value and offset from any ValueOffsetPair in the set.
3825 SetVector<ScalarEvolution::ValueOffsetPair> *
3826 ScalarEvolution::getSCEVValues(const SCEV *S) {
3827   ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
3828   if (SI == ExprValueMap.end())
3829     return nullptr;
3830 #ifndef NDEBUG
3831   if (VerifySCEVMap) {
3832     // Check there is no dangling Value in the set returned.
3833     for (const auto &VE : SI->second)
3834       assert(ValueExprMap.count(VE.first));
3835   }
3836 #endif
3837   return &SI->second;
3838 }
3839 
3840 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
3841 /// cannot be used separately. eraseValueFromMap should be used to remove
3842 /// V from ValueExprMap and ExprValueMap at the same time.
3843 void ScalarEvolution::eraseValueFromMap(Value *V) {
3844   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3845   if (I != ValueExprMap.end()) {
3846     const SCEV *S = I->second;
3847     // Remove {V, 0} from the set of ExprValueMap[S]
3848     if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S))
3849       SV->remove({V, nullptr});
3850 
3851     // Remove {V, Offset} from the set of ExprValueMap[Stripped]
3852     const SCEV *Stripped;
3853     ConstantInt *Offset;
3854     std::tie(Stripped, Offset) = splitAddExpr(S);
3855     if (Offset != nullptr) {
3856       if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped))
3857         SV->remove({V, Offset});
3858     }
3859     ValueExprMap.erase(V);
3860   }
3861 }
3862 
3863 /// Check whether value has nuw/nsw/exact set but SCEV does not.
3864 /// TODO: In reality it is better to check the poison recursively
3865 /// but this is better than nothing.
3866 static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) {
3867   if (auto *I = dyn_cast<Instruction>(V)) {
3868     if (isa<OverflowingBinaryOperator>(I)) {
3869       if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) {
3870         if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap())
3871           return true;
3872         if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap())
3873           return true;
3874       }
3875     } else if (isa<PossiblyExactOperator>(I) && I->isExact())
3876       return true;
3877   }
3878   return false;
3879 }
3880 
3881 /// Return an existing SCEV if it exists, otherwise analyze the expression and
3882 /// create a new one.
3883 const SCEV *ScalarEvolution::getSCEV(Value *V) {
3884   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3885 
3886   const SCEV *S = getExistingSCEV(V);
3887   if (S == nullptr) {
3888     S = createSCEV(V);
3889     // During PHI resolution, it is possible to create two SCEVs for the same
3890     // V, so it is needed to double check whether V->S is inserted into
3891     // ValueExprMap before insert S->{V, 0} into ExprValueMap.
3892     std::pair<ValueExprMapType::iterator, bool> Pair =
3893         ValueExprMap.insert({SCEVCallbackVH(V, this), S});
3894     if (Pair.second && !SCEVLostPoisonFlags(S, V)) {
3895       ExprValueMap[S].insert({V, nullptr});
3896 
3897       // If S == Stripped + Offset, add Stripped -> {V, Offset} into
3898       // ExprValueMap.
3899       const SCEV *Stripped = S;
3900       ConstantInt *Offset = nullptr;
3901       std::tie(Stripped, Offset) = splitAddExpr(S);
3902       // If stripped is SCEVUnknown, don't bother to save
3903       // Stripped -> {V, offset}. It doesn't simplify and sometimes even
3904       // increase the complexity of the expansion code.
3905       // If V is GetElementPtrInst, don't save Stripped -> {V, offset}
3906       // because it may generate add/sub instead of GEP in SCEV expansion.
3907       if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) &&
3908           !isa<GetElementPtrInst>(V))
3909         ExprValueMap[Stripped].insert({V, Offset});
3910     }
3911   }
3912   return S;
3913 }
3914 
3915 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
3916   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3917 
3918   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3919   if (I != ValueExprMap.end()) {
3920     const SCEV *S = I->second;
3921     if (checkValidity(S))
3922       return S;
3923     eraseValueFromMap(V);
3924     forgetMemoizedResults(S);
3925   }
3926   return nullptr;
3927 }
3928 
3929 /// Return a SCEV corresponding to -V = -1*V
3930 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
3931                                              SCEV::NoWrapFlags Flags) {
3932   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3933     return getConstant(
3934                cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
3935 
3936   Type *Ty = V->getType();
3937   Ty = getEffectiveSCEVType(Ty);
3938   return getMulExpr(V, getMinusOne(Ty), Flags);
3939 }
3940 
3941 /// If Expr computes ~A, return A else return nullptr
3942 static const SCEV *MatchNotExpr(const SCEV *Expr) {
3943   const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
3944   if (!Add || Add->getNumOperands() != 2 ||
3945       !Add->getOperand(0)->isAllOnesValue())
3946     return nullptr;
3947 
3948   const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
3949   if (!AddRHS || AddRHS->getNumOperands() != 2 ||
3950       !AddRHS->getOperand(0)->isAllOnesValue())
3951     return nullptr;
3952 
3953   return AddRHS->getOperand(1);
3954 }
3955 
3956 /// Return a SCEV corresponding to ~V = -1-V
3957 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
3958   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3959     return getConstant(
3960                 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
3961 
3962   // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y)
3963   if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) {
3964     auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) {
3965       SmallVector<const SCEV *, 2> MatchedOperands;
3966       for (const SCEV *Operand : MME->operands()) {
3967         const SCEV *Matched = MatchNotExpr(Operand);
3968         if (!Matched)
3969           return (const SCEV *)nullptr;
3970         MatchedOperands.push_back(Matched);
3971       }
3972       return getMinMaxExpr(SCEVMinMaxExpr::negate(MME->getSCEVType()),
3973                            MatchedOperands);
3974     };
3975     if (const SCEV *Replaced = MatchMinMaxNegation(MME))
3976       return Replaced;
3977   }
3978 
3979   Type *Ty = V->getType();
3980   Ty = getEffectiveSCEVType(Ty);
3981   return getMinusSCEV(getMinusOne(Ty), V);
3982 }
3983 
3984 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
3985                                           SCEV::NoWrapFlags Flags,
3986                                           unsigned Depth) {
3987   // Fast path: X - X --> 0.
3988   if (LHS == RHS)
3989     return getZero(LHS->getType());
3990 
3991   // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
3992   // makes it so that we cannot make much use of NUW.
3993   auto AddFlags = SCEV::FlagAnyWrap;
3994   const bool RHSIsNotMinSigned =
3995       !getSignedRangeMin(RHS).isMinSignedValue();
3996   if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) {
3997     // Let M be the minimum representable signed value. Then (-1)*RHS
3998     // signed-wraps if and only if RHS is M. That can happen even for
3999     // a NSW subtraction because e.g. (-1)*M signed-wraps even though
4000     // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
4001     // (-1)*RHS, we need to prove that RHS != M.
4002     //
4003     // If LHS is non-negative and we know that LHS - RHS does not
4004     // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
4005     // either by proving that RHS > M or that LHS >= 0.
4006     if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
4007       AddFlags = SCEV::FlagNSW;
4008     }
4009   }
4010 
4011   // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
4012   // RHS is NSW and LHS >= 0.
4013   //
4014   // The difficulty here is that the NSW flag may have been proven
4015   // relative to a loop that is to be found in a recurrence in LHS and
4016   // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
4017   // larger scope than intended.
4018   auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
4019 
4020   return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
4021 }
4022 
4023 const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty,
4024                                                      unsigned Depth) {
4025   Type *SrcTy = V->getType();
4026   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4027          "Cannot truncate or zero extend with non-integer arguments!");
4028   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4029     return V;  // No conversion
4030   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4031     return getTruncateExpr(V, Ty, Depth);
4032   return getZeroExtendExpr(V, Ty, Depth);
4033 }
4034 
4035 const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty,
4036                                                      unsigned Depth) {
4037   Type *SrcTy = V->getType();
4038   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4039          "Cannot truncate or zero extend with non-integer arguments!");
4040   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4041     return V;  // No conversion
4042   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4043     return getTruncateExpr(V, Ty, Depth);
4044   return getSignExtendExpr(V, Ty, Depth);
4045 }
4046 
4047 const SCEV *
4048 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
4049   Type *SrcTy = V->getType();
4050   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4051          "Cannot noop or zero extend with non-integer arguments!");
4052   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4053          "getNoopOrZeroExtend cannot truncate!");
4054   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4055     return V;  // No conversion
4056   return getZeroExtendExpr(V, Ty);
4057 }
4058 
4059 const SCEV *
4060 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
4061   Type *SrcTy = V->getType();
4062   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4063          "Cannot noop or sign extend with non-integer arguments!");
4064   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4065          "getNoopOrSignExtend cannot truncate!");
4066   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4067     return V;  // No conversion
4068   return getSignExtendExpr(V, Ty);
4069 }
4070 
4071 const SCEV *
4072 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
4073   Type *SrcTy = V->getType();
4074   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4075          "Cannot noop or any extend with non-integer arguments!");
4076   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4077          "getNoopOrAnyExtend cannot truncate!");
4078   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4079     return V;  // No conversion
4080   return getAnyExtendExpr(V, Ty);
4081 }
4082 
4083 const SCEV *
4084 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
4085   Type *SrcTy = V->getType();
4086   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4087          "Cannot truncate or noop with non-integer arguments!");
4088   assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
4089          "getTruncateOrNoop cannot extend!");
4090   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4091     return V;  // No conversion
4092   return getTruncateExpr(V, Ty);
4093 }
4094 
4095 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
4096                                                         const SCEV *RHS) {
4097   const SCEV *PromotedLHS = LHS;
4098   const SCEV *PromotedRHS = RHS;
4099 
4100   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
4101     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
4102   else
4103     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
4104 
4105   return getUMaxExpr(PromotedLHS, PromotedRHS);
4106 }
4107 
4108 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
4109                                                         const SCEV *RHS) {
4110   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
4111   return getUMinFromMismatchedTypes(Ops);
4112 }
4113 
4114 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(
4115     SmallVectorImpl<const SCEV *> &Ops) {
4116   assert(!Ops.empty() && "At least one operand must be!");
4117   // Trivial case.
4118   if (Ops.size() == 1)
4119     return Ops[0];
4120 
4121   // Find the max type first.
4122   Type *MaxType = nullptr;
4123   for (auto *S : Ops)
4124     if (MaxType)
4125       MaxType = getWiderType(MaxType, S->getType());
4126     else
4127       MaxType = S->getType();
4128   assert(MaxType && "Failed to find maximum type!");
4129 
4130   // Extend all ops to max type.
4131   SmallVector<const SCEV *, 2> PromotedOps;
4132   for (auto *S : Ops)
4133     PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType));
4134 
4135   // Generate umin.
4136   return getUMinExpr(PromotedOps);
4137 }
4138 
4139 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
4140   // A pointer operand may evaluate to a nonpointer expression, such as null.
4141   if (!V->getType()->isPointerTy())
4142     return V;
4143 
4144   while (true) {
4145     if (const SCEVIntegralCastExpr *Cast = dyn_cast<SCEVIntegralCastExpr>(V)) {
4146       V = Cast->getOperand();
4147     } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
4148       const SCEV *PtrOp = nullptr;
4149       for (const SCEV *NAryOp : NAry->operands()) {
4150         if (NAryOp->getType()->isPointerTy()) {
4151           // Cannot find the base of an expression with multiple pointer ops.
4152           if (PtrOp)
4153             return V;
4154           PtrOp = NAryOp;
4155         }
4156       }
4157       if (!PtrOp) // All operands were non-pointer.
4158         return V;
4159       V = PtrOp;
4160     } else // Not something we can look further into.
4161       return V;
4162   }
4163 }
4164 
4165 /// Push users of the given Instruction onto the given Worklist.
4166 static void
4167 PushDefUseChildren(Instruction *I,
4168                    SmallVectorImpl<Instruction *> &Worklist) {
4169   // Push the def-use children onto the Worklist stack.
4170   for (User *U : I->users())
4171     Worklist.push_back(cast<Instruction>(U));
4172 }
4173 
4174 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) {
4175   SmallVector<Instruction *, 16> Worklist;
4176   PushDefUseChildren(PN, Worklist);
4177 
4178   SmallPtrSet<Instruction *, 8> Visited;
4179   Visited.insert(PN);
4180   while (!Worklist.empty()) {
4181     Instruction *I = Worklist.pop_back_val();
4182     if (!Visited.insert(I).second)
4183       continue;
4184 
4185     auto It = ValueExprMap.find_as(static_cast<Value *>(I));
4186     if (It != ValueExprMap.end()) {
4187       const SCEV *Old = It->second;
4188 
4189       // Short-circuit the def-use traversal if the symbolic name
4190       // ceases to appear in expressions.
4191       if (Old != SymName && !hasOperand(Old, SymName))
4192         continue;
4193 
4194       // SCEVUnknown for a PHI either means that it has an unrecognized
4195       // structure, it's a PHI that's in the progress of being computed
4196       // by createNodeForPHI, or it's a single-value PHI. In the first case,
4197       // additional loop trip count information isn't going to change anything.
4198       // In the second case, createNodeForPHI will perform the necessary
4199       // updates on its own when it gets to that point. In the third, we do
4200       // want to forget the SCEVUnknown.
4201       if (!isa<PHINode>(I) ||
4202           !isa<SCEVUnknown>(Old) ||
4203           (I != PN && Old == SymName)) {
4204         eraseValueFromMap(It->first);
4205         forgetMemoizedResults(Old);
4206       }
4207     }
4208 
4209     PushDefUseChildren(I, Worklist);
4210   }
4211 }
4212 
4213 namespace {
4214 
4215 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start
4216 /// expression in case its Loop is L. If it is not L then
4217 /// if IgnoreOtherLoops is true then use AddRec itself
4218 /// otherwise rewrite cannot be done.
4219 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4220 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
4221 public:
4222   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
4223                              bool IgnoreOtherLoops = true) {
4224     SCEVInitRewriter Rewriter(L, SE);
4225     const SCEV *Result = Rewriter.visit(S);
4226     if (Rewriter.hasSeenLoopVariantSCEVUnknown())
4227       return SE.getCouldNotCompute();
4228     return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops
4229                ? SE.getCouldNotCompute()
4230                : Result;
4231   }
4232 
4233   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4234     if (!SE.isLoopInvariant(Expr, L))
4235       SeenLoopVariantSCEVUnknown = true;
4236     return Expr;
4237   }
4238 
4239   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4240     // Only re-write AddRecExprs for this loop.
4241     if (Expr->getLoop() == L)
4242       return Expr->getStart();
4243     SeenOtherLoops = true;
4244     return Expr;
4245   }
4246 
4247   bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4248 
4249   bool hasSeenOtherLoops() { return SeenOtherLoops; }
4250 
4251 private:
4252   explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
4253       : SCEVRewriteVisitor(SE), L(L) {}
4254 
4255   const Loop *L;
4256   bool SeenLoopVariantSCEVUnknown = false;
4257   bool SeenOtherLoops = false;
4258 };
4259 
4260 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post
4261 /// increment expression in case its Loop is L. If it is not L then
4262 /// use AddRec itself.
4263 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4264 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> {
4265 public:
4266   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) {
4267     SCEVPostIncRewriter Rewriter(L, SE);
4268     const SCEV *Result = Rewriter.visit(S);
4269     return Rewriter.hasSeenLoopVariantSCEVUnknown()
4270         ? SE.getCouldNotCompute()
4271         : Result;
4272   }
4273 
4274   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4275     if (!SE.isLoopInvariant(Expr, L))
4276       SeenLoopVariantSCEVUnknown = true;
4277     return Expr;
4278   }
4279 
4280   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4281     // Only re-write AddRecExprs for this loop.
4282     if (Expr->getLoop() == L)
4283       return Expr->getPostIncExpr(SE);
4284     SeenOtherLoops = true;
4285     return Expr;
4286   }
4287 
4288   bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4289 
4290   bool hasSeenOtherLoops() { return SeenOtherLoops; }
4291 
4292 private:
4293   explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE)
4294       : SCEVRewriteVisitor(SE), L(L) {}
4295 
4296   const Loop *L;
4297   bool SeenLoopVariantSCEVUnknown = false;
4298   bool SeenOtherLoops = false;
4299 };
4300 
4301 /// This class evaluates the compare condition by matching it against the
4302 /// condition of loop latch. If there is a match we assume a true value
4303 /// for the condition while building SCEV nodes.
4304 class SCEVBackedgeConditionFolder
4305     : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> {
4306 public:
4307   static const SCEV *rewrite(const SCEV *S, const Loop *L,
4308                              ScalarEvolution &SE) {
4309     bool IsPosBECond = false;
4310     Value *BECond = nullptr;
4311     if (BasicBlock *Latch = L->getLoopLatch()) {
4312       BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator());
4313       if (BI && BI->isConditional()) {
4314         assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
4315                "Both outgoing branches should not target same header!");
4316         BECond = BI->getCondition();
4317         IsPosBECond = BI->getSuccessor(0) == L->getHeader();
4318       } else {
4319         return S;
4320       }
4321     }
4322     SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE);
4323     return Rewriter.visit(S);
4324   }
4325 
4326   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4327     const SCEV *Result = Expr;
4328     bool InvariantF = SE.isLoopInvariant(Expr, L);
4329 
4330     if (!InvariantF) {
4331       Instruction *I = cast<Instruction>(Expr->getValue());
4332       switch (I->getOpcode()) {
4333       case Instruction::Select: {
4334         SelectInst *SI = cast<SelectInst>(I);
4335         Optional<const SCEV *> Res =
4336             compareWithBackedgeCondition(SI->getCondition());
4337         if (Res.hasValue()) {
4338           bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne();
4339           Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue());
4340         }
4341         break;
4342       }
4343       default: {
4344         Optional<const SCEV *> Res = compareWithBackedgeCondition(I);
4345         if (Res.hasValue())
4346           Result = Res.getValue();
4347         break;
4348       }
4349       }
4350     }
4351     return Result;
4352   }
4353 
4354 private:
4355   explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond,
4356                                        bool IsPosBECond, ScalarEvolution &SE)
4357       : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond),
4358         IsPositiveBECond(IsPosBECond) {}
4359 
4360   Optional<const SCEV *> compareWithBackedgeCondition(Value *IC);
4361 
4362   const Loop *L;
4363   /// Loop back condition.
4364   Value *BackedgeCond = nullptr;
4365   /// Set to true if loop back is on positive branch condition.
4366   bool IsPositiveBECond;
4367 };
4368 
4369 Optional<const SCEV *>
4370 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) {
4371 
4372   // If value matches the backedge condition for loop latch,
4373   // then return a constant evolution node based on loopback
4374   // branch taken.
4375   if (BackedgeCond == IC)
4376     return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext()))
4377                             : SE.getZero(Type::getInt1Ty(SE.getContext()));
4378   return None;
4379 }
4380 
4381 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
4382 public:
4383   static const SCEV *rewrite(const SCEV *S, const Loop *L,
4384                              ScalarEvolution &SE) {
4385     SCEVShiftRewriter Rewriter(L, SE);
4386     const SCEV *Result = Rewriter.visit(S);
4387     return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
4388   }
4389 
4390   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4391     // Only allow AddRecExprs for this loop.
4392     if (!SE.isLoopInvariant(Expr, L))
4393       Valid = false;
4394     return Expr;
4395   }
4396 
4397   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4398     if (Expr->getLoop() == L && Expr->isAffine())
4399       return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
4400     Valid = false;
4401     return Expr;
4402   }
4403 
4404   bool isValid() { return Valid; }
4405 
4406 private:
4407   explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
4408       : SCEVRewriteVisitor(SE), L(L) {}
4409 
4410   const Loop *L;
4411   bool Valid = true;
4412 };
4413 
4414 } // end anonymous namespace
4415 
4416 SCEV::NoWrapFlags
4417 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
4418   if (!AR->isAffine())
4419     return SCEV::FlagAnyWrap;
4420 
4421   using OBO = OverflowingBinaryOperator;
4422 
4423   SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
4424 
4425   if (!AR->hasNoSignedWrap()) {
4426     ConstantRange AddRecRange = getSignedRange(AR);
4427     ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
4428 
4429     auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4430         Instruction::Add, IncRange, OBO::NoSignedWrap);
4431     if (NSWRegion.contains(AddRecRange))
4432       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
4433   }
4434 
4435   if (!AR->hasNoUnsignedWrap()) {
4436     ConstantRange AddRecRange = getUnsignedRange(AR);
4437     ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
4438 
4439     auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4440         Instruction::Add, IncRange, OBO::NoUnsignedWrap);
4441     if (NUWRegion.contains(AddRecRange))
4442       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
4443   }
4444 
4445   return Result;
4446 }
4447 
4448 SCEV::NoWrapFlags
4449 ScalarEvolution::proveNoSignedWrapViaInduction(const SCEVAddRecExpr *AR) {
4450   SCEV::NoWrapFlags Result = AR->getNoWrapFlags();
4451 
4452   if (AR->hasNoSignedWrap())
4453     return Result;
4454 
4455   if (!AR->isAffine())
4456     return Result;
4457 
4458   const SCEV *Step = AR->getStepRecurrence(*this);
4459   const Loop *L = AR->getLoop();
4460 
4461   // Check whether the backedge-taken count is SCEVCouldNotCompute.
4462   // Note that this serves two purposes: It filters out loops that are
4463   // simply not analyzable, and it covers the case where this code is
4464   // being called from within backedge-taken count analysis, such that
4465   // attempting to ask for the backedge-taken count would likely result
4466   // in infinite recursion. In the later case, the analysis code will
4467   // cope with a conservative value, and it will take care to purge
4468   // that value once it has finished.
4469   const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
4470 
4471   // Normally, in the cases we can prove no-overflow via a
4472   // backedge guarding condition, we can also compute a backedge
4473   // taken count for the loop.  The exceptions are assumptions and
4474   // guards present in the loop -- SCEV is not great at exploiting
4475   // these to compute max backedge taken counts, but can still use
4476   // these to prove lack of overflow.  Use this fact to avoid
4477   // doing extra work that may not pay off.
4478 
4479   if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
4480       AC.assumptions().empty())
4481     return Result;
4482 
4483   // If the backedge is guarded by a comparison with the pre-inc  value the
4484   // addrec is safe. Also, if the entry is guarded by a comparison with the
4485   // start value and the backedge is guarded by a comparison with the post-inc
4486   // value, the addrec is safe.
4487   ICmpInst::Predicate Pred;
4488   const SCEV *OverflowLimit =
4489     getSignedOverflowLimitForStep(Step, &Pred, this);
4490   if (OverflowLimit &&
4491       (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
4492        isKnownOnEveryIteration(Pred, AR, OverflowLimit))) {
4493     Result = setFlags(Result, SCEV::FlagNSW);
4494   }
4495   return Result;
4496 }
4497 SCEV::NoWrapFlags
4498 ScalarEvolution::proveNoUnsignedWrapViaInduction(const SCEVAddRecExpr *AR) {
4499   SCEV::NoWrapFlags Result = AR->getNoWrapFlags();
4500 
4501   if (AR->hasNoUnsignedWrap())
4502     return Result;
4503 
4504   if (!AR->isAffine())
4505     return Result;
4506 
4507   const SCEV *Step = AR->getStepRecurrence(*this);
4508   unsigned BitWidth = getTypeSizeInBits(AR->getType());
4509   const Loop *L = AR->getLoop();
4510 
4511   // Check whether the backedge-taken count is SCEVCouldNotCompute.
4512   // Note that this serves two purposes: It filters out loops that are
4513   // simply not analyzable, and it covers the case where this code is
4514   // being called from within backedge-taken count analysis, such that
4515   // attempting to ask for the backedge-taken count would likely result
4516   // in infinite recursion. In the later case, the analysis code will
4517   // cope with a conservative value, and it will take care to purge
4518   // that value once it has finished.
4519   const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
4520 
4521   // Normally, in the cases we can prove no-overflow via a
4522   // backedge guarding condition, we can also compute a backedge
4523   // taken count for the loop.  The exceptions are assumptions and
4524   // guards present in the loop -- SCEV is not great at exploiting
4525   // these to compute max backedge taken counts, but can still use
4526   // these to prove lack of overflow.  Use this fact to avoid
4527   // doing extra work that may not pay off.
4528 
4529   if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
4530       AC.assumptions().empty())
4531     return Result;
4532 
4533   // If the backedge is guarded by a comparison with the pre-inc  value the
4534   // addrec is safe. Also, if the entry is guarded by a comparison with the
4535   // start value and the backedge is guarded by a comparison with the post-inc
4536   // value, the addrec is safe.
4537   if (isKnownPositive(Step)) {
4538     const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
4539                                 getUnsignedRangeMax(Step));
4540     if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
4541         isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) {
4542       Result = setFlags(Result, SCEV::FlagNUW);
4543     }
4544   }
4545 
4546   return Result;
4547 }
4548 
4549 namespace {
4550 
4551 /// Represents an abstract binary operation.  This may exist as a
4552 /// normal instruction or constant expression, or may have been
4553 /// derived from an expression tree.
4554 struct BinaryOp {
4555   unsigned Opcode;
4556   Value *LHS;
4557   Value *RHS;
4558   bool IsNSW = false;
4559   bool IsNUW = false;
4560 
4561   /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
4562   /// constant expression.
4563   Operator *Op = nullptr;
4564 
4565   explicit BinaryOp(Operator *Op)
4566       : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
4567         Op(Op) {
4568     if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
4569       IsNSW = OBO->hasNoSignedWrap();
4570       IsNUW = OBO->hasNoUnsignedWrap();
4571     }
4572   }
4573 
4574   explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
4575                     bool IsNUW = false)
4576       : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {}
4577 };
4578 
4579 } // end anonymous namespace
4580 
4581 /// Try to map \p V into a BinaryOp, and return \c None on failure.
4582 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) {
4583   auto *Op = dyn_cast<Operator>(V);
4584   if (!Op)
4585     return None;
4586 
4587   // Implementation detail: all the cleverness here should happen without
4588   // creating new SCEV expressions -- our caller knowns tricks to avoid creating
4589   // SCEV expressions when possible, and we should not break that.
4590 
4591   switch (Op->getOpcode()) {
4592   case Instruction::Add:
4593   case Instruction::Sub:
4594   case Instruction::Mul:
4595   case Instruction::UDiv:
4596   case Instruction::URem:
4597   case Instruction::And:
4598   case Instruction::Or:
4599   case Instruction::AShr:
4600   case Instruction::Shl:
4601     return BinaryOp(Op);
4602 
4603   case Instruction::Xor:
4604     if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
4605       // If the RHS of the xor is a signmask, then this is just an add.
4606       // Instcombine turns add of signmask into xor as a strength reduction step.
4607       if (RHSC->getValue().isSignMask())
4608         return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
4609     return BinaryOp(Op);
4610 
4611   case Instruction::LShr:
4612     // Turn logical shift right of a constant into a unsigned divide.
4613     if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
4614       uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
4615 
4616       // If the shift count is not less than the bitwidth, the result of
4617       // the shift is undefined. Don't try to analyze it, because the
4618       // resolution chosen here may differ from the resolution chosen in
4619       // other parts of the compiler.
4620       if (SA->getValue().ult(BitWidth)) {
4621         Constant *X =
4622             ConstantInt::get(SA->getContext(),
4623                              APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
4624         return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
4625       }
4626     }
4627     return BinaryOp(Op);
4628 
4629   case Instruction::ExtractValue: {
4630     auto *EVI = cast<ExtractValueInst>(Op);
4631     if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
4632       break;
4633 
4634     auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand());
4635     if (!WO)
4636       break;
4637 
4638     Instruction::BinaryOps BinOp = WO->getBinaryOp();
4639     bool Signed = WO->isSigned();
4640     // TODO: Should add nuw/nsw flags for mul as well.
4641     if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT))
4642       return BinaryOp(BinOp, WO->getLHS(), WO->getRHS());
4643 
4644     // Now that we know that all uses of the arithmetic-result component of
4645     // CI are guarded by the overflow check, we can go ahead and pretend
4646     // that the arithmetic is non-overflowing.
4647     return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(),
4648                     /* IsNSW = */ Signed, /* IsNUW = */ !Signed);
4649   }
4650 
4651   default:
4652     break;
4653   }
4654 
4655   // Recognise intrinsic loop.decrement.reg, and as this has exactly the same
4656   // semantics as a Sub, return a binary sub expression.
4657   if (auto *II = dyn_cast<IntrinsicInst>(V))
4658     if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg)
4659       return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1));
4660 
4661   return None;
4662 }
4663 
4664 /// Helper function to createAddRecFromPHIWithCasts. We have a phi
4665 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
4666 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
4667 /// way. This function checks if \p Op, an operand of this SCEVAddExpr,
4668 /// follows one of the following patterns:
4669 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4670 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4671 /// If the SCEV expression of \p Op conforms with one of the expected patterns
4672 /// we return the type of the truncation operation, and indicate whether the
4673 /// truncated type should be treated as signed/unsigned by setting
4674 /// \p Signed to true/false, respectively.
4675 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
4676                                bool &Signed, ScalarEvolution &SE) {
4677   // The case where Op == SymbolicPHI (that is, with no type conversions on
4678   // the way) is handled by the regular add recurrence creating logic and
4679   // would have already been triggered in createAddRecForPHI. Reaching it here
4680   // means that createAddRecFromPHI had failed for this PHI before (e.g.,
4681   // because one of the other operands of the SCEVAddExpr updating this PHI is
4682   // not invariant).
4683   //
4684   // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
4685   // this case predicates that allow us to prove that Op == SymbolicPHI will
4686   // be added.
4687   if (Op == SymbolicPHI)
4688     return nullptr;
4689 
4690   unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
4691   unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
4692   if (SourceBits != NewBits)
4693     return nullptr;
4694 
4695   const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op);
4696   const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op);
4697   if (!SExt && !ZExt)
4698     return nullptr;
4699   const SCEVTruncateExpr *Trunc =
4700       SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand())
4701            : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand());
4702   if (!Trunc)
4703     return nullptr;
4704   const SCEV *X = Trunc->getOperand();
4705   if (X != SymbolicPHI)
4706     return nullptr;
4707   Signed = SExt != nullptr;
4708   return Trunc->getType();
4709 }
4710 
4711 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
4712   if (!PN->getType()->isIntegerTy())
4713     return nullptr;
4714   const Loop *L = LI.getLoopFor(PN->getParent());
4715   if (!L || L->getHeader() != PN->getParent())
4716     return nullptr;
4717   return L;
4718 }
4719 
4720 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
4721 // computation that updates the phi follows the following pattern:
4722 //   (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
4723 // which correspond to a phi->trunc->sext/zext->add->phi update chain.
4724 // If so, try to see if it can be rewritten as an AddRecExpr under some
4725 // Predicates. If successful, return them as a pair. Also cache the results
4726 // of the analysis.
4727 //
4728 // Example usage scenario:
4729 //    Say the Rewriter is called for the following SCEV:
4730 //         8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4731 //    where:
4732 //         %X = phi i64 (%Start, %BEValue)
4733 //    It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
4734 //    and call this function with %SymbolicPHI = %X.
4735 //
4736 //    The analysis will find that the value coming around the backedge has
4737 //    the following SCEV:
4738 //         BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4739 //    Upon concluding that this matches the desired pattern, the function
4740 //    will return the pair {NewAddRec, SmallPredsVec} where:
4741 //         NewAddRec = {%Start,+,%Step}
4742 //         SmallPredsVec = {P1, P2, P3} as follows:
4743 //           P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
4744 //           P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
4745 //           P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
4746 //    The returned pair means that SymbolicPHI can be rewritten into NewAddRec
4747 //    under the predicates {P1,P2,P3}.
4748 //    This predicated rewrite will be cached in PredicatedSCEVRewrites:
4749 //         PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
4750 //
4751 // TODO's:
4752 //
4753 // 1) Extend the Induction descriptor to also support inductions that involve
4754 //    casts: When needed (namely, when we are called in the context of the
4755 //    vectorizer induction analysis), a Set of cast instructions will be
4756 //    populated by this method, and provided back to isInductionPHI. This is
4757 //    needed to allow the vectorizer to properly record them to be ignored by
4758 //    the cost model and to avoid vectorizing them (otherwise these casts,
4759 //    which are redundant under the runtime overflow checks, will be
4760 //    vectorized, which can be costly).
4761 //
4762 // 2) Support additional induction/PHISCEV patterns: We also want to support
4763 //    inductions where the sext-trunc / zext-trunc operations (partly) occur
4764 //    after the induction update operation (the induction increment):
4765 //
4766 //      (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
4767 //    which correspond to a phi->add->trunc->sext/zext->phi update chain.
4768 //
4769 //      (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
4770 //    which correspond to a phi->trunc->add->sext/zext->phi update chain.
4771 //
4772 // 3) Outline common code with createAddRecFromPHI to avoid duplication.
4773 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4774 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
4775   SmallVector<const SCEVPredicate *, 3> Predicates;
4776 
4777   // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
4778   // return an AddRec expression under some predicate.
4779 
4780   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
4781   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
4782   assert(L && "Expecting an integer loop header phi");
4783 
4784   // The loop may have multiple entrances or multiple exits; we can analyze
4785   // this phi as an addrec if it has a unique entry value and a unique
4786   // backedge value.
4787   Value *BEValueV = nullptr, *StartValueV = nullptr;
4788   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4789     Value *V = PN->getIncomingValue(i);
4790     if (L->contains(PN->getIncomingBlock(i))) {
4791       if (!BEValueV) {
4792         BEValueV = V;
4793       } else if (BEValueV != V) {
4794         BEValueV = nullptr;
4795         break;
4796       }
4797     } else if (!StartValueV) {
4798       StartValueV = V;
4799     } else if (StartValueV != V) {
4800       StartValueV = nullptr;
4801       break;
4802     }
4803   }
4804   if (!BEValueV || !StartValueV)
4805     return None;
4806 
4807   const SCEV *BEValue = getSCEV(BEValueV);
4808 
4809   // If the value coming around the backedge is an add with the symbolic
4810   // value we just inserted, possibly with casts that we can ignore under
4811   // an appropriate runtime guard, then we found a simple induction variable!
4812   const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
4813   if (!Add)
4814     return None;
4815 
4816   // If there is a single occurrence of the symbolic value, possibly
4817   // casted, replace it with a recurrence.
4818   unsigned FoundIndex = Add->getNumOperands();
4819   Type *TruncTy = nullptr;
4820   bool Signed;
4821   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4822     if ((TruncTy =
4823              isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
4824       if (FoundIndex == e) {
4825         FoundIndex = i;
4826         break;
4827       }
4828 
4829   if (FoundIndex == Add->getNumOperands())
4830     return None;
4831 
4832   // Create an add with everything but the specified operand.
4833   SmallVector<const SCEV *, 8> Ops;
4834   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4835     if (i != FoundIndex)
4836       Ops.push_back(Add->getOperand(i));
4837   const SCEV *Accum = getAddExpr(Ops);
4838 
4839   // The runtime checks will not be valid if the step amount is
4840   // varying inside the loop.
4841   if (!isLoopInvariant(Accum, L))
4842     return None;
4843 
4844   // *** Part2: Create the predicates
4845 
4846   // Analysis was successful: we have a phi-with-cast pattern for which we
4847   // can return an AddRec expression under the following predicates:
4848   //
4849   // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
4850   //     fits within the truncated type (does not overflow) for i = 0 to n-1.
4851   // P2: An Equal predicate that guarantees that
4852   //     Start = (Ext ix (Trunc iy (Start) to ix) to iy)
4853   // P3: An Equal predicate that guarantees that
4854   //     Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
4855   //
4856   // As we next prove, the above predicates guarantee that:
4857   //     Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
4858   //
4859   //
4860   // More formally, we want to prove that:
4861   //     Expr(i+1) = Start + (i+1) * Accum
4862   //               = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4863   //
4864   // Given that:
4865   // 1) Expr(0) = Start
4866   // 2) Expr(1) = Start + Accum
4867   //            = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
4868   // 3) Induction hypothesis (step i):
4869   //    Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
4870   //
4871   // Proof:
4872   //  Expr(i+1) =
4873   //   = Start + (i+1)*Accum
4874   //   = (Start + i*Accum) + Accum
4875   //   = Expr(i) + Accum
4876   //   = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
4877   //                                                             :: from step i
4878   //
4879   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
4880   //
4881   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
4882   //     + (Ext ix (Trunc iy (Accum) to ix) to iy)
4883   //     + Accum                                                     :: from P3
4884   //
4885   //   = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
4886   //     + Accum                            :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
4887   //
4888   //   = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
4889   //   = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4890   //
4891   // By induction, the same applies to all iterations 1<=i<n:
4892   //
4893 
4894   // Create a truncated addrec for which we will add a no overflow check (P1).
4895   const SCEV *StartVal = getSCEV(StartValueV);
4896   const SCEV *PHISCEV =
4897       getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
4898                     getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap);
4899 
4900   // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
4901   // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
4902   // will be constant.
4903   //
4904   //  If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
4905   // add P1.
4906   if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
4907     SCEVWrapPredicate::IncrementWrapFlags AddedFlags =
4908         Signed ? SCEVWrapPredicate::IncrementNSSW
4909                : SCEVWrapPredicate::IncrementNUSW;
4910     const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
4911     Predicates.push_back(AddRecPred);
4912   }
4913 
4914   // Create the Equal Predicates P2,P3:
4915 
4916   // It is possible that the predicates P2 and/or P3 are computable at
4917   // compile time due to StartVal and/or Accum being constants.
4918   // If either one is, then we can check that now and escape if either P2
4919   // or P3 is false.
4920 
4921   // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
4922   // for each of StartVal and Accum
4923   auto getExtendedExpr = [&](const SCEV *Expr,
4924                              bool CreateSignExtend) -> const SCEV * {
4925     assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant");
4926     const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
4927     const SCEV *ExtendedExpr =
4928         CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType())
4929                          : getZeroExtendExpr(TruncatedExpr, Expr->getType());
4930     return ExtendedExpr;
4931   };
4932 
4933   // Given:
4934   //  ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
4935   //               = getExtendedExpr(Expr)
4936   // Determine whether the predicate P: Expr == ExtendedExpr
4937   // is known to be false at compile time
4938   auto PredIsKnownFalse = [&](const SCEV *Expr,
4939                               const SCEV *ExtendedExpr) -> bool {
4940     return Expr != ExtendedExpr &&
4941            isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr);
4942   };
4943 
4944   const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
4945   if (PredIsKnownFalse(StartVal, StartExtended)) {
4946     LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";);
4947     return None;
4948   }
4949 
4950   // The Step is always Signed (because the overflow checks are either
4951   // NSSW or NUSW)
4952   const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true);
4953   if (PredIsKnownFalse(Accum, AccumExtended)) {
4954     LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";);
4955     return None;
4956   }
4957 
4958   auto AppendPredicate = [&](const SCEV *Expr,
4959                              const SCEV *ExtendedExpr) -> void {
4960     if (Expr != ExtendedExpr &&
4961         !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
4962       const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
4963       LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred);
4964       Predicates.push_back(Pred);
4965     }
4966   };
4967 
4968   AppendPredicate(StartVal, StartExtended);
4969   AppendPredicate(Accum, AccumExtended);
4970 
4971   // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
4972   // which the casts had been folded away. The caller can rewrite SymbolicPHI
4973   // into NewAR if it will also add the runtime overflow checks specified in
4974   // Predicates.
4975   auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap);
4976 
4977   std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
4978       std::make_pair(NewAR, Predicates);
4979   // Remember the result of the analysis for this SCEV at this locayyytion.
4980   PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
4981   return PredRewrite;
4982 }
4983 
4984 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4985 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) {
4986   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
4987   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
4988   if (!L)
4989     return None;
4990 
4991   // Check to see if we already analyzed this PHI.
4992   auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
4993   if (I != PredicatedSCEVRewrites.end()) {
4994     std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
4995         I->second;
4996     // Analysis was done before and failed to create an AddRec:
4997     if (Rewrite.first == SymbolicPHI)
4998       return None;
4999     // Analysis was done before and succeeded to create an AddRec under
5000     // a predicate:
5001     assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec");
5002     assert(!(Rewrite.second).empty() && "Expected to find Predicates");
5003     return Rewrite;
5004   }
5005 
5006   Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5007     Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
5008 
5009   // Record in the cache that the analysis failed
5010   if (!Rewrite) {
5011     SmallVector<const SCEVPredicate *, 3> Predicates;
5012     PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
5013     return None;
5014   }
5015 
5016   return Rewrite;
5017 }
5018 
5019 // FIXME: This utility is currently required because the Rewriter currently
5020 // does not rewrite this expression:
5021 // {0, +, (sext ix (trunc iy to ix) to iy)}
5022 // into {0, +, %step},
5023 // even when the following Equal predicate exists:
5024 // "%step == (sext ix (trunc iy to ix) to iy)".
5025 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds(
5026     const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const {
5027   if (AR1 == AR2)
5028     return true;
5029 
5030   auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool {
5031     if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) &&
5032         !Preds.implies(SE.getEqualPredicate(Expr2, Expr1)))
5033       return false;
5034     return true;
5035   };
5036 
5037   if (!areExprsEqual(AR1->getStart(), AR2->getStart()) ||
5038       !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE)))
5039     return false;
5040   return true;
5041 }
5042 
5043 /// A helper function for createAddRecFromPHI to handle simple cases.
5044 ///
5045 /// This function tries to find an AddRec expression for the simplest (yet most
5046 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
5047 /// If it fails, createAddRecFromPHI will use a more general, but slow,
5048 /// technique for finding the AddRec expression.
5049 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
5050                                                       Value *BEValueV,
5051                                                       Value *StartValueV) {
5052   const Loop *L = LI.getLoopFor(PN->getParent());
5053   assert(L && L->getHeader() == PN->getParent());
5054   assert(BEValueV && StartValueV);
5055 
5056   auto BO = MatchBinaryOp(BEValueV, DT);
5057   if (!BO)
5058     return nullptr;
5059 
5060   if (BO->Opcode != Instruction::Add)
5061     return nullptr;
5062 
5063   const SCEV *Accum = nullptr;
5064   if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
5065     Accum = getSCEV(BO->RHS);
5066   else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
5067     Accum = getSCEV(BO->LHS);
5068 
5069   if (!Accum)
5070     return nullptr;
5071 
5072   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5073   if (BO->IsNUW)
5074     Flags = setFlags(Flags, SCEV::FlagNUW);
5075   if (BO->IsNSW)
5076     Flags = setFlags(Flags, SCEV::FlagNSW);
5077 
5078   const SCEV *StartVal = getSCEV(StartValueV);
5079   const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5080 
5081   ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
5082 
5083   // We can add Flags to the post-inc expression only if we
5084   // know that it is *undefined behavior* for BEValueV to
5085   // overflow.
5086   if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5087     if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5088       (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5089 
5090   return PHISCEV;
5091 }
5092 
5093 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
5094   const Loop *L = LI.getLoopFor(PN->getParent());
5095   if (!L || L->getHeader() != PN->getParent())
5096     return nullptr;
5097 
5098   // The loop may have multiple entrances or multiple exits; we can analyze
5099   // this phi as an addrec if it has a unique entry value and a unique
5100   // backedge value.
5101   Value *BEValueV = nullptr, *StartValueV = nullptr;
5102   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5103     Value *V = PN->getIncomingValue(i);
5104     if (L->contains(PN->getIncomingBlock(i))) {
5105       if (!BEValueV) {
5106         BEValueV = V;
5107       } else if (BEValueV != V) {
5108         BEValueV = nullptr;
5109         break;
5110       }
5111     } else if (!StartValueV) {
5112       StartValueV = V;
5113     } else if (StartValueV != V) {
5114       StartValueV = nullptr;
5115       break;
5116     }
5117   }
5118   if (!BEValueV || !StartValueV)
5119     return nullptr;
5120 
5121   assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
5122          "PHI node already processed?");
5123 
5124   // First, try to find AddRec expression without creating a fictituos symbolic
5125   // value for PN.
5126   if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
5127     return S;
5128 
5129   // Handle PHI node value symbolically.
5130   const SCEV *SymbolicName = getUnknown(PN);
5131   ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName});
5132 
5133   // Using this symbolic name for the PHI, analyze the value coming around
5134   // the back-edge.
5135   const SCEV *BEValue = getSCEV(BEValueV);
5136 
5137   // NOTE: If BEValue is loop invariant, we know that the PHI node just
5138   // has a special value for the first iteration of the loop.
5139 
5140   // If the value coming around the backedge is an add with the symbolic
5141   // value we just inserted, then we found a simple induction variable!
5142   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
5143     // If there is a single occurrence of the symbolic value, replace it
5144     // with a recurrence.
5145     unsigned FoundIndex = Add->getNumOperands();
5146     for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5147       if (Add->getOperand(i) == SymbolicName)
5148         if (FoundIndex == e) {
5149           FoundIndex = i;
5150           break;
5151         }
5152 
5153     if (FoundIndex != Add->getNumOperands()) {
5154       // Create an add with everything but the specified operand.
5155       SmallVector<const SCEV *, 8> Ops;
5156       for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5157         if (i != FoundIndex)
5158           Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i),
5159                                                              L, *this));
5160       const SCEV *Accum = getAddExpr(Ops);
5161 
5162       // This is not a valid addrec if the step amount is varying each
5163       // loop iteration, but is not itself an addrec in this loop.
5164       if (isLoopInvariant(Accum, L) ||
5165           (isa<SCEVAddRecExpr>(Accum) &&
5166            cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
5167         SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5168 
5169         if (auto BO = MatchBinaryOp(BEValueV, DT)) {
5170           if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
5171             if (BO->IsNUW)
5172               Flags = setFlags(Flags, SCEV::FlagNUW);
5173             if (BO->IsNSW)
5174               Flags = setFlags(Flags, SCEV::FlagNSW);
5175           }
5176         } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
5177           // If the increment is an inbounds GEP, then we know the address
5178           // space cannot be wrapped around. We cannot make any guarantee
5179           // about signed or unsigned overflow because pointers are
5180           // unsigned but we may have a negative index from the base
5181           // pointer. We can guarantee that no unsigned wrap occurs if the
5182           // indices form a positive value.
5183           if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
5184             Flags = setFlags(Flags, SCEV::FlagNW);
5185 
5186             const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
5187             if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
5188               Flags = setFlags(Flags, SCEV::FlagNUW);
5189           }
5190 
5191           // We cannot transfer nuw and nsw flags from subtraction
5192           // operations -- sub nuw X, Y is not the same as add nuw X, -Y
5193           // for instance.
5194         }
5195 
5196         const SCEV *StartVal = getSCEV(StartValueV);
5197         const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5198 
5199         // Okay, for the entire analysis of this edge we assumed the PHI
5200         // to be symbolic.  We now need to go back and purge all of the
5201         // entries for the scalars that use the symbolic expression.
5202         forgetSymbolicName(PN, SymbolicName);
5203         ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
5204 
5205         // We can add Flags to the post-inc expression only if we
5206         // know that it is *undefined behavior* for BEValueV to
5207         // overflow.
5208         if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5209           if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5210             (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5211 
5212         return PHISCEV;
5213       }
5214     }
5215   } else {
5216     // Otherwise, this could be a loop like this:
5217     //     i = 0;  for (j = 1; ..; ++j) { ....  i = j; }
5218     // In this case, j = {1,+,1}  and BEValue is j.
5219     // Because the other in-value of i (0) fits the evolution of BEValue
5220     // i really is an addrec evolution.
5221     //
5222     // We can generalize this saying that i is the shifted value of BEValue
5223     // by one iteration:
5224     //   PHI(f(0), f({1,+,1})) --> f({0,+,1})
5225     const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
5226     const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false);
5227     if (Shifted != getCouldNotCompute() &&
5228         Start != getCouldNotCompute()) {
5229       const SCEV *StartVal = getSCEV(StartValueV);
5230       if (Start == StartVal) {
5231         // Okay, for the entire analysis of this edge we assumed the PHI
5232         // to be symbolic.  We now need to go back and purge all of the
5233         // entries for the scalars that use the symbolic expression.
5234         forgetSymbolicName(PN, SymbolicName);
5235         ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted;
5236         return Shifted;
5237       }
5238     }
5239   }
5240 
5241   // Remove the temporary PHI node SCEV that has been inserted while intending
5242   // to create an AddRecExpr for this PHI node. We can not keep this temporary
5243   // as it will prevent later (possibly simpler) SCEV expressions to be added
5244   // to the ValueExprMap.
5245   eraseValueFromMap(PN);
5246 
5247   return nullptr;
5248 }
5249 
5250 // Checks if the SCEV S is available at BB.  S is considered available at BB
5251 // if S can be materialized at BB without introducing a fault.
5252 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
5253                                BasicBlock *BB) {
5254   struct CheckAvailable {
5255     bool TraversalDone = false;
5256     bool Available = true;
5257 
5258     const Loop *L = nullptr;  // The loop BB is in (can be nullptr)
5259     BasicBlock *BB = nullptr;
5260     DominatorTree &DT;
5261 
5262     CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
5263       : L(L), BB(BB), DT(DT) {}
5264 
5265     bool setUnavailable() {
5266       TraversalDone = true;
5267       Available = false;
5268       return false;
5269     }
5270 
5271     bool follow(const SCEV *S) {
5272       switch (S->getSCEVType()) {
5273       case scConstant:
5274       case scPtrToInt:
5275       case scTruncate:
5276       case scZeroExtend:
5277       case scSignExtend:
5278       case scAddExpr:
5279       case scMulExpr:
5280       case scUMaxExpr:
5281       case scSMaxExpr:
5282       case scUMinExpr:
5283       case scSMinExpr:
5284         // These expressions are available if their operand(s) is/are.
5285         return true;
5286 
5287       case scAddRecExpr: {
5288         // We allow add recurrences that are on the loop BB is in, or some
5289         // outer loop.  This guarantees availability because the value of the
5290         // add recurrence at BB is simply the "current" value of the induction
5291         // variable.  We can relax this in the future; for instance an add
5292         // recurrence on a sibling dominating loop is also available at BB.
5293         const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
5294         if (L && (ARLoop == L || ARLoop->contains(L)))
5295           return true;
5296 
5297         return setUnavailable();
5298       }
5299 
5300       case scUnknown: {
5301         // For SCEVUnknown, we check for simple dominance.
5302         const auto *SU = cast<SCEVUnknown>(S);
5303         Value *V = SU->getValue();
5304 
5305         if (isa<Argument>(V))
5306           return false;
5307 
5308         if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
5309           return false;
5310 
5311         return setUnavailable();
5312       }
5313 
5314       case scUDivExpr:
5315       case scCouldNotCompute:
5316         // We do not try to smart about these at all.
5317         return setUnavailable();
5318       }
5319       llvm_unreachable("Unknown SCEV kind!");
5320     }
5321 
5322     bool isDone() { return TraversalDone; }
5323   };
5324 
5325   CheckAvailable CA(L, BB, DT);
5326   SCEVTraversal<CheckAvailable> ST(CA);
5327 
5328   ST.visitAll(S);
5329   return CA.Available;
5330 }
5331 
5332 // Try to match a control flow sequence that branches out at BI and merges back
5333 // at Merge into a "C ? LHS : RHS" select pattern.  Return true on a successful
5334 // match.
5335 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
5336                           Value *&C, Value *&LHS, Value *&RHS) {
5337   C = BI->getCondition();
5338 
5339   BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
5340   BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
5341 
5342   if (!LeftEdge.isSingleEdge())
5343     return false;
5344 
5345   assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
5346 
5347   Use &LeftUse = Merge->getOperandUse(0);
5348   Use &RightUse = Merge->getOperandUse(1);
5349 
5350   if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
5351     LHS = LeftUse;
5352     RHS = RightUse;
5353     return true;
5354   }
5355 
5356   if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
5357     LHS = RightUse;
5358     RHS = LeftUse;
5359     return true;
5360   }
5361 
5362   return false;
5363 }
5364 
5365 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
5366   auto IsReachable =
5367       [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
5368   if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
5369     const Loop *L = LI.getLoopFor(PN->getParent());
5370 
5371     // We don't want to break LCSSA, even in a SCEV expression tree.
5372     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
5373       if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
5374         return nullptr;
5375 
5376     // Try to match
5377     //
5378     //  br %cond, label %left, label %right
5379     // left:
5380     //  br label %merge
5381     // right:
5382     //  br label %merge
5383     // merge:
5384     //  V = phi [ %x, %left ], [ %y, %right ]
5385     //
5386     // as "select %cond, %x, %y"
5387 
5388     BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
5389     assert(IDom && "At least the entry block should dominate PN");
5390 
5391     auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
5392     Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
5393 
5394     if (BI && BI->isConditional() &&
5395         BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
5396         IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
5397         IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
5398       return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
5399   }
5400 
5401   return nullptr;
5402 }
5403 
5404 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
5405   if (const SCEV *S = createAddRecFromPHI(PN))
5406     return S;
5407 
5408   if (const SCEV *S = createNodeFromSelectLikePHI(PN))
5409     return S;
5410 
5411   // If the PHI has a single incoming value, follow that value, unless the
5412   // PHI's incoming blocks are in a different loop, in which case doing so
5413   // risks breaking LCSSA form. Instcombine would normally zap these, but
5414   // it doesn't have DominatorTree information, so it may miss cases.
5415   if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC}))
5416     if (LI.replacementPreservesLCSSAForm(PN, V))
5417       return getSCEV(V);
5418 
5419   // If it's not a loop phi, we can't handle it yet.
5420   return getUnknown(PN);
5421 }
5422 
5423 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I,
5424                                                       Value *Cond,
5425                                                       Value *TrueVal,
5426                                                       Value *FalseVal) {
5427   // Handle "constant" branch or select. This can occur for instance when a
5428   // loop pass transforms an inner loop and moves on to process the outer loop.
5429   if (auto *CI = dyn_cast<ConstantInt>(Cond))
5430     return getSCEV(CI->isOne() ? TrueVal : FalseVal);
5431 
5432   // Try to match some simple smax or umax patterns.
5433   auto *ICI = dyn_cast<ICmpInst>(Cond);
5434   if (!ICI)
5435     return getUnknown(I);
5436 
5437   Value *LHS = ICI->getOperand(0);
5438   Value *RHS = ICI->getOperand(1);
5439 
5440   switch (ICI->getPredicate()) {
5441   case ICmpInst::ICMP_SLT:
5442   case ICmpInst::ICMP_SLE:
5443     std::swap(LHS, RHS);
5444     LLVM_FALLTHROUGH;
5445   case ICmpInst::ICMP_SGT:
5446   case ICmpInst::ICMP_SGE:
5447     // a >s b ? a+x : b+x  ->  smax(a, b)+x
5448     // a >s b ? b+x : a+x  ->  smin(a, b)+x
5449     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5450       const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType());
5451       const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType());
5452       const SCEV *LA = getSCEV(TrueVal);
5453       const SCEV *RA = getSCEV(FalseVal);
5454       const SCEV *LDiff = getMinusSCEV(LA, LS);
5455       const SCEV *RDiff = getMinusSCEV(RA, RS);
5456       if (LDiff == RDiff)
5457         return getAddExpr(getSMaxExpr(LS, RS), LDiff);
5458       LDiff = getMinusSCEV(LA, RS);
5459       RDiff = getMinusSCEV(RA, LS);
5460       if (LDiff == RDiff)
5461         return getAddExpr(getSMinExpr(LS, RS), LDiff);
5462     }
5463     break;
5464   case ICmpInst::ICMP_ULT:
5465   case ICmpInst::ICMP_ULE:
5466     std::swap(LHS, RHS);
5467     LLVM_FALLTHROUGH;
5468   case ICmpInst::ICMP_UGT:
5469   case ICmpInst::ICMP_UGE:
5470     // a >u b ? a+x : b+x  ->  umax(a, b)+x
5471     // a >u b ? b+x : a+x  ->  umin(a, b)+x
5472     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5473       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5474       const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType());
5475       const SCEV *LA = getSCEV(TrueVal);
5476       const SCEV *RA = getSCEV(FalseVal);
5477       const SCEV *LDiff = getMinusSCEV(LA, LS);
5478       const SCEV *RDiff = getMinusSCEV(RA, RS);
5479       if (LDiff == RDiff)
5480         return getAddExpr(getUMaxExpr(LS, RS), LDiff);
5481       LDiff = getMinusSCEV(LA, RS);
5482       RDiff = getMinusSCEV(RA, LS);
5483       if (LDiff == RDiff)
5484         return getAddExpr(getUMinExpr(LS, RS), LDiff);
5485     }
5486     break;
5487   case ICmpInst::ICMP_NE:
5488     // n != 0 ? n+x : 1+x  ->  umax(n, 1)+x
5489     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5490         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5491       const SCEV *One = getOne(I->getType());
5492       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5493       const SCEV *LA = getSCEV(TrueVal);
5494       const SCEV *RA = getSCEV(FalseVal);
5495       const SCEV *LDiff = getMinusSCEV(LA, LS);
5496       const SCEV *RDiff = getMinusSCEV(RA, One);
5497       if (LDiff == RDiff)
5498         return getAddExpr(getUMaxExpr(One, LS), LDiff);
5499     }
5500     break;
5501   case ICmpInst::ICMP_EQ:
5502     // n == 0 ? 1+x : n+x  ->  umax(n, 1)+x
5503     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5504         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5505       const SCEV *One = getOne(I->getType());
5506       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5507       const SCEV *LA = getSCEV(TrueVal);
5508       const SCEV *RA = getSCEV(FalseVal);
5509       const SCEV *LDiff = getMinusSCEV(LA, One);
5510       const SCEV *RDiff = getMinusSCEV(RA, LS);
5511       if (LDiff == RDiff)
5512         return getAddExpr(getUMaxExpr(One, LS), LDiff);
5513     }
5514     break;
5515   default:
5516     break;
5517   }
5518 
5519   return getUnknown(I);
5520 }
5521 
5522 /// Expand GEP instructions into add and multiply operations. This allows them
5523 /// to be analyzed by regular SCEV code.
5524 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
5525   // Don't attempt to analyze GEPs over unsized objects.
5526   if (!GEP->getSourceElementType()->isSized())
5527     return getUnknown(GEP);
5528 
5529   SmallVector<const SCEV *, 4> IndexExprs;
5530   for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
5531     IndexExprs.push_back(getSCEV(*Index));
5532   return getGEPExpr(GEP, IndexExprs);
5533 }
5534 
5535 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) {
5536   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5537     return C->getAPInt().countTrailingZeros();
5538 
5539   if (const SCEVPtrToIntExpr *I = dyn_cast<SCEVPtrToIntExpr>(S))
5540     return GetMinTrailingZeros(I->getOperand());
5541 
5542   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
5543     return std::min(GetMinTrailingZeros(T->getOperand()),
5544                     (uint32_t)getTypeSizeInBits(T->getType()));
5545 
5546   if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
5547     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5548     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5549                ? getTypeSizeInBits(E->getType())
5550                : OpRes;
5551   }
5552 
5553   if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
5554     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5555     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5556                ? getTypeSizeInBits(E->getType())
5557                : OpRes;
5558   }
5559 
5560   if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
5561     // The result is the min of all operands results.
5562     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5563     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5564       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5565     return MinOpRes;
5566   }
5567 
5568   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
5569     // The result is the sum of all operands results.
5570     uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
5571     uint32_t BitWidth = getTypeSizeInBits(M->getType());
5572     for (unsigned i = 1, e = M->getNumOperands();
5573          SumOpRes != BitWidth && i != e; ++i)
5574       SumOpRes =
5575           std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth);
5576     return SumOpRes;
5577   }
5578 
5579   if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
5580     // The result is the min of all operands results.
5581     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5582     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5583       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5584     return MinOpRes;
5585   }
5586 
5587   if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
5588     // The result is the min of all operands results.
5589     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5590     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5591       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5592     return MinOpRes;
5593   }
5594 
5595   if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
5596     // The result is the min of all operands results.
5597     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5598     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5599       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5600     return MinOpRes;
5601   }
5602 
5603   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5604     // For a SCEVUnknown, ask ValueTracking.
5605     KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT);
5606     return Known.countMinTrailingZeros();
5607   }
5608 
5609   // SCEVUDivExpr
5610   return 0;
5611 }
5612 
5613 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
5614   auto I = MinTrailingZerosCache.find(S);
5615   if (I != MinTrailingZerosCache.end())
5616     return I->second;
5617 
5618   uint32_t Result = GetMinTrailingZerosImpl(S);
5619   auto InsertPair = MinTrailingZerosCache.insert({S, Result});
5620   assert(InsertPair.second && "Should insert a new key");
5621   return InsertPair.first->second;
5622 }
5623 
5624 /// Helper method to assign a range to V from metadata present in the IR.
5625 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
5626   if (Instruction *I = dyn_cast<Instruction>(V))
5627     if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
5628       return getConstantRangeFromMetadata(*MD);
5629 
5630   return None;
5631 }
5632 
5633 void ScalarEvolution::setNoWrapFlags(SCEVAddRecExpr *AddRec,
5634                                      SCEV::NoWrapFlags Flags) {
5635   if (AddRec->getNoWrapFlags(Flags) != Flags) {
5636     AddRec->setNoWrapFlags(Flags);
5637     UnsignedRanges.erase(AddRec);
5638     SignedRanges.erase(AddRec);
5639   }
5640 }
5641 
5642 ConstantRange ScalarEvolution::
5643 getRangeForUnknownRecurrence(const SCEVUnknown *U) {
5644   const DataLayout &DL = getDataLayout();
5645 
5646   unsigned BitWidth = getTypeSizeInBits(U->getType());
5647   ConstantRange CR(BitWidth, /*isFullSet=*/true);
5648 
5649   // Match a simple recurrence of the form: <start, ShiftOp, Step>, and then
5650   // use information about the trip count to improve our available range.  Note
5651   // that the trip count independent cases are already handled by known bits.
5652   // WARNING: The definition of recurrence used here is subtly different than
5653   // the one used by AddRec (and thus most of this file).  Step is allowed to
5654   // be arbitrarily loop varying here, where AddRec allows only loop invariant
5655   // and other addrecs in the same loop (for non-affine addrecs).  The code
5656   // below intentionally handles the case where step is not loop invariant.
5657   auto *P = dyn_cast<PHINode>(U->getValue());
5658   if (!P)
5659     return CR;
5660 
5661   // Make sure that no Phi input comes from an unreachable block. Otherwise,
5662   // even the values that are not available in these blocks may come from them,
5663   // and this leads to false-positive recurrence test.
5664   for (auto *Pred : predecessors(P->getParent()))
5665     if (!DT.isReachableFromEntry(Pred))
5666       return CR;
5667 
5668   BinaryOperator *BO;
5669   Value *Start, *Step;
5670   if (!matchSimpleRecurrence(P, BO, Start, Step))
5671     return CR;
5672 
5673   // If we found a recurrence in reachable code, we must be in a loop. Note
5674   // that BO might be in some subloop of L, and that's completely okay.
5675   auto *L = LI.getLoopFor(P->getParent());
5676   assert(L && L->getHeader() == P->getParent());
5677   if (!L->contains(BO->getParent()))
5678     // NOTE: This bailout should be an assert instead.  However, asserting
5679     // the condition here exposes a case where LoopFusion is querying SCEV
5680     // with malformed loop information during the midst of the transform.
5681     // There doesn't appear to be an obvious fix, so for the moment bailout
5682     // until the caller issue can be fixed.  PR49566 tracks the bug.
5683     return CR;
5684 
5685   // TODO: Handle ashr and lshr cases to increase minimum value reported
5686   if (BO->getOpcode() != Instruction::Shl || BO->getOperand(0) != P)
5687     return CR;
5688 
5689   unsigned TC = getSmallConstantMaxTripCount(L);
5690   if (!TC || TC >= BitWidth)
5691     return CR;
5692 
5693   auto KnownStart = computeKnownBits(Start, DL, 0, &AC, nullptr, &DT);
5694   auto KnownStep = computeKnownBits(Step, DL, 0, &AC, nullptr, &DT);
5695   assert(KnownStart.getBitWidth() == BitWidth &&
5696          KnownStep.getBitWidth() == BitWidth);
5697 
5698   // Compute total shift amount, being careful of overflow and bitwidths.
5699   auto MaxShiftAmt = KnownStep.getMaxValue();
5700   APInt TCAP(BitWidth, TC-1);
5701   bool Overflow = false;
5702   auto TotalShift = MaxShiftAmt.umul_ov(TCAP, Overflow);
5703   if (Overflow)
5704     return CR;
5705 
5706   // Iff no bits are shifted out, value increases on every shift.
5707   auto KnownEnd = KnownBits::shl(KnownStart,
5708                                  KnownBits::makeConstant(TotalShift));
5709   if (TotalShift.ult(KnownStart.countMinLeadingZeros()))
5710     CR = CR.intersectWith(ConstantRange(KnownStart.getMinValue(),
5711                                         KnownEnd.getMaxValue() + 1));
5712   return CR;
5713 }
5714 
5715 
5716 
5717 /// Determine the range for a particular SCEV.  If SignHint is
5718 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
5719 /// with a "cleaner" unsigned (resp. signed) representation.
5720 const ConstantRange &
5721 ScalarEvolution::getRangeRef(const SCEV *S,
5722                              ScalarEvolution::RangeSignHint SignHint) {
5723   DenseMap<const SCEV *, ConstantRange> &Cache =
5724       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
5725                                                        : SignedRanges;
5726   ConstantRange::PreferredRangeType RangeType =
5727       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED
5728           ? ConstantRange::Unsigned : ConstantRange::Signed;
5729 
5730   // See if we've computed this range already.
5731   DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
5732   if (I != Cache.end())
5733     return I->second;
5734 
5735   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5736     return setRange(C, SignHint, ConstantRange(C->getAPInt()));
5737 
5738   unsigned BitWidth = getTypeSizeInBits(S->getType());
5739   ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
5740   using OBO = OverflowingBinaryOperator;
5741 
5742   // If the value has known zeros, the maximum value will have those known zeros
5743   // as well.
5744   uint32_t TZ = GetMinTrailingZeros(S);
5745   if (TZ != 0) {
5746     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
5747       ConservativeResult =
5748           ConstantRange(APInt::getMinValue(BitWidth),
5749                         APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
5750     else
5751       ConservativeResult = ConstantRange(
5752           APInt::getSignedMinValue(BitWidth),
5753           APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
5754   }
5755 
5756   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
5757     ConstantRange X = getRangeRef(Add->getOperand(0), SignHint);
5758     unsigned WrapType = OBO::AnyWrap;
5759     if (Add->hasNoSignedWrap())
5760       WrapType |= OBO::NoSignedWrap;
5761     if (Add->hasNoUnsignedWrap())
5762       WrapType |= OBO::NoUnsignedWrap;
5763     for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
5764       X = X.addWithNoWrap(getRangeRef(Add->getOperand(i), SignHint),
5765                           WrapType, RangeType);
5766     return setRange(Add, SignHint,
5767                     ConservativeResult.intersectWith(X, RangeType));
5768   }
5769 
5770   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
5771     ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint);
5772     for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
5773       X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint));
5774     return setRange(Mul, SignHint,
5775                     ConservativeResult.intersectWith(X, RangeType));
5776   }
5777 
5778   if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
5779     ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint);
5780     for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
5781       X = X.smax(getRangeRef(SMax->getOperand(i), SignHint));
5782     return setRange(SMax, SignHint,
5783                     ConservativeResult.intersectWith(X, RangeType));
5784   }
5785 
5786   if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
5787     ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint);
5788     for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
5789       X = X.umax(getRangeRef(UMax->getOperand(i), SignHint));
5790     return setRange(UMax, SignHint,
5791                     ConservativeResult.intersectWith(X, RangeType));
5792   }
5793 
5794   if (const SCEVSMinExpr *SMin = dyn_cast<SCEVSMinExpr>(S)) {
5795     ConstantRange X = getRangeRef(SMin->getOperand(0), SignHint);
5796     for (unsigned i = 1, e = SMin->getNumOperands(); i != e; ++i)
5797       X = X.smin(getRangeRef(SMin->getOperand(i), SignHint));
5798     return setRange(SMin, SignHint,
5799                     ConservativeResult.intersectWith(X, RangeType));
5800   }
5801 
5802   if (const SCEVUMinExpr *UMin = dyn_cast<SCEVUMinExpr>(S)) {
5803     ConstantRange X = getRangeRef(UMin->getOperand(0), SignHint);
5804     for (unsigned i = 1, e = UMin->getNumOperands(); i != e; ++i)
5805       X = X.umin(getRangeRef(UMin->getOperand(i), SignHint));
5806     return setRange(UMin, SignHint,
5807                     ConservativeResult.intersectWith(X, RangeType));
5808   }
5809 
5810   if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
5811     ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint);
5812     ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint);
5813     return setRange(UDiv, SignHint,
5814                     ConservativeResult.intersectWith(X.udiv(Y), RangeType));
5815   }
5816 
5817   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
5818     ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint);
5819     return setRange(ZExt, SignHint,
5820                     ConservativeResult.intersectWith(X.zeroExtend(BitWidth),
5821                                                      RangeType));
5822   }
5823 
5824   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
5825     ConstantRange X = getRangeRef(SExt->getOperand(), SignHint);
5826     return setRange(SExt, SignHint,
5827                     ConservativeResult.intersectWith(X.signExtend(BitWidth),
5828                                                      RangeType));
5829   }
5830 
5831   if (const SCEVPtrToIntExpr *PtrToInt = dyn_cast<SCEVPtrToIntExpr>(S)) {
5832     ConstantRange X = getRangeRef(PtrToInt->getOperand(), SignHint);
5833     return setRange(PtrToInt, SignHint, X);
5834   }
5835 
5836   if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
5837     ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint);
5838     return setRange(Trunc, SignHint,
5839                     ConservativeResult.intersectWith(X.truncate(BitWidth),
5840                                                      RangeType));
5841   }
5842 
5843   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
5844     // If there's no unsigned wrap, the value will never be less than its
5845     // initial value.
5846     if (AddRec->hasNoUnsignedWrap()) {
5847       APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart());
5848       if (!UnsignedMinValue.isNullValue())
5849         ConservativeResult = ConservativeResult.intersectWith(
5850             ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType);
5851     }
5852 
5853     // If there's no signed wrap, and all the operands except initial value have
5854     // the same sign or zero, the value won't ever be:
5855     // 1: smaller than initial value if operands are non negative,
5856     // 2: bigger than initial value if operands are non positive.
5857     // For both cases, value can not cross signed min/max boundary.
5858     if (AddRec->hasNoSignedWrap()) {
5859       bool AllNonNeg = true;
5860       bool AllNonPos = true;
5861       for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) {
5862         if (!isKnownNonNegative(AddRec->getOperand(i)))
5863           AllNonNeg = false;
5864         if (!isKnownNonPositive(AddRec->getOperand(i)))
5865           AllNonPos = false;
5866       }
5867       if (AllNonNeg)
5868         ConservativeResult = ConservativeResult.intersectWith(
5869             ConstantRange::getNonEmpty(getSignedRangeMin(AddRec->getStart()),
5870                                        APInt::getSignedMinValue(BitWidth)),
5871             RangeType);
5872       else if (AllNonPos)
5873         ConservativeResult = ConservativeResult.intersectWith(
5874             ConstantRange::getNonEmpty(
5875                 APInt::getSignedMinValue(BitWidth),
5876                 getSignedRangeMax(AddRec->getStart()) + 1),
5877             RangeType);
5878     }
5879 
5880     // TODO: non-affine addrec
5881     if (AddRec->isAffine()) {
5882       const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(AddRec->getLoop());
5883       if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
5884           getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
5885         auto RangeFromAffine = getRangeForAffineAR(
5886             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
5887             BitWidth);
5888         ConservativeResult =
5889             ConservativeResult.intersectWith(RangeFromAffine, RangeType);
5890 
5891         auto RangeFromFactoring = getRangeViaFactoring(
5892             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
5893             BitWidth);
5894         ConservativeResult =
5895             ConservativeResult.intersectWith(RangeFromFactoring, RangeType);
5896       }
5897 
5898       // Now try symbolic BE count and more powerful methods.
5899       if (UseExpensiveRangeSharpening) {
5900         const SCEV *SymbolicMaxBECount =
5901             getSymbolicMaxBackedgeTakenCount(AddRec->getLoop());
5902         if (!isa<SCEVCouldNotCompute>(SymbolicMaxBECount) &&
5903             getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
5904             AddRec->hasNoSelfWrap()) {
5905           auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR(
5906               AddRec, SymbolicMaxBECount, BitWidth, SignHint);
5907           ConservativeResult =
5908               ConservativeResult.intersectWith(RangeFromAffineNew, RangeType);
5909         }
5910       }
5911     }
5912 
5913     return setRange(AddRec, SignHint, std::move(ConservativeResult));
5914   }
5915 
5916   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5917 
5918     // Check if the IR explicitly contains !range metadata.
5919     Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
5920     if (MDRange.hasValue())
5921       ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue(),
5922                                                             RangeType);
5923 
5924     // Use facts about recurrences in the underlying IR.  Note that add
5925     // recurrences are AddRecExprs and thus don't hit this path.  This
5926     // primarily handles shift recurrences.
5927     auto CR = getRangeForUnknownRecurrence(U);
5928     ConservativeResult = ConservativeResult.intersectWith(CR);
5929 
5930     // See if ValueTracking can give us a useful range.
5931     const DataLayout &DL = getDataLayout();
5932     KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
5933     if (Known.getBitWidth() != BitWidth)
5934       Known = Known.zextOrTrunc(BitWidth);
5935 
5936     // ValueTracking may be able to compute a tighter result for the number of
5937     // sign bits than for the value of those sign bits.
5938     unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
5939     if (U->getType()->isPointerTy()) {
5940       // If the pointer size is larger than the index size type, this can cause
5941       // NS to be larger than BitWidth. So compensate for this.
5942       unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType());
5943       int ptrIdxDiff = ptrSize - BitWidth;
5944       if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff)
5945         NS -= ptrIdxDiff;
5946     }
5947 
5948     if (NS > 1) {
5949       // If we know any of the sign bits, we know all of the sign bits.
5950       if (!Known.Zero.getHiBits(NS).isNullValue())
5951         Known.Zero.setHighBits(NS);
5952       if (!Known.One.getHiBits(NS).isNullValue())
5953         Known.One.setHighBits(NS);
5954     }
5955 
5956     if (Known.getMinValue() != Known.getMaxValue() + 1)
5957       ConservativeResult = ConservativeResult.intersectWith(
5958           ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1),
5959           RangeType);
5960     if (NS > 1)
5961       ConservativeResult = ConservativeResult.intersectWith(
5962           ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
5963                         APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1),
5964           RangeType);
5965 
5966     // A range of Phi is a subset of union of all ranges of its input.
5967     if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) {
5968       // Make sure that we do not run over cycled Phis.
5969       if (PendingPhiRanges.insert(Phi).second) {
5970         ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false);
5971         for (auto &Op : Phi->operands()) {
5972           auto OpRange = getRangeRef(getSCEV(Op), SignHint);
5973           RangeFromOps = RangeFromOps.unionWith(OpRange);
5974           // No point to continue if we already have a full set.
5975           if (RangeFromOps.isFullSet())
5976             break;
5977         }
5978         ConservativeResult =
5979             ConservativeResult.intersectWith(RangeFromOps, RangeType);
5980         bool Erased = PendingPhiRanges.erase(Phi);
5981         assert(Erased && "Failed to erase Phi properly?");
5982         (void) Erased;
5983       }
5984     }
5985 
5986     return setRange(U, SignHint, std::move(ConservativeResult));
5987   }
5988 
5989   return setRange(S, SignHint, std::move(ConservativeResult));
5990 }
5991 
5992 // Given a StartRange, Step and MaxBECount for an expression compute a range of
5993 // values that the expression can take. Initially, the expression has a value
5994 // from StartRange and then is changed by Step up to MaxBECount times. Signed
5995 // argument defines if we treat Step as signed or unsigned.
5996 static ConstantRange getRangeForAffineARHelper(APInt Step,
5997                                                const ConstantRange &StartRange,
5998                                                const APInt &MaxBECount,
5999                                                unsigned BitWidth, bool Signed) {
6000   // If either Step or MaxBECount is 0, then the expression won't change, and we
6001   // just need to return the initial range.
6002   if (Step == 0 || MaxBECount == 0)
6003     return StartRange;
6004 
6005   // If we don't know anything about the initial value (i.e. StartRange is
6006   // FullRange), then we don't know anything about the final range either.
6007   // Return FullRange.
6008   if (StartRange.isFullSet())
6009     return ConstantRange::getFull(BitWidth);
6010 
6011   // If Step is signed and negative, then we use its absolute value, but we also
6012   // note that we're moving in the opposite direction.
6013   bool Descending = Signed && Step.isNegative();
6014 
6015   if (Signed)
6016     // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
6017     // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
6018     // This equations hold true due to the well-defined wrap-around behavior of
6019     // APInt.
6020     Step = Step.abs();
6021 
6022   // Check if Offset is more than full span of BitWidth. If it is, the
6023   // expression is guaranteed to overflow.
6024   if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
6025     return ConstantRange::getFull(BitWidth);
6026 
6027   // Offset is by how much the expression can change. Checks above guarantee no
6028   // overflow here.
6029   APInt Offset = Step * MaxBECount;
6030 
6031   // Minimum value of the final range will match the minimal value of StartRange
6032   // if the expression is increasing and will be decreased by Offset otherwise.
6033   // Maximum value of the final range will match the maximal value of StartRange
6034   // if the expression is decreasing and will be increased by Offset otherwise.
6035   APInt StartLower = StartRange.getLower();
6036   APInt StartUpper = StartRange.getUpper() - 1;
6037   APInt MovedBoundary = Descending ? (StartLower - std::move(Offset))
6038                                    : (StartUpper + std::move(Offset));
6039 
6040   // It's possible that the new minimum/maximum value will fall into the initial
6041   // range (due to wrap around). This means that the expression can take any
6042   // value in this bitwidth, and we have to return full range.
6043   if (StartRange.contains(MovedBoundary))
6044     return ConstantRange::getFull(BitWidth);
6045 
6046   APInt NewLower =
6047       Descending ? std::move(MovedBoundary) : std::move(StartLower);
6048   APInt NewUpper =
6049       Descending ? std::move(StartUpper) : std::move(MovedBoundary);
6050   NewUpper += 1;
6051 
6052   // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
6053   return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper));
6054 }
6055 
6056 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
6057                                                    const SCEV *Step,
6058                                                    const SCEV *MaxBECount,
6059                                                    unsigned BitWidth) {
6060   assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&
6061          getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
6062          "Precondition!");
6063 
6064   MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType());
6065   APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount);
6066 
6067   // First, consider step signed.
6068   ConstantRange StartSRange = getSignedRange(Start);
6069   ConstantRange StepSRange = getSignedRange(Step);
6070 
6071   // If Step can be both positive and negative, we need to find ranges for the
6072   // maximum absolute step values in both directions and union them.
6073   ConstantRange SR =
6074       getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange,
6075                                 MaxBECountValue, BitWidth, /* Signed = */ true);
6076   SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(),
6077                                               StartSRange, MaxBECountValue,
6078                                               BitWidth, /* Signed = */ true));
6079 
6080   // Next, consider step unsigned.
6081   ConstantRange UR = getRangeForAffineARHelper(
6082       getUnsignedRangeMax(Step), getUnsignedRange(Start),
6083       MaxBECountValue, BitWidth, /* Signed = */ false);
6084 
6085   // Finally, intersect signed and unsigned ranges.
6086   return SR.intersectWith(UR, ConstantRange::Smallest);
6087 }
6088 
6089 ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR(
6090     const SCEVAddRecExpr *AddRec, const SCEV *MaxBECount, unsigned BitWidth,
6091     ScalarEvolution::RangeSignHint SignHint) {
6092   assert(AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n");
6093   assert(AddRec->hasNoSelfWrap() &&
6094          "This only works for non-self-wrapping AddRecs!");
6095   const bool IsSigned = SignHint == HINT_RANGE_SIGNED;
6096   const SCEV *Step = AddRec->getStepRecurrence(*this);
6097   // Only deal with constant step to save compile time.
6098   if (!isa<SCEVConstant>(Step))
6099     return ConstantRange::getFull(BitWidth);
6100   // Let's make sure that we can prove that we do not self-wrap during
6101   // MaxBECount iterations. We need this because MaxBECount is a maximum
6102   // iteration count estimate, and we might infer nw from some exit for which we
6103   // do not know max exit count (or any other side reasoning).
6104   // TODO: Turn into assert at some point.
6105   if (getTypeSizeInBits(MaxBECount->getType()) >
6106       getTypeSizeInBits(AddRec->getType()))
6107     return ConstantRange::getFull(BitWidth);
6108   MaxBECount = getNoopOrZeroExtend(MaxBECount, AddRec->getType());
6109   const SCEV *RangeWidth = getMinusOne(AddRec->getType());
6110   const SCEV *StepAbs = getUMinExpr(Step, getNegativeSCEV(Step));
6111   const SCEV *MaxItersWithoutWrap = getUDivExpr(RangeWidth, StepAbs);
6112   if (!isKnownPredicateViaConstantRanges(ICmpInst::ICMP_ULE, MaxBECount,
6113                                          MaxItersWithoutWrap))
6114     return ConstantRange::getFull(BitWidth);
6115 
6116   ICmpInst::Predicate LEPred =
6117       IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
6118   ICmpInst::Predicate GEPred =
6119       IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
6120   const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
6121 
6122   // We know that there is no self-wrap. Let's take Start and End values and
6123   // look at all intermediate values V1, V2, ..., Vn that IndVar takes during
6124   // the iteration. They either lie inside the range [Min(Start, End),
6125   // Max(Start, End)] or outside it:
6126   //
6127   // Case 1:   RangeMin    ...    Start V1 ... VN End ...           RangeMax;
6128   // Case 2:   RangeMin Vk ... V1 Start    ...    End Vn ... Vk + 1 RangeMax;
6129   //
6130   // No self wrap flag guarantees that the intermediate values cannot be BOTH
6131   // outside and inside the range [Min(Start, End), Max(Start, End)]. Using that
6132   // knowledge, let's try to prove that we are dealing with Case 1. It is so if
6133   // Start <= End and step is positive, or Start >= End and step is negative.
6134   const SCEV *Start = AddRec->getStart();
6135   ConstantRange StartRange = getRangeRef(Start, SignHint);
6136   ConstantRange EndRange = getRangeRef(End, SignHint);
6137   ConstantRange RangeBetween = StartRange.unionWith(EndRange);
6138   // If they already cover full iteration space, we will know nothing useful
6139   // even if we prove what we want to prove.
6140   if (RangeBetween.isFullSet())
6141     return RangeBetween;
6142   // Only deal with ranges that do not wrap (i.e. RangeMin < RangeMax).
6143   bool IsWrappedSet = IsSigned ? RangeBetween.isSignWrappedSet()
6144                                : RangeBetween.isWrappedSet();
6145   if (IsWrappedSet)
6146     return ConstantRange::getFull(BitWidth);
6147 
6148   if (isKnownPositive(Step) &&
6149       isKnownPredicateViaConstantRanges(LEPred, Start, End))
6150     return RangeBetween;
6151   else if (isKnownNegative(Step) &&
6152            isKnownPredicateViaConstantRanges(GEPred, Start, End))
6153     return RangeBetween;
6154   return ConstantRange::getFull(BitWidth);
6155 }
6156 
6157 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
6158                                                     const SCEV *Step,
6159                                                     const SCEV *MaxBECount,
6160                                                     unsigned BitWidth) {
6161   //    RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
6162   // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
6163 
6164   struct SelectPattern {
6165     Value *Condition = nullptr;
6166     APInt TrueValue;
6167     APInt FalseValue;
6168 
6169     explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
6170                            const SCEV *S) {
6171       Optional<unsigned> CastOp;
6172       APInt Offset(BitWidth, 0);
6173 
6174       assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&
6175              "Should be!");
6176 
6177       // Peel off a constant offset:
6178       if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
6179         // In the future we could consider being smarter here and handle
6180         // {Start+Step,+,Step} too.
6181         if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
6182           return;
6183 
6184         Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
6185         S = SA->getOperand(1);
6186       }
6187 
6188       // Peel off a cast operation
6189       if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) {
6190         CastOp = SCast->getSCEVType();
6191         S = SCast->getOperand();
6192       }
6193 
6194       using namespace llvm::PatternMatch;
6195 
6196       auto *SU = dyn_cast<SCEVUnknown>(S);
6197       const APInt *TrueVal, *FalseVal;
6198       if (!SU ||
6199           !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
6200                                           m_APInt(FalseVal)))) {
6201         Condition = nullptr;
6202         return;
6203       }
6204 
6205       TrueValue = *TrueVal;
6206       FalseValue = *FalseVal;
6207 
6208       // Re-apply the cast we peeled off earlier
6209       if (CastOp.hasValue())
6210         switch (*CastOp) {
6211         default:
6212           llvm_unreachable("Unknown SCEV cast type!");
6213 
6214         case scTruncate:
6215           TrueValue = TrueValue.trunc(BitWidth);
6216           FalseValue = FalseValue.trunc(BitWidth);
6217           break;
6218         case scZeroExtend:
6219           TrueValue = TrueValue.zext(BitWidth);
6220           FalseValue = FalseValue.zext(BitWidth);
6221           break;
6222         case scSignExtend:
6223           TrueValue = TrueValue.sext(BitWidth);
6224           FalseValue = FalseValue.sext(BitWidth);
6225           break;
6226         }
6227 
6228       // Re-apply the constant offset we peeled off earlier
6229       TrueValue += Offset;
6230       FalseValue += Offset;
6231     }
6232 
6233     bool isRecognized() { return Condition != nullptr; }
6234   };
6235 
6236   SelectPattern StartPattern(*this, BitWidth, Start);
6237   if (!StartPattern.isRecognized())
6238     return ConstantRange::getFull(BitWidth);
6239 
6240   SelectPattern StepPattern(*this, BitWidth, Step);
6241   if (!StepPattern.isRecognized())
6242     return ConstantRange::getFull(BitWidth);
6243 
6244   if (StartPattern.Condition != StepPattern.Condition) {
6245     // We don't handle this case today; but we could, by considering four
6246     // possibilities below instead of two. I'm not sure if there are cases where
6247     // that will help over what getRange already does, though.
6248     return ConstantRange::getFull(BitWidth);
6249   }
6250 
6251   // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
6252   // construct arbitrary general SCEV expressions here.  This function is called
6253   // from deep in the call stack, and calling getSCEV (on a sext instruction,
6254   // say) can end up caching a suboptimal value.
6255 
6256   // FIXME: without the explicit `this` receiver below, MSVC errors out with
6257   // C2352 and C2512 (otherwise it isn't needed).
6258 
6259   const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
6260   const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
6261   const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
6262   const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
6263 
6264   ConstantRange TrueRange =
6265       this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
6266   ConstantRange FalseRange =
6267       this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
6268 
6269   return TrueRange.unionWith(FalseRange);
6270 }
6271 
6272 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
6273   if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
6274   const BinaryOperator *BinOp = cast<BinaryOperator>(V);
6275 
6276   // Return early if there are no flags to propagate to the SCEV.
6277   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
6278   if (BinOp->hasNoUnsignedWrap())
6279     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
6280   if (BinOp->hasNoSignedWrap())
6281     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
6282   if (Flags == SCEV::FlagAnyWrap)
6283     return SCEV::FlagAnyWrap;
6284 
6285   return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
6286 }
6287 
6288 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
6289   // Here we check that I is in the header of the innermost loop containing I,
6290   // since we only deal with instructions in the loop header. The actual loop we
6291   // need to check later will come from an add recurrence, but getting that
6292   // requires computing the SCEV of the operands, which can be expensive. This
6293   // check we can do cheaply to rule out some cases early.
6294   Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent());
6295   if (InnermostContainingLoop == nullptr ||
6296       InnermostContainingLoop->getHeader() != I->getParent())
6297     return false;
6298 
6299   // Only proceed if we can prove that I does not yield poison.
6300   if (!programUndefinedIfPoison(I))
6301     return false;
6302 
6303   // At this point we know that if I is executed, then it does not wrap
6304   // according to at least one of NSW or NUW. If I is not executed, then we do
6305   // not know if the calculation that I represents would wrap. Multiple
6306   // instructions can map to the same SCEV. If we apply NSW or NUW from I to
6307   // the SCEV, we must guarantee no wrapping for that SCEV also when it is
6308   // derived from other instructions that map to the same SCEV. We cannot make
6309   // that guarantee for cases where I is not executed. So we need to find the
6310   // loop that I is considered in relation to and prove that I is executed for
6311   // every iteration of that loop. That implies that the value that I
6312   // calculates does not wrap anywhere in the loop, so then we can apply the
6313   // flags to the SCEV.
6314   //
6315   // We check isLoopInvariant to disambiguate in case we are adding recurrences
6316   // from different loops, so that we know which loop to prove that I is
6317   // executed in.
6318   for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) {
6319     // I could be an extractvalue from a call to an overflow intrinsic.
6320     // TODO: We can do better here in some cases.
6321     if (!isSCEVable(I->getOperand(OpIndex)->getType()))
6322       return false;
6323     const SCEV *Op = getSCEV(I->getOperand(OpIndex));
6324     if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
6325       bool AllOtherOpsLoopInvariant = true;
6326       for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands();
6327            ++OtherOpIndex) {
6328         if (OtherOpIndex != OpIndex) {
6329           const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex));
6330           if (!isLoopInvariant(OtherOp, AddRec->getLoop())) {
6331             AllOtherOpsLoopInvariant = false;
6332             break;
6333           }
6334         }
6335       }
6336       if (AllOtherOpsLoopInvariant &&
6337           isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop()))
6338         return true;
6339     }
6340   }
6341   return false;
6342 }
6343 
6344 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
6345   // If we know that \c I can never be poison period, then that's enough.
6346   if (isSCEVExprNeverPoison(I))
6347     return true;
6348 
6349   // For an add recurrence specifically, we assume that infinite loops without
6350   // side effects are undefined behavior, and then reason as follows:
6351   //
6352   // If the add recurrence is poison in any iteration, it is poison on all
6353   // future iterations (since incrementing poison yields poison). If the result
6354   // of the add recurrence is fed into the loop latch condition and the loop
6355   // does not contain any throws or exiting blocks other than the latch, we now
6356   // have the ability to "choose" whether the backedge is taken or not (by
6357   // choosing a sufficiently evil value for the poison feeding into the branch)
6358   // for every iteration including and after the one in which \p I first became
6359   // poison.  There are two possibilities (let's call the iteration in which \p
6360   // I first became poison as K):
6361   //
6362   //  1. In the set of iterations including and after K, the loop body executes
6363   //     no side effects.  In this case executing the backege an infinte number
6364   //     of times will yield undefined behavior.
6365   //
6366   //  2. In the set of iterations including and after K, the loop body executes
6367   //     at least one side effect.  In this case, that specific instance of side
6368   //     effect is control dependent on poison, which also yields undefined
6369   //     behavior.
6370 
6371   auto *ExitingBB = L->getExitingBlock();
6372   auto *LatchBB = L->getLoopLatch();
6373   if (!ExitingBB || !LatchBB || ExitingBB != LatchBB)
6374     return false;
6375 
6376   SmallPtrSet<const Instruction *, 16> Pushed;
6377   SmallVector<const Instruction *, 8> PoisonStack;
6378 
6379   // We start by assuming \c I, the post-inc add recurrence, is poison.  Only
6380   // things that are known to be poison under that assumption go on the
6381   // PoisonStack.
6382   Pushed.insert(I);
6383   PoisonStack.push_back(I);
6384 
6385   bool LatchControlDependentOnPoison = false;
6386   while (!PoisonStack.empty() && !LatchControlDependentOnPoison) {
6387     const Instruction *Poison = PoisonStack.pop_back_val();
6388 
6389     for (auto *PoisonUser : Poison->users()) {
6390       if (propagatesPoison(cast<Operator>(PoisonUser))) {
6391         if (Pushed.insert(cast<Instruction>(PoisonUser)).second)
6392           PoisonStack.push_back(cast<Instruction>(PoisonUser));
6393       } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) {
6394         assert(BI->isConditional() && "Only possibility!");
6395         if (BI->getParent() == LatchBB) {
6396           LatchControlDependentOnPoison = true;
6397           break;
6398         }
6399       }
6400     }
6401   }
6402 
6403   return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L);
6404 }
6405 
6406 ScalarEvolution::LoopProperties
6407 ScalarEvolution::getLoopProperties(const Loop *L) {
6408   using LoopProperties = ScalarEvolution::LoopProperties;
6409 
6410   auto Itr = LoopPropertiesCache.find(L);
6411   if (Itr == LoopPropertiesCache.end()) {
6412     auto HasSideEffects = [](Instruction *I) {
6413       if (auto *SI = dyn_cast<StoreInst>(I))
6414         return !SI->isSimple();
6415 
6416       return I->mayHaveSideEffects();
6417     };
6418 
6419     LoopProperties LP = {/* HasNoAbnormalExits */ true,
6420                          /*HasNoSideEffects*/ true};
6421 
6422     for (auto *BB : L->getBlocks())
6423       for (auto &I : *BB) {
6424         if (!isGuaranteedToTransferExecutionToSuccessor(&I))
6425           LP.HasNoAbnormalExits = false;
6426         if (HasSideEffects(&I))
6427           LP.HasNoSideEffects = false;
6428         if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
6429           break; // We're already as pessimistic as we can get.
6430       }
6431 
6432     auto InsertPair = LoopPropertiesCache.insert({L, LP});
6433     assert(InsertPair.second && "We just checked!");
6434     Itr = InsertPair.first;
6435   }
6436 
6437   return Itr->second;
6438 }
6439 
6440 const SCEV *ScalarEvolution::createSCEV(Value *V) {
6441   if (!isSCEVable(V->getType()))
6442     return getUnknown(V);
6443 
6444   if (Instruction *I = dyn_cast<Instruction>(V)) {
6445     // Don't attempt to analyze instructions in blocks that aren't
6446     // reachable. Such instructions don't matter, and they aren't required
6447     // to obey basic rules for definitions dominating uses which this
6448     // analysis depends on.
6449     if (!DT.isReachableFromEntry(I->getParent()))
6450       return getUnknown(UndefValue::get(V->getType()));
6451   } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
6452     return getConstant(CI);
6453   else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
6454     return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee());
6455   else if (!isa<ConstantExpr>(V))
6456     return getUnknown(V);
6457 
6458   Operator *U = cast<Operator>(V);
6459   if (auto BO = MatchBinaryOp(U, DT)) {
6460     switch (BO->Opcode) {
6461     case Instruction::Add: {
6462       // The simple thing to do would be to just call getSCEV on both operands
6463       // and call getAddExpr with the result. However if we're looking at a
6464       // bunch of things all added together, this can be quite inefficient,
6465       // because it leads to N-1 getAddExpr calls for N ultimate operands.
6466       // Instead, gather up all the operands and make a single getAddExpr call.
6467       // LLVM IR canonical form means we need only traverse the left operands.
6468       SmallVector<const SCEV *, 4> AddOps;
6469       do {
6470         if (BO->Op) {
6471           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
6472             AddOps.push_back(OpSCEV);
6473             break;
6474           }
6475 
6476           // If a NUW or NSW flag can be applied to the SCEV for this
6477           // addition, then compute the SCEV for this addition by itself
6478           // with a separate call to getAddExpr. We need to do that
6479           // instead of pushing the operands of the addition onto AddOps,
6480           // since the flags are only known to apply to this particular
6481           // addition - they may not apply to other additions that can be
6482           // formed with operands from AddOps.
6483           const SCEV *RHS = getSCEV(BO->RHS);
6484           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
6485           if (Flags != SCEV::FlagAnyWrap) {
6486             const SCEV *LHS = getSCEV(BO->LHS);
6487             if (BO->Opcode == Instruction::Sub)
6488               AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
6489             else
6490               AddOps.push_back(getAddExpr(LHS, RHS, Flags));
6491             break;
6492           }
6493         }
6494 
6495         if (BO->Opcode == Instruction::Sub)
6496           AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
6497         else
6498           AddOps.push_back(getSCEV(BO->RHS));
6499 
6500         auto NewBO = MatchBinaryOp(BO->LHS, DT);
6501         if (!NewBO || (NewBO->Opcode != Instruction::Add &&
6502                        NewBO->Opcode != Instruction::Sub)) {
6503           AddOps.push_back(getSCEV(BO->LHS));
6504           break;
6505         }
6506         BO = NewBO;
6507       } while (true);
6508 
6509       return getAddExpr(AddOps);
6510     }
6511 
6512     case Instruction::Mul: {
6513       SmallVector<const SCEV *, 4> MulOps;
6514       do {
6515         if (BO->Op) {
6516           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
6517             MulOps.push_back(OpSCEV);
6518             break;
6519           }
6520 
6521           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
6522           if (Flags != SCEV::FlagAnyWrap) {
6523             MulOps.push_back(
6524                 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags));
6525             break;
6526           }
6527         }
6528 
6529         MulOps.push_back(getSCEV(BO->RHS));
6530         auto NewBO = MatchBinaryOp(BO->LHS, DT);
6531         if (!NewBO || NewBO->Opcode != Instruction::Mul) {
6532           MulOps.push_back(getSCEV(BO->LHS));
6533           break;
6534         }
6535         BO = NewBO;
6536       } while (true);
6537 
6538       return getMulExpr(MulOps);
6539     }
6540     case Instruction::UDiv:
6541       return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
6542     case Instruction::URem:
6543       return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
6544     case Instruction::Sub: {
6545       SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
6546       if (BO->Op)
6547         Flags = getNoWrapFlagsFromUB(BO->Op);
6548       return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags);
6549     }
6550     case Instruction::And:
6551       // For an expression like x&255 that merely masks off the high bits,
6552       // use zext(trunc(x)) as the SCEV expression.
6553       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6554         if (CI->isZero())
6555           return getSCEV(BO->RHS);
6556         if (CI->isMinusOne())
6557           return getSCEV(BO->LHS);
6558         const APInt &A = CI->getValue();
6559 
6560         // Instcombine's ShrinkDemandedConstant may strip bits out of
6561         // constants, obscuring what would otherwise be a low-bits mask.
6562         // Use computeKnownBits to compute what ShrinkDemandedConstant
6563         // knew about to reconstruct a low-bits mask value.
6564         unsigned LZ = A.countLeadingZeros();
6565         unsigned TZ = A.countTrailingZeros();
6566         unsigned BitWidth = A.getBitWidth();
6567         KnownBits Known(BitWidth);
6568         computeKnownBits(BO->LHS, Known, getDataLayout(),
6569                          0, &AC, nullptr, &DT);
6570 
6571         APInt EffectiveMask =
6572             APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
6573         if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
6574           const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
6575           const SCEV *LHS = getSCEV(BO->LHS);
6576           const SCEV *ShiftedLHS = nullptr;
6577           if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
6578             if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
6579               // For an expression like (x * 8) & 8, simplify the multiply.
6580               unsigned MulZeros = OpC->getAPInt().countTrailingZeros();
6581               unsigned GCD = std::min(MulZeros, TZ);
6582               APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
6583               SmallVector<const SCEV*, 4> MulOps;
6584               MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD)));
6585               MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end());
6586               auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
6587               ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
6588             }
6589           }
6590           if (!ShiftedLHS)
6591             ShiftedLHS = getUDivExpr(LHS, MulCount);
6592           return getMulExpr(
6593               getZeroExtendExpr(
6594                   getTruncateExpr(ShiftedLHS,
6595                       IntegerType::get(getContext(), BitWidth - LZ - TZ)),
6596                   BO->LHS->getType()),
6597               MulCount);
6598         }
6599       }
6600       break;
6601 
6602     case Instruction::Or:
6603       // If the RHS of the Or is a constant, we may have something like:
6604       // X*4+1 which got turned into X*4|1.  Handle this as an Add so loop
6605       // optimizations will transparently handle this case.
6606       //
6607       // In order for this transformation to be safe, the LHS must be of the
6608       // form X*(2^n) and the Or constant must be less than 2^n.
6609       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6610         const SCEV *LHS = getSCEV(BO->LHS);
6611         const APInt &CIVal = CI->getValue();
6612         if (GetMinTrailingZeros(LHS) >=
6613             (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
6614           // Build a plain add SCEV.
6615           return getAddExpr(LHS, getSCEV(CI),
6616                             (SCEV::NoWrapFlags)(SCEV::FlagNUW | SCEV::FlagNSW));
6617         }
6618       }
6619       break;
6620 
6621     case Instruction::Xor:
6622       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6623         // If the RHS of xor is -1, then this is a not operation.
6624         if (CI->isMinusOne())
6625           return getNotSCEV(getSCEV(BO->LHS));
6626 
6627         // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
6628         // This is a variant of the check for xor with -1, and it handles
6629         // the case where instcombine has trimmed non-demanded bits out
6630         // of an xor with -1.
6631         if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
6632           if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
6633             if (LBO->getOpcode() == Instruction::And &&
6634                 LCI->getValue() == CI->getValue())
6635               if (const SCEVZeroExtendExpr *Z =
6636                       dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
6637                 Type *UTy = BO->LHS->getType();
6638                 const SCEV *Z0 = Z->getOperand();
6639                 Type *Z0Ty = Z0->getType();
6640                 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
6641 
6642                 // If C is a low-bits mask, the zero extend is serving to
6643                 // mask off the high bits. Complement the operand and
6644                 // re-apply the zext.
6645                 if (CI->getValue().isMask(Z0TySize))
6646                   return getZeroExtendExpr(getNotSCEV(Z0), UTy);
6647 
6648                 // If C is a single bit, it may be in the sign-bit position
6649                 // before the zero-extend. In this case, represent the xor
6650                 // using an add, which is equivalent, and re-apply the zext.
6651                 APInt Trunc = CI->getValue().trunc(Z0TySize);
6652                 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
6653                     Trunc.isSignMask())
6654                   return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
6655                                            UTy);
6656               }
6657       }
6658       break;
6659 
6660     case Instruction::Shl:
6661       // Turn shift left of a constant amount into a multiply.
6662       if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
6663         uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
6664 
6665         // If the shift count is not less than the bitwidth, the result of
6666         // the shift is undefined. Don't try to analyze it, because the
6667         // resolution chosen here may differ from the resolution chosen in
6668         // other parts of the compiler.
6669         if (SA->getValue().uge(BitWidth))
6670           break;
6671 
6672         // We can safely preserve the nuw flag in all cases. It's also safe to
6673         // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation
6674         // requires special handling. It can be preserved as long as we're not
6675         // left shifting by bitwidth - 1.
6676         auto Flags = SCEV::FlagAnyWrap;
6677         if (BO->Op) {
6678           auto MulFlags = getNoWrapFlagsFromUB(BO->Op);
6679           if ((MulFlags & SCEV::FlagNSW) &&
6680               ((MulFlags & SCEV::FlagNUW) || SA->getValue().ult(BitWidth - 1)))
6681             Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNSW);
6682           if (MulFlags & SCEV::FlagNUW)
6683             Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNUW);
6684         }
6685 
6686         Constant *X = ConstantInt::get(
6687             getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
6688         return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags);
6689       }
6690       break;
6691 
6692     case Instruction::AShr: {
6693       // AShr X, C, where C is a constant.
6694       ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
6695       if (!CI)
6696         break;
6697 
6698       Type *OuterTy = BO->LHS->getType();
6699       uint64_t BitWidth = getTypeSizeInBits(OuterTy);
6700       // If the shift count is not less than the bitwidth, the result of
6701       // the shift is undefined. Don't try to analyze it, because the
6702       // resolution chosen here may differ from the resolution chosen in
6703       // other parts of the compiler.
6704       if (CI->getValue().uge(BitWidth))
6705         break;
6706 
6707       if (CI->isZero())
6708         return getSCEV(BO->LHS); // shift by zero --> noop
6709 
6710       uint64_t AShrAmt = CI->getZExtValue();
6711       Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
6712 
6713       Operator *L = dyn_cast<Operator>(BO->LHS);
6714       if (L && L->getOpcode() == Instruction::Shl) {
6715         // X = Shl A, n
6716         // Y = AShr X, m
6717         // Both n and m are constant.
6718 
6719         const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
6720         if (L->getOperand(1) == BO->RHS)
6721           // For a two-shift sext-inreg, i.e. n = m,
6722           // use sext(trunc(x)) as the SCEV expression.
6723           return getSignExtendExpr(
6724               getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy);
6725 
6726         ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
6727         if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) {
6728           uint64_t ShlAmt = ShlAmtCI->getZExtValue();
6729           if (ShlAmt > AShrAmt) {
6730             // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
6731             // expression. We already checked that ShlAmt < BitWidth, so
6732             // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
6733             // ShlAmt - AShrAmt < Amt.
6734             APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
6735                                             ShlAmt - AShrAmt);
6736             return getSignExtendExpr(
6737                 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy),
6738                 getConstant(Mul)), OuterTy);
6739           }
6740         }
6741       }
6742       break;
6743     }
6744     }
6745   }
6746 
6747   switch (U->getOpcode()) {
6748   case Instruction::Trunc:
6749     return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
6750 
6751   case Instruction::ZExt:
6752     return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
6753 
6754   case Instruction::SExt:
6755     if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) {
6756       // The NSW flag of a subtract does not always survive the conversion to
6757       // A + (-1)*B.  By pushing sign extension onto its operands we are much
6758       // more likely to preserve NSW and allow later AddRec optimisations.
6759       //
6760       // NOTE: This is effectively duplicating this logic from getSignExtend:
6761       //   sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
6762       // but by that point the NSW information has potentially been lost.
6763       if (BO->Opcode == Instruction::Sub && BO->IsNSW) {
6764         Type *Ty = U->getType();
6765         auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty);
6766         auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty);
6767         return getMinusSCEV(V1, V2, SCEV::FlagNSW);
6768       }
6769     }
6770     return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
6771 
6772   case Instruction::BitCast:
6773     // BitCasts are no-op casts so we just eliminate the cast.
6774     if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
6775       return getSCEV(U->getOperand(0));
6776     break;
6777 
6778   case Instruction::PtrToInt: {
6779     // Pointer to integer cast is straight-forward, so do model it.
6780     Value *Ptr = U->getOperand(0);
6781     const SCEV *Op = getSCEV(Ptr);
6782     Type *DstIntTy = U->getType();
6783     Type *PtrTy = Ptr->getType();
6784     Type *IntPtrTy = getDataLayout().getIntPtrType(PtrTy);
6785     // But only if effective SCEV (integer) type is wide enough to represent
6786     // all possible pointer values.
6787     if (getDataLayout().getTypeSizeInBits(getEffectiveSCEVType(PtrTy)) !=
6788         getDataLayout().getTypeSizeInBits(IntPtrTy))
6789       return getUnknown(V);
6790     return getPtrToIntExpr(Op, DstIntTy);
6791   }
6792   case Instruction::IntToPtr:
6793     // Just don't deal with inttoptr casts.
6794     return getUnknown(V);
6795 
6796   case Instruction::SDiv:
6797     // If both operands are non-negative, this is just an udiv.
6798     if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
6799         isKnownNonNegative(getSCEV(U->getOperand(1))))
6800       return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
6801     break;
6802 
6803   case Instruction::SRem:
6804     // If both operands are non-negative, this is just an urem.
6805     if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
6806         isKnownNonNegative(getSCEV(U->getOperand(1))))
6807       return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
6808     break;
6809 
6810   case Instruction::GetElementPtr:
6811     return createNodeForGEP(cast<GEPOperator>(U));
6812 
6813   case Instruction::PHI:
6814     return createNodeForPHI(cast<PHINode>(U));
6815 
6816   case Instruction::Select:
6817     // U can also be a select constant expr, which let fall through.  Since
6818     // createNodeForSelect only works for a condition that is an `ICmpInst`, and
6819     // constant expressions cannot have instructions as operands, we'd have
6820     // returned getUnknown for a select constant expressions anyway.
6821     if (isa<Instruction>(U))
6822       return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0),
6823                                       U->getOperand(1), U->getOperand(2));
6824     break;
6825 
6826   case Instruction::Call:
6827   case Instruction::Invoke:
6828     if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand())
6829       return getSCEV(RV);
6830 
6831     if (auto *II = dyn_cast<IntrinsicInst>(U)) {
6832       switch (II->getIntrinsicID()) {
6833       case Intrinsic::abs:
6834         return getAbsExpr(
6835             getSCEV(II->getArgOperand(0)),
6836             /*IsNSW=*/cast<ConstantInt>(II->getArgOperand(1))->isOne());
6837       case Intrinsic::umax:
6838         return getUMaxExpr(getSCEV(II->getArgOperand(0)),
6839                            getSCEV(II->getArgOperand(1)));
6840       case Intrinsic::umin:
6841         return getUMinExpr(getSCEV(II->getArgOperand(0)),
6842                            getSCEV(II->getArgOperand(1)));
6843       case Intrinsic::smax:
6844         return getSMaxExpr(getSCEV(II->getArgOperand(0)),
6845                            getSCEV(II->getArgOperand(1)));
6846       case Intrinsic::smin:
6847         return getSMinExpr(getSCEV(II->getArgOperand(0)),
6848                            getSCEV(II->getArgOperand(1)));
6849       case Intrinsic::usub_sat: {
6850         const SCEV *X = getSCEV(II->getArgOperand(0));
6851         const SCEV *Y = getSCEV(II->getArgOperand(1));
6852         const SCEV *ClampedY = getUMinExpr(X, Y);
6853         return getMinusSCEV(X, ClampedY, SCEV::FlagNUW);
6854       }
6855       case Intrinsic::uadd_sat: {
6856         const SCEV *X = getSCEV(II->getArgOperand(0));
6857         const SCEV *Y = getSCEV(II->getArgOperand(1));
6858         const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y));
6859         return getAddExpr(ClampedX, Y, SCEV::FlagNUW);
6860       }
6861       case Intrinsic::start_loop_iterations:
6862         // A start_loop_iterations is just equivalent to the first operand for
6863         // SCEV purposes.
6864         return getSCEV(II->getArgOperand(0));
6865       default:
6866         break;
6867       }
6868     }
6869     break;
6870   }
6871 
6872   return getUnknown(V);
6873 }
6874 
6875 //===----------------------------------------------------------------------===//
6876 //                   Iteration Count Computation Code
6877 //
6878 
6879 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
6880   if (!ExitCount)
6881     return 0;
6882 
6883   ConstantInt *ExitConst = ExitCount->getValue();
6884 
6885   // Guard against huge trip counts.
6886   if (ExitConst->getValue().getActiveBits() > 32)
6887     return 0;
6888 
6889   // In case of integer overflow, this returns 0, which is correct.
6890   return ((unsigned)ExitConst->getZExtValue()) + 1;
6891 }
6892 
6893 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) {
6894   if (BasicBlock *ExitingBB = L->getExitingBlock())
6895     return getSmallConstantTripCount(L, ExitingBB);
6896 
6897   // No trip count information for multiple exits.
6898   return 0;
6899 }
6900 
6901 unsigned
6902 ScalarEvolution::getSmallConstantTripCount(const Loop *L,
6903                                            const BasicBlock *ExitingBlock) {
6904   assert(ExitingBlock && "Must pass a non-null exiting block!");
6905   assert(L->isLoopExiting(ExitingBlock) &&
6906          "Exiting block must actually branch out of the loop!");
6907   const SCEVConstant *ExitCount =
6908       dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
6909   return getConstantTripCount(ExitCount);
6910 }
6911 
6912 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) {
6913   const auto *MaxExitCount =
6914       dyn_cast<SCEVConstant>(getConstantMaxBackedgeTakenCount(L));
6915   return getConstantTripCount(MaxExitCount);
6916 }
6917 
6918 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) {
6919   if (BasicBlock *ExitingBB = L->getExitingBlock())
6920     return getSmallConstantTripMultiple(L, ExitingBB);
6921 
6922   // No trip multiple information for multiple exits.
6923   return 0;
6924 }
6925 
6926 /// Returns the largest constant divisor of the trip count of this loop as a
6927 /// normal unsigned value, if possible. This means that the actual trip count is
6928 /// always a multiple of the returned value (don't forget the trip count could
6929 /// very well be zero as well!).
6930 ///
6931 /// Returns 1 if the trip count is unknown or not guaranteed to be the
6932 /// multiple of a constant (which is also the case if the trip count is simply
6933 /// constant, use getSmallConstantTripCount for that case), Will also return 1
6934 /// if the trip count is very large (>= 2^32).
6935 ///
6936 /// As explained in the comments for getSmallConstantTripCount, this assumes
6937 /// that control exits the loop via ExitingBlock.
6938 unsigned
6939 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
6940                                               const BasicBlock *ExitingBlock) {
6941   assert(ExitingBlock && "Must pass a non-null exiting block!");
6942   assert(L->isLoopExiting(ExitingBlock) &&
6943          "Exiting block must actually branch out of the loop!");
6944   const SCEV *ExitCount = getExitCount(L, ExitingBlock);
6945   if (ExitCount == getCouldNotCompute())
6946     return 1;
6947 
6948   // Get the trip count from the BE count by adding 1.
6949   const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType()));
6950 
6951   const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr);
6952   if (!TC)
6953     // Attempt to factor more general cases. Returns the greatest power of
6954     // two divisor. If overflow happens, the trip count expression is still
6955     // divisible by the greatest power of 2 divisor returned.
6956     return 1U << std::min((uint32_t)31,
6957                           GetMinTrailingZeros(applyLoopGuards(TCExpr, L)));
6958 
6959   ConstantInt *Result = TC->getValue();
6960 
6961   // Guard against huge trip counts (this requires checking
6962   // for zero to handle the case where the trip count == -1 and the
6963   // addition wraps).
6964   if (!Result || Result->getValue().getActiveBits() > 32 ||
6965       Result->getValue().getActiveBits() == 0)
6966     return 1;
6967 
6968   return (unsigned)Result->getZExtValue();
6969 }
6970 
6971 const SCEV *ScalarEvolution::getExitCount(const Loop *L,
6972                                           const BasicBlock *ExitingBlock,
6973                                           ExitCountKind Kind) {
6974   switch (Kind) {
6975   case Exact:
6976   case SymbolicMaximum:
6977     return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
6978   case ConstantMaximum:
6979     return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this);
6980   };
6981   llvm_unreachable("Invalid ExitCountKind!");
6982 }
6983 
6984 const SCEV *
6985 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
6986                                                  SCEVUnionPredicate &Preds) {
6987   return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds);
6988 }
6989 
6990 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L,
6991                                                    ExitCountKind Kind) {
6992   switch (Kind) {
6993   case Exact:
6994     return getBackedgeTakenInfo(L).getExact(L, this);
6995   case ConstantMaximum:
6996     return getBackedgeTakenInfo(L).getConstantMax(this);
6997   case SymbolicMaximum:
6998     return getBackedgeTakenInfo(L).getSymbolicMax(L, this);
6999   };
7000   llvm_unreachable("Invalid ExitCountKind!");
7001 }
7002 
7003 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) {
7004   return getBackedgeTakenInfo(L).isConstantMaxOrZero(this);
7005 }
7006 
7007 /// Push PHI nodes in the header of the given loop onto the given Worklist.
7008 static void
7009 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
7010   BasicBlock *Header = L->getHeader();
7011 
7012   // Push all Loop-header PHIs onto the Worklist stack.
7013   for (PHINode &PN : Header->phis())
7014     Worklist.push_back(&PN);
7015 }
7016 
7017 const ScalarEvolution::BackedgeTakenInfo &
7018 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
7019   auto &BTI = getBackedgeTakenInfo(L);
7020   if (BTI.hasFullInfo())
7021     return BTI;
7022 
7023   auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
7024 
7025   if (!Pair.second)
7026     return Pair.first->second;
7027 
7028   BackedgeTakenInfo Result =
7029       computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
7030 
7031   return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
7032 }
7033 
7034 ScalarEvolution::BackedgeTakenInfo &
7035 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
7036   // Initially insert an invalid entry for this loop. If the insertion
7037   // succeeds, proceed to actually compute a backedge-taken count and
7038   // update the value. The temporary CouldNotCompute value tells SCEV
7039   // code elsewhere that it shouldn't attempt to request a new
7040   // backedge-taken count, which could result in infinite recursion.
7041   std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
7042       BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
7043   if (!Pair.second)
7044     return Pair.first->second;
7045 
7046   // computeBackedgeTakenCount may allocate memory for its result. Inserting it
7047   // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
7048   // must be cleared in this scope.
7049   BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
7050 
7051   // In product build, there are no usage of statistic.
7052   (void)NumTripCountsComputed;
7053   (void)NumTripCountsNotComputed;
7054 #if LLVM_ENABLE_STATS || !defined(NDEBUG)
7055   const SCEV *BEExact = Result.getExact(L, this);
7056   if (BEExact != getCouldNotCompute()) {
7057     assert(isLoopInvariant(BEExact, L) &&
7058            isLoopInvariant(Result.getConstantMax(this), L) &&
7059            "Computed backedge-taken count isn't loop invariant for loop!");
7060     ++NumTripCountsComputed;
7061   } else if (Result.getConstantMax(this) == getCouldNotCompute() &&
7062              isa<PHINode>(L->getHeader()->begin())) {
7063     // Only count loops that have phi nodes as not being computable.
7064     ++NumTripCountsNotComputed;
7065   }
7066 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG)
7067 
7068   // Now that we know more about the trip count for this loop, forget any
7069   // existing SCEV values for PHI nodes in this loop since they are only
7070   // conservative estimates made without the benefit of trip count
7071   // information. This is similar to the code in forgetLoop, except that
7072   // it handles SCEVUnknown PHI nodes specially.
7073   if (Result.hasAnyInfo()) {
7074     SmallVector<Instruction *, 16> Worklist;
7075     PushLoopPHIs(L, Worklist);
7076 
7077     SmallPtrSet<Instruction *, 8> Discovered;
7078     while (!Worklist.empty()) {
7079       Instruction *I = Worklist.pop_back_val();
7080 
7081       ValueExprMapType::iterator It =
7082         ValueExprMap.find_as(static_cast<Value *>(I));
7083       if (It != ValueExprMap.end()) {
7084         const SCEV *Old = It->second;
7085 
7086         // SCEVUnknown for a PHI either means that it has an unrecognized
7087         // structure, or it's a PHI that's in the progress of being computed
7088         // by createNodeForPHI.  In the former case, additional loop trip
7089         // count information isn't going to change anything. In the later
7090         // case, createNodeForPHI will perform the necessary updates on its
7091         // own when it gets to that point.
7092         if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
7093           eraseValueFromMap(It->first);
7094           forgetMemoizedResults(Old);
7095         }
7096         if (PHINode *PN = dyn_cast<PHINode>(I))
7097           ConstantEvolutionLoopExitValue.erase(PN);
7098       }
7099 
7100       // Since we don't need to invalidate anything for correctness and we're
7101       // only invalidating to make SCEV's results more precise, we get to stop
7102       // early to avoid invalidating too much.  This is especially important in
7103       // cases like:
7104       //
7105       //   %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node
7106       // loop0:
7107       //   %pn0 = phi
7108       //   ...
7109       // loop1:
7110       //   %pn1 = phi
7111       //   ...
7112       //
7113       // where both loop0 and loop1's backedge taken count uses the SCEV
7114       // expression for %v.  If we don't have the early stop below then in cases
7115       // like the above, getBackedgeTakenInfo(loop1) will clear out the trip
7116       // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip
7117       // count for loop1, effectively nullifying SCEV's trip count cache.
7118       for (auto *U : I->users())
7119         if (auto *I = dyn_cast<Instruction>(U)) {
7120           auto *LoopForUser = LI.getLoopFor(I->getParent());
7121           if (LoopForUser && L->contains(LoopForUser) &&
7122               Discovered.insert(I).second)
7123             Worklist.push_back(I);
7124         }
7125     }
7126   }
7127 
7128   // Re-lookup the insert position, since the call to
7129   // computeBackedgeTakenCount above could result in a
7130   // recusive call to getBackedgeTakenInfo (on a different
7131   // loop), which would invalidate the iterator computed
7132   // earlier.
7133   return BackedgeTakenCounts.find(L)->second = std::move(Result);
7134 }
7135 
7136 void ScalarEvolution::forgetAllLoops() {
7137   // This method is intended to forget all info about loops. It should
7138   // invalidate caches as if the following happened:
7139   // - The trip counts of all loops have changed arbitrarily
7140   // - Every llvm::Value has been updated in place to produce a different
7141   // result.
7142   BackedgeTakenCounts.clear();
7143   PredicatedBackedgeTakenCounts.clear();
7144   LoopPropertiesCache.clear();
7145   ConstantEvolutionLoopExitValue.clear();
7146   ValueExprMap.clear();
7147   ValuesAtScopes.clear();
7148   LoopDispositions.clear();
7149   BlockDispositions.clear();
7150   UnsignedRanges.clear();
7151   SignedRanges.clear();
7152   ExprValueMap.clear();
7153   HasRecMap.clear();
7154   MinTrailingZerosCache.clear();
7155   PredicatedSCEVRewrites.clear();
7156 }
7157 
7158 void ScalarEvolution::forgetLoop(const Loop *L) {
7159   // Drop any stored trip count value.
7160   auto RemoveLoopFromBackedgeMap =
7161       [](DenseMap<const Loop *, BackedgeTakenInfo> &Map, const Loop *L) {
7162         auto BTCPos = Map.find(L);
7163         if (BTCPos != Map.end()) {
7164           BTCPos->second.clear();
7165           Map.erase(BTCPos);
7166         }
7167       };
7168 
7169   SmallVector<const Loop *, 16> LoopWorklist(1, L);
7170   SmallVector<Instruction *, 32> Worklist;
7171   SmallPtrSet<Instruction *, 16> Visited;
7172 
7173   // Iterate over all the loops and sub-loops to drop SCEV information.
7174   while (!LoopWorklist.empty()) {
7175     auto *CurrL = LoopWorklist.pop_back_val();
7176 
7177     RemoveLoopFromBackedgeMap(BackedgeTakenCounts, CurrL);
7178     RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts, CurrL);
7179 
7180     // Drop information about predicated SCEV rewrites for this loop.
7181     for (auto I = PredicatedSCEVRewrites.begin();
7182          I != PredicatedSCEVRewrites.end();) {
7183       std::pair<const SCEV *, const Loop *> Entry = I->first;
7184       if (Entry.second == CurrL)
7185         PredicatedSCEVRewrites.erase(I++);
7186       else
7187         ++I;
7188     }
7189 
7190     auto LoopUsersItr = LoopUsers.find(CurrL);
7191     if (LoopUsersItr != LoopUsers.end()) {
7192       for (auto *S : LoopUsersItr->second)
7193         forgetMemoizedResults(S);
7194       LoopUsers.erase(LoopUsersItr);
7195     }
7196 
7197     // Drop information about expressions based on loop-header PHIs.
7198     PushLoopPHIs(CurrL, Worklist);
7199 
7200     while (!Worklist.empty()) {
7201       Instruction *I = Worklist.pop_back_val();
7202       if (!Visited.insert(I).second)
7203         continue;
7204 
7205       ValueExprMapType::iterator It =
7206           ValueExprMap.find_as(static_cast<Value *>(I));
7207       if (It != ValueExprMap.end()) {
7208         eraseValueFromMap(It->first);
7209         forgetMemoizedResults(It->second);
7210         if (PHINode *PN = dyn_cast<PHINode>(I))
7211           ConstantEvolutionLoopExitValue.erase(PN);
7212       }
7213 
7214       PushDefUseChildren(I, Worklist);
7215     }
7216 
7217     LoopPropertiesCache.erase(CurrL);
7218     // Forget all contained loops too, to avoid dangling entries in the
7219     // ValuesAtScopes map.
7220     LoopWorklist.append(CurrL->begin(), CurrL->end());
7221   }
7222 }
7223 
7224 void ScalarEvolution::forgetTopmostLoop(const Loop *L) {
7225   while (Loop *Parent = L->getParentLoop())
7226     L = Parent;
7227   forgetLoop(L);
7228 }
7229 
7230 void ScalarEvolution::forgetValue(Value *V) {
7231   Instruction *I = dyn_cast<Instruction>(V);
7232   if (!I) return;
7233 
7234   // Drop information about expressions based on loop-header PHIs.
7235   SmallVector<Instruction *, 16> Worklist;
7236   Worklist.push_back(I);
7237 
7238   SmallPtrSet<Instruction *, 8> Visited;
7239   while (!Worklist.empty()) {
7240     I = Worklist.pop_back_val();
7241     if (!Visited.insert(I).second)
7242       continue;
7243 
7244     ValueExprMapType::iterator It =
7245       ValueExprMap.find_as(static_cast<Value *>(I));
7246     if (It != ValueExprMap.end()) {
7247       eraseValueFromMap(It->first);
7248       forgetMemoizedResults(It->second);
7249       if (PHINode *PN = dyn_cast<PHINode>(I))
7250         ConstantEvolutionLoopExitValue.erase(PN);
7251     }
7252 
7253     PushDefUseChildren(I, Worklist);
7254   }
7255 }
7256 
7257 void ScalarEvolution::forgetLoopDispositions(const Loop *L) {
7258   LoopDispositions.clear();
7259 }
7260 
7261 /// Get the exact loop backedge taken count considering all loop exits. A
7262 /// computable result can only be returned for loops with all exiting blocks
7263 /// dominating the latch. howFarToZero assumes that the limit of each loop test
7264 /// is never skipped. This is a valid assumption as long as the loop exits via
7265 /// that test. For precise results, it is the caller's responsibility to specify
7266 /// the relevant loop exiting block using getExact(ExitingBlock, SE).
7267 const SCEV *
7268 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE,
7269                                              SCEVUnionPredicate *Preds) const {
7270   // If any exits were not computable, the loop is not computable.
7271   if (!isComplete() || ExitNotTaken.empty())
7272     return SE->getCouldNotCompute();
7273 
7274   const BasicBlock *Latch = L->getLoopLatch();
7275   // All exiting blocks we have collected must dominate the only backedge.
7276   if (!Latch)
7277     return SE->getCouldNotCompute();
7278 
7279   // All exiting blocks we have gathered dominate loop's latch, so exact trip
7280   // count is simply a minimum out of all these calculated exit counts.
7281   SmallVector<const SCEV *, 2> Ops;
7282   for (auto &ENT : ExitNotTaken) {
7283     const SCEV *BECount = ENT.ExactNotTaken;
7284     assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!");
7285     assert(SE->DT.dominates(ENT.ExitingBlock, Latch) &&
7286            "We should only have known counts for exiting blocks that dominate "
7287            "latch!");
7288 
7289     Ops.push_back(BECount);
7290 
7291     if (Preds && !ENT.hasAlwaysTruePredicate())
7292       Preds->add(ENT.Predicate.get());
7293 
7294     assert((Preds || ENT.hasAlwaysTruePredicate()) &&
7295            "Predicate should be always true!");
7296   }
7297 
7298   return SE->getUMinFromMismatchedTypes(Ops);
7299 }
7300 
7301 /// Get the exact not taken count for this loop exit.
7302 const SCEV *
7303 ScalarEvolution::BackedgeTakenInfo::getExact(const BasicBlock *ExitingBlock,
7304                                              ScalarEvolution *SE) const {
7305   for (auto &ENT : ExitNotTaken)
7306     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
7307       return ENT.ExactNotTaken;
7308 
7309   return SE->getCouldNotCompute();
7310 }
7311 
7312 const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax(
7313     const BasicBlock *ExitingBlock, ScalarEvolution *SE) const {
7314   for (auto &ENT : ExitNotTaken)
7315     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
7316       return ENT.MaxNotTaken;
7317 
7318   return SE->getCouldNotCompute();
7319 }
7320 
7321 /// getConstantMax - Get the constant max backedge taken count for the loop.
7322 const SCEV *
7323 ScalarEvolution::BackedgeTakenInfo::getConstantMax(ScalarEvolution *SE) const {
7324   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
7325     return !ENT.hasAlwaysTruePredicate();
7326   };
7327 
7328   if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getConstantMax())
7329     return SE->getCouldNotCompute();
7330 
7331   assert((isa<SCEVCouldNotCompute>(getConstantMax()) ||
7332           isa<SCEVConstant>(getConstantMax())) &&
7333          "No point in having a non-constant max backedge taken count!");
7334   return getConstantMax();
7335 }
7336 
7337 const SCEV *
7338 ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(const Loop *L,
7339                                                    ScalarEvolution *SE) {
7340   if (!SymbolicMax)
7341     SymbolicMax = SE->computeSymbolicMaxBackedgeTakenCount(L);
7342   return SymbolicMax;
7343 }
7344 
7345 bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero(
7346     ScalarEvolution *SE) const {
7347   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
7348     return !ENT.hasAlwaysTruePredicate();
7349   };
7350   return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
7351 }
7352 
7353 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S,
7354                                                     ScalarEvolution *SE) const {
7355   if (getConstantMax() && getConstantMax() != SE->getCouldNotCompute() &&
7356       SE->hasOperand(getConstantMax(), S))
7357     return true;
7358 
7359   for (auto &ENT : ExitNotTaken)
7360     if (ENT.ExactNotTaken != SE->getCouldNotCompute() &&
7361         SE->hasOperand(ENT.ExactNotTaken, S))
7362       return true;
7363 
7364   return false;
7365 }
7366 
7367 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E)
7368     : ExactNotTaken(E), MaxNotTaken(E) {
7369   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
7370           isa<SCEVConstant>(MaxNotTaken)) &&
7371          "No point in having a non-constant max backedge taken count!");
7372 }
7373 
7374 ScalarEvolution::ExitLimit::ExitLimit(
7375     const SCEV *E, const SCEV *M, bool MaxOrZero,
7376     ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList)
7377     : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) {
7378   assert((isa<SCEVCouldNotCompute>(ExactNotTaken) ||
7379           !isa<SCEVCouldNotCompute>(MaxNotTaken)) &&
7380          "Exact is not allowed to be less precise than Max");
7381   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
7382           isa<SCEVConstant>(MaxNotTaken)) &&
7383          "No point in having a non-constant max backedge taken count!");
7384   for (auto *PredSet : PredSetList)
7385     for (auto *P : *PredSet)
7386       addPredicate(P);
7387 }
7388 
7389 ScalarEvolution::ExitLimit::ExitLimit(
7390     const SCEV *E, const SCEV *M, bool MaxOrZero,
7391     const SmallPtrSetImpl<const SCEVPredicate *> &PredSet)
7392     : ExitLimit(E, M, MaxOrZero, {&PredSet}) {
7393   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
7394           isa<SCEVConstant>(MaxNotTaken)) &&
7395          "No point in having a non-constant max backedge taken count!");
7396 }
7397 
7398 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M,
7399                                       bool MaxOrZero)
7400     : ExitLimit(E, M, MaxOrZero, None) {
7401   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
7402           isa<SCEVConstant>(MaxNotTaken)) &&
7403          "No point in having a non-constant max backedge taken count!");
7404 }
7405 
7406 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
7407 /// computable exit into a persistent ExitNotTakenInfo array.
7408 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
7409     ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> ExitCounts,
7410     bool IsComplete, const SCEV *ConstantMax, bool MaxOrZero)
7411     : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) {
7412   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
7413 
7414   ExitNotTaken.reserve(ExitCounts.size());
7415   std::transform(
7416       ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken),
7417       [&](const EdgeExitInfo &EEI) {
7418         BasicBlock *ExitBB = EEI.first;
7419         const ExitLimit &EL = EEI.second;
7420         if (EL.Predicates.empty())
7421           return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken,
7422                                   nullptr);
7423 
7424         std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate);
7425         for (auto *Pred : EL.Predicates)
7426           Predicate->add(Pred);
7427 
7428         return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken,
7429                                 std::move(Predicate));
7430       });
7431   assert((isa<SCEVCouldNotCompute>(ConstantMax) ||
7432           isa<SCEVConstant>(ConstantMax)) &&
7433          "No point in having a non-constant max backedge taken count!");
7434 }
7435 
7436 /// Invalidate this result and free the ExitNotTakenInfo array.
7437 void ScalarEvolution::BackedgeTakenInfo::clear() {
7438   ExitNotTaken.clear();
7439 }
7440 
7441 /// Compute the number of times the backedge of the specified loop will execute.
7442 ScalarEvolution::BackedgeTakenInfo
7443 ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
7444                                            bool AllowPredicates) {
7445   SmallVector<BasicBlock *, 8> ExitingBlocks;
7446   L->getExitingBlocks(ExitingBlocks);
7447 
7448   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
7449 
7450   SmallVector<EdgeExitInfo, 4> ExitCounts;
7451   bool CouldComputeBECount = true;
7452   BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
7453   const SCEV *MustExitMaxBECount = nullptr;
7454   const SCEV *MayExitMaxBECount = nullptr;
7455   bool MustExitMaxOrZero = false;
7456 
7457   // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
7458   // and compute maxBECount.
7459   // Do a union of all the predicates here.
7460   for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
7461     BasicBlock *ExitBB = ExitingBlocks[i];
7462 
7463     // We canonicalize untaken exits to br (constant), ignore them so that
7464     // proving an exit untaken doesn't negatively impact our ability to reason
7465     // about the loop as whole.
7466     if (auto *BI = dyn_cast<BranchInst>(ExitBB->getTerminator()))
7467       if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
7468         bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
7469         if ((ExitIfTrue && CI->isZero()) || (!ExitIfTrue && CI->isOne()))
7470           continue;
7471       }
7472 
7473     ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
7474 
7475     assert((AllowPredicates || EL.Predicates.empty()) &&
7476            "Predicated exit limit when predicates are not allowed!");
7477 
7478     // 1. For each exit that can be computed, add an entry to ExitCounts.
7479     // CouldComputeBECount is true only if all exits can be computed.
7480     if (EL.ExactNotTaken == getCouldNotCompute())
7481       // We couldn't compute an exact value for this exit, so
7482       // we won't be able to compute an exact value for the loop.
7483       CouldComputeBECount = false;
7484     else
7485       ExitCounts.emplace_back(ExitBB, EL);
7486 
7487     // 2. Derive the loop's MaxBECount from each exit's max number of
7488     // non-exiting iterations. Partition the loop exits into two kinds:
7489     // LoopMustExits and LoopMayExits.
7490     //
7491     // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
7492     // is a LoopMayExit.  If any computable LoopMustExit is found, then
7493     // MaxBECount is the minimum EL.MaxNotTaken of computable
7494     // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
7495     // EL.MaxNotTaken, where CouldNotCompute is considered greater than any
7496     // computable EL.MaxNotTaken.
7497     if (EL.MaxNotTaken != getCouldNotCompute() && Latch &&
7498         DT.dominates(ExitBB, Latch)) {
7499       if (!MustExitMaxBECount) {
7500         MustExitMaxBECount = EL.MaxNotTaken;
7501         MustExitMaxOrZero = EL.MaxOrZero;
7502       } else {
7503         MustExitMaxBECount =
7504             getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken);
7505       }
7506     } else if (MayExitMaxBECount != getCouldNotCompute()) {
7507       if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute())
7508         MayExitMaxBECount = EL.MaxNotTaken;
7509       else {
7510         MayExitMaxBECount =
7511             getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken);
7512       }
7513     }
7514   }
7515   const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
7516     (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
7517   // The loop backedge will be taken the maximum or zero times if there's
7518   // a single exit that must be taken the maximum or zero times.
7519   bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
7520   return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
7521                            MaxBECount, MaxOrZero);
7522 }
7523 
7524 ScalarEvolution::ExitLimit
7525 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
7526                                       bool AllowPredicates) {
7527   assert(L->contains(ExitingBlock) && "Exit count for non-loop block?");
7528   // If our exiting block does not dominate the latch, then its connection with
7529   // loop's exit limit may be far from trivial.
7530   const BasicBlock *Latch = L->getLoopLatch();
7531   if (!Latch || !DT.dominates(ExitingBlock, Latch))
7532     return getCouldNotCompute();
7533 
7534   bool IsOnlyExit = (L->getExitingBlock() != nullptr);
7535   Instruction *Term = ExitingBlock->getTerminator();
7536   if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
7537     assert(BI->isConditional() && "If unconditional, it can't be in loop!");
7538     bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
7539     assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) &&
7540            "It should have one successor in loop and one exit block!");
7541     // Proceed to the next level to examine the exit condition expression.
7542     return computeExitLimitFromCond(
7543         L, BI->getCondition(), ExitIfTrue,
7544         /*ControlsExit=*/IsOnlyExit, AllowPredicates);
7545   }
7546 
7547   if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) {
7548     // For switch, make sure that there is a single exit from the loop.
7549     BasicBlock *Exit = nullptr;
7550     for (auto *SBB : successors(ExitingBlock))
7551       if (!L->contains(SBB)) {
7552         if (Exit) // Multiple exit successors.
7553           return getCouldNotCompute();
7554         Exit = SBB;
7555       }
7556     assert(Exit && "Exiting block must have at least one exit");
7557     return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
7558                                                 /*ControlsExit=*/IsOnlyExit);
7559   }
7560 
7561   return getCouldNotCompute();
7562 }
7563 
7564 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond(
7565     const Loop *L, Value *ExitCond, bool ExitIfTrue,
7566     bool ControlsExit, bool AllowPredicates) {
7567   ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates);
7568   return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue,
7569                                         ControlsExit, AllowPredicates);
7570 }
7571 
7572 Optional<ScalarEvolution::ExitLimit>
7573 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
7574                                       bool ExitIfTrue, bool ControlsExit,
7575                                       bool AllowPredicates) {
7576   (void)this->L;
7577   (void)this->ExitIfTrue;
7578   (void)this->AllowPredicates;
7579 
7580   assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
7581          this->AllowPredicates == AllowPredicates &&
7582          "Variance in assumed invariant key components!");
7583   auto Itr = TripCountMap.find({ExitCond, ControlsExit});
7584   if (Itr == TripCountMap.end())
7585     return None;
7586   return Itr->second;
7587 }
7588 
7589 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
7590                                              bool ExitIfTrue,
7591                                              bool ControlsExit,
7592                                              bool AllowPredicates,
7593                                              const ExitLimit &EL) {
7594   assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
7595          this->AllowPredicates == AllowPredicates &&
7596          "Variance in assumed invariant key components!");
7597 
7598   auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL});
7599   assert(InsertResult.second && "Expected successful insertion!");
7600   (void)InsertResult;
7601   (void)ExitIfTrue;
7602 }
7603 
7604 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
7605     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
7606     bool ControlsExit, bool AllowPredicates) {
7607 
7608   if (auto MaybeEL =
7609           Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates))
7610     return *MaybeEL;
7611 
7612   ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue,
7613                                               ControlsExit, AllowPredicates);
7614   Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL);
7615   return EL;
7616 }
7617 
7618 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
7619     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
7620     bool ControlsExit, bool AllowPredicates) {
7621   // Handle BinOp conditions (And, Or).
7622   if (auto LimitFromBinOp = computeExitLimitFromCondFromBinOp(
7623           Cache, L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates))
7624     return *LimitFromBinOp;
7625 
7626   // With an icmp, it may be feasible to compute an exact backedge-taken count.
7627   // Proceed to the next level to examine the icmp.
7628   if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
7629     ExitLimit EL =
7630         computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit);
7631     if (EL.hasFullInfo() || !AllowPredicates)
7632       return EL;
7633 
7634     // Try again, but use SCEV predicates this time.
7635     return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit,
7636                                     /*AllowPredicates=*/true);
7637   }
7638 
7639   // Check for a constant condition. These are normally stripped out by
7640   // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
7641   // preserve the CFG and is temporarily leaving constant conditions
7642   // in place.
7643   if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
7644     if (ExitIfTrue == !CI->getZExtValue())
7645       // The backedge is always taken.
7646       return getCouldNotCompute();
7647     else
7648       // The backedge is never taken.
7649       return getZero(CI->getType());
7650   }
7651 
7652   // If it's not an integer or pointer comparison then compute it the hard way.
7653   return computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
7654 }
7655 
7656 Optional<ScalarEvolution::ExitLimit>
7657 ScalarEvolution::computeExitLimitFromCondFromBinOp(
7658     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
7659     bool ControlsExit, bool AllowPredicates) {
7660   // Check if the controlling expression for this loop is an And or Or.
7661   Value *Op0, *Op1;
7662   bool IsAnd = false;
7663   if (match(ExitCond, m_LogicalAnd(m_Value(Op0), m_Value(Op1))))
7664     IsAnd = true;
7665   else if (match(ExitCond, m_LogicalOr(m_Value(Op0), m_Value(Op1))))
7666     IsAnd = false;
7667   else
7668     return None;
7669 
7670   // EitherMayExit is true in these two cases:
7671   //   br (and Op0 Op1), loop, exit
7672   //   br (or  Op0 Op1), exit, loop
7673   bool EitherMayExit = IsAnd ^ ExitIfTrue;
7674   ExitLimit EL0 = computeExitLimitFromCondCached(Cache, L, Op0, ExitIfTrue,
7675                                                  ControlsExit && !EitherMayExit,
7676                                                  AllowPredicates);
7677   ExitLimit EL1 = computeExitLimitFromCondCached(Cache, L, Op1, ExitIfTrue,
7678                                                  ControlsExit && !EitherMayExit,
7679                                                  AllowPredicates);
7680 
7681   // Be robust against unsimplified IR for the form "op i1 X, NeutralElement"
7682   const Constant *NeutralElement = ConstantInt::get(ExitCond->getType(), IsAnd);
7683   if (isa<ConstantInt>(Op1))
7684     return Op1 == NeutralElement ? EL0 : EL1;
7685   if (isa<ConstantInt>(Op0))
7686     return Op0 == NeutralElement ? EL1 : EL0;
7687 
7688   const SCEV *BECount = getCouldNotCompute();
7689   const SCEV *MaxBECount = getCouldNotCompute();
7690   if (EitherMayExit) {
7691     // Both conditions must be same for the loop to continue executing.
7692     // Choose the less conservative count.
7693     // If ExitCond is a short-circuit form (select), using
7694     // umin(EL0.ExactNotTaken, EL1.ExactNotTaken) is unsafe in general.
7695     // To see the detailed examples, please see
7696     // test/Analysis/ScalarEvolution/exit-count-select.ll
7697     bool PoisonSafe = isa<BinaryOperator>(ExitCond);
7698     if (!PoisonSafe)
7699       // Even if ExitCond is select, we can safely derive BECount using both
7700       // EL0 and EL1 in these cases:
7701       // (1) EL0.ExactNotTaken is non-zero
7702       // (2) EL1.ExactNotTaken is non-poison
7703       // (3) EL0.ExactNotTaken is zero (BECount should be simply zero and
7704       //     it cannot be umin(0, ..))
7705       // The PoisonSafe assignment below is simplified and the assertion after
7706       // BECount calculation fully guarantees the condition (3).
7707       PoisonSafe = isa<SCEVConstant>(EL0.ExactNotTaken) ||
7708                    isa<SCEVConstant>(EL1.ExactNotTaken);
7709     if (EL0.ExactNotTaken != getCouldNotCompute() &&
7710         EL1.ExactNotTaken != getCouldNotCompute() && PoisonSafe) {
7711       BECount =
7712           getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
7713 
7714       // If EL0.ExactNotTaken was zero and ExitCond was a short-circuit form,
7715       // it should have been simplified to zero (see the condition (3) above)
7716       assert(!isa<BinaryOperator>(ExitCond) || !EL0.ExactNotTaken->isZero() ||
7717              BECount->isZero());
7718     }
7719     if (EL0.MaxNotTaken == getCouldNotCompute())
7720       MaxBECount = EL1.MaxNotTaken;
7721     else if (EL1.MaxNotTaken == getCouldNotCompute())
7722       MaxBECount = EL0.MaxNotTaken;
7723     else
7724       MaxBECount = getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
7725   } else {
7726     // Both conditions must be same at the same time for the loop to exit.
7727     // For now, be conservative.
7728     if (EL0.ExactNotTaken == EL1.ExactNotTaken)
7729       BECount = EL0.ExactNotTaken;
7730   }
7731 
7732   // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
7733   // to be more aggressive when computing BECount than when computing
7734   // MaxBECount.  In these cases it is possible for EL0.ExactNotTaken and
7735   // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
7736   // to not.
7737   if (isa<SCEVCouldNotCompute>(MaxBECount) &&
7738       !isa<SCEVCouldNotCompute>(BECount))
7739     MaxBECount = getConstant(getUnsignedRangeMax(BECount));
7740 
7741   return ExitLimit(BECount, MaxBECount, false,
7742                    { &EL0.Predicates, &EL1.Predicates });
7743 }
7744 
7745 ScalarEvolution::ExitLimit
7746 ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
7747                                           ICmpInst *ExitCond,
7748                                           bool ExitIfTrue,
7749                                           bool ControlsExit,
7750                                           bool AllowPredicates) {
7751   // If the condition was exit on true, convert the condition to exit on false
7752   ICmpInst::Predicate Pred;
7753   if (!ExitIfTrue)
7754     Pred = ExitCond->getPredicate();
7755   else
7756     Pred = ExitCond->getInversePredicate();
7757   const ICmpInst::Predicate OriginalPred = Pred;
7758 
7759   // Handle common loops like: for (X = "string"; *X; ++X)
7760   if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
7761     if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
7762       ExitLimit ItCnt =
7763         computeLoadConstantCompareExitLimit(LI, RHS, L, Pred);
7764       if (ItCnt.hasAnyInfo())
7765         return ItCnt;
7766     }
7767 
7768   const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
7769   const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
7770 
7771   // Try to evaluate any dependencies out of the loop.
7772   LHS = getSCEVAtScope(LHS, L);
7773   RHS = getSCEVAtScope(RHS, L);
7774 
7775   // At this point, we would like to compute how many iterations of the
7776   // loop the predicate will return true for these inputs.
7777   if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
7778     // If there is a loop-invariant, force it into the RHS.
7779     std::swap(LHS, RHS);
7780     Pred = ICmpInst::getSwappedPredicate(Pred);
7781   }
7782 
7783   // Simplify the operands before analyzing them.
7784   (void)SimplifyICmpOperands(Pred, LHS, RHS);
7785 
7786   // If we have a comparison of a chrec against a constant, try to use value
7787   // ranges to answer this query.
7788   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
7789     if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
7790       if (AddRec->getLoop() == L) {
7791         // Form the constant range.
7792         ConstantRange CompRange =
7793             ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt());
7794 
7795         const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
7796         if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
7797       }
7798 
7799   switch (Pred) {
7800   case ICmpInst::ICMP_NE: {                     // while (X != Y)
7801     // Convert to: while (X-Y != 0)
7802     ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit,
7803                                 AllowPredicates);
7804     if (EL.hasAnyInfo()) return EL;
7805     break;
7806   }
7807   case ICmpInst::ICMP_EQ: {                     // while (X == Y)
7808     // Convert to: while (X-Y == 0)
7809     ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
7810     if (EL.hasAnyInfo()) return EL;
7811     break;
7812   }
7813   case ICmpInst::ICMP_SLT:
7814   case ICmpInst::ICMP_ULT: {                    // while (X < Y)
7815     bool IsSigned = Pred == ICmpInst::ICMP_SLT;
7816     ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit,
7817                                     AllowPredicates);
7818     if (EL.hasAnyInfo()) return EL;
7819     break;
7820   }
7821   case ICmpInst::ICMP_SGT:
7822   case ICmpInst::ICMP_UGT: {                    // while (X > Y)
7823     bool IsSigned = Pred == ICmpInst::ICMP_SGT;
7824     ExitLimit EL =
7825         howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
7826                             AllowPredicates);
7827     if (EL.hasAnyInfo()) return EL;
7828     break;
7829   }
7830   default:
7831     break;
7832   }
7833 
7834   auto *ExhaustiveCount =
7835       computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
7836 
7837   if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
7838     return ExhaustiveCount;
7839 
7840   return computeShiftCompareExitLimit(ExitCond->getOperand(0),
7841                                       ExitCond->getOperand(1), L, OriginalPred);
7842 }
7843 
7844 ScalarEvolution::ExitLimit
7845 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
7846                                                       SwitchInst *Switch,
7847                                                       BasicBlock *ExitingBlock,
7848                                                       bool ControlsExit) {
7849   assert(!L->contains(ExitingBlock) && "Not an exiting block!");
7850 
7851   // Give up if the exit is the default dest of a switch.
7852   if (Switch->getDefaultDest() == ExitingBlock)
7853     return getCouldNotCompute();
7854 
7855   assert(L->contains(Switch->getDefaultDest()) &&
7856          "Default case must not exit the loop!");
7857   const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
7858   const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
7859 
7860   // while (X != Y) --> while (X-Y != 0)
7861   ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
7862   if (EL.hasAnyInfo())
7863     return EL;
7864 
7865   return getCouldNotCompute();
7866 }
7867 
7868 static ConstantInt *
7869 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
7870                                 ScalarEvolution &SE) {
7871   const SCEV *InVal = SE.getConstant(C);
7872   const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
7873   assert(isa<SCEVConstant>(Val) &&
7874          "Evaluation of SCEV at constant didn't fold correctly?");
7875   return cast<SCEVConstant>(Val)->getValue();
7876 }
7877 
7878 /// Given an exit condition of 'icmp op load X, cst', try to see if we can
7879 /// compute the backedge execution count.
7880 ScalarEvolution::ExitLimit
7881 ScalarEvolution::computeLoadConstantCompareExitLimit(
7882   LoadInst *LI,
7883   Constant *RHS,
7884   const Loop *L,
7885   ICmpInst::Predicate predicate) {
7886   if (LI->isVolatile()) return getCouldNotCompute();
7887 
7888   // Check to see if the loaded pointer is a getelementptr of a global.
7889   // TODO: Use SCEV instead of manually grubbing with GEPs.
7890   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
7891   if (!GEP) return getCouldNotCompute();
7892 
7893   // Make sure that it is really a constant global we are gepping, with an
7894   // initializer, and make sure the first IDX is really 0.
7895   GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
7896   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
7897       GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
7898       !cast<Constant>(GEP->getOperand(1))->isNullValue())
7899     return getCouldNotCompute();
7900 
7901   // Okay, we allow one non-constant index into the GEP instruction.
7902   Value *VarIdx = nullptr;
7903   std::vector<Constant*> Indexes;
7904   unsigned VarIdxNum = 0;
7905   for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
7906     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
7907       Indexes.push_back(CI);
7908     } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
7909       if (VarIdx) return getCouldNotCompute();  // Multiple non-constant idx's.
7910       VarIdx = GEP->getOperand(i);
7911       VarIdxNum = i-2;
7912       Indexes.push_back(nullptr);
7913     }
7914 
7915   // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
7916   if (!VarIdx)
7917     return getCouldNotCompute();
7918 
7919   // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
7920   // Check to see if X is a loop variant variable value now.
7921   const SCEV *Idx = getSCEV(VarIdx);
7922   Idx = getSCEVAtScope(Idx, L);
7923 
7924   // We can only recognize very limited forms of loop index expressions, in
7925   // particular, only affine AddRec's like {C1,+,C2}<L>.
7926   const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
7927   if (!IdxExpr || IdxExpr->getLoop() != L || !IdxExpr->isAffine() ||
7928       isLoopInvariant(IdxExpr, L) ||
7929       !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
7930       !isa<SCEVConstant>(IdxExpr->getOperand(1)))
7931     return getCouldNotCompute();
7932 
7933   unsigned MaxSteps = MaxBruteForceIterations;
7934   for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
7935     ConstantInt *ItCst = ConstantInt::get(
7936                            cast<IntegerType>(IdxExpr->getType()), IterationNum);
7937     ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
7938 
7939     // Form the GEP offset.
7940     Indexes[VarIdxNum] = Val;
7941 
7942     Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
7943                                                          Indexes);
7944     if (!Result) break;  // Cannot compute!
7945 
7946     // Evaluate the condition for this iteration.
7947     Result = ConstantExpr::getICmp(predicate, Result, RHS);
7948     if (!isa<ConstantInt>(Result)) break;  // Couldn't decide for sure
7949     if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
7950       ++NumArrayLenItCounts;
7951       return getConstant(ItCst);   // Found terminating iteration!
7952     }
7953   }
7954   return getCouldNotCompute();
7955 }
7956 
7957 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
7958     Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
7959   ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
7960   if (!RHS)
7961     return getCouldNotCompute();
7962 
7963   const BasicBlock *Latch = L->getLoopLatch();
7964   if (!Latch)
7965     return getCouldNotCompute();
7966 
7967   const BasicBlock *Predecessor = L->getLoopPredecessor();
7968   if (!Predecessor)
7969     return getCouldNotCompute();
7970 
7971   // Return true if V is of the form "LHS `shift_op` <positive constant>".
7972   // Return LHS in OutLHS and shift_opt in OutOpCode.
7973   auto MatchPositiveShift =
7974       [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
7975 
7976     using namespace PatternMatch;
7977 
7978     ConstantInt *ShiftAmt;
7979     if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7980       OutOpCode = Instruction::LShr;
7981     else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7982       OutOpCode = Instruction::AShr;
7983     else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7984       OutOpCode = Instruction::Shl;
7985     else
7986       return false;
7987 
7988     return ShiftAmt->getValue().isStrictlyPositive();
7989   };
7990 
7991   // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
7992   //
7993   // loop:
7994   //   %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
7995   //   %iv.shifted = lshr i32 %iv, <positive constant>
7996   //
7997   // Return true on a successful match.  Return the corresponding PHI node (%iv
7998   // above) in PNOut and the opcode of the shift operation in OpCodeOut.
7999   auto MatchShiftRecurrence =
8000       [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
8001     Optional<Instruction::BinaryOps> PostShiftOpCode;
8002 
8003     {
8004       Instruction::BinaryOps OpC;
8005       Value *V;
8006 
8007       // If we encounter a shift instruction, "peel off" the shift operation,
8008       // and remember that we did so.  Later when we inspect %iv's backedge
8009       // value, we will make sure that the backedge value uses the same
8010       // operation.
8011       //
8012       // Note: the peeled shift operation does not have to be the same
8013       // instruction as the one feeding into the PHI's backedge value.  We only
8014       // really care about it being the same *kind* of shift instruction --
8015       // that's all that is required for our later inferences to hold.
8016       if (MatchPositiveShift(LHS, V, OpC)) {
8017         PostShiftOpCode = OpC;
8018         LHS = V;
8019       }
8020     }
8021 
8022     PNOut = dyn_cast<PHINode>(LHS);
8023     if (!PNOut || PNOut->getParent() != L->getHeader())
8024       return false;
8025 
8026     Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
8027     Value *OpLHS;
8028 
8029     return
8030         // The backedge value for the PHI node must be a shift by a positive
8031         // amount
8032         MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
8033 
8034         // of the PHI node itself
8035         OpLHS == PNOut &&
8036 
8037         // and the kind of shift should be match the kind of shift we peeled
8038         // off, if any.
8039         (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut);
8040   };
8041 
8042   PHINode *PN;
8043   Instruction::BinaryOps OpCode;
8044   if (!MatchShiftRecurrence(LHS, PN, OpCode))
8045     return getCouldNotCompute();
8046 
8047   const DataLayout &DL = getDataLayout();
8048 
8049   // The key rationale for this optimization is that for some kinds of shift
8050   // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
8051   // within a finite number of iterations.  If the condition guarding the
8052   // backedge (in the sense that the backedge is taken if the condition is true)
8053   // is false for the value the shift recurrence stabilizes to, then we know
8054   // that the backedge is taken only a finite number of times.
8055 
8056   ConstantInt *StableValue = nullptr;
8057   switch (OpCode) {
8058   default:
8059     llvm_unreachable("Impossible case!");
8060 
8061   case Instruction::AShr: {
8062     // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
8063     // bitwidth(K) iterations.
8064     Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
8065     KnownBits Known = computeKnownBits(FirstValue, DL, 0, &AC,
8066                                        Predecessor->getTerminator(), &DT);
8067     auto *Ty = cast<IntegerType>(RHS->getType());
8068     if (Known.isNonNegative())
8069       StableValue = ConstantInt::get(Ty, 0);
8070     else if (Known.isNegative())
8071       StableValue = ConstantInt::get(Ty, -1, true);
8072     else
8073       return getCouldNotCompute();
8074 
8075     break;
8076   }
8077   case Instruction::LShr:
8078   case Instruction::Shl:
8079     // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
8080     // stabilize to 0 in at most bitwidth(K) iterations.
8081     StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
8082     break;
8083   }
8084 
8085   auto *Result =
8086       ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
8087   assert(Result->getType()->isIntegerTy(1) &&
8088          "Otherwise cannot be an operand to a branch instruction");
8089 
8090   if (Result->isZeroValue()) {
8091     unsigned BitWidth = getTypeSizeInBits(RHS->getType());
8092     const SCEV *UpperBound =
8093         getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
8094     return ExitLimit(getCouldNotCompute(), UpperBound, false);
8095   }
8096 
8097   return getCouldNotCompute();
8098 }
8099 
8100 /// Return true if we can constant fold an instruction of the specified type,
8101 /// assuming that all operands were constants.
8102 static bool CanConstantFold(const Instruction *I) {
8103   if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
8104       isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
8105       isa<LoadInst>(I) || isa<ExtractValueInst>(I))
8106     return true;
8107 
8108   if (const CallInst *CI = dyn_cast<CallInst>(I))
8109     if (const Function *F = CI->getCalledFunction())
8110       return canConstantFoldCallTo(CI, F);
8111   return false;
8112 }
8113 
8114 /// Determine whether this instruction can constant evolve within this loop
8115 /// assuming its operands can all constant evolve.
8116 static bool canConstantEvolve(Instruction *I, const Loop *L) {
8117   // An instruction outside of the loop can't be derived from a loop PHI.
8118   if (!L->contains(I)) return false;
8119 
8120   if (isa<PHINode>(I)) {
8121     // We don't currently keep track of the control flow needed to evaluate
8122     // PHIs, so we cannot handle PHIs inside of loops.
8123     return L->getHeader() == I->getParent();
8124   }
8125 
8126   // If we won't be able to constant fold this expression even if the operands
8127   // are constants, bail early.
8128   return CanConstantFold(I);
8129 }
8130 
8131 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
8132 /// recursing through each instruction operand until reaching a loop header phi.
8133 static PHINode *
8134 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
8135                                DenseMap<Instruction *, PHINode *> &PHIMap,
8136                                unsigned Depth) {
8137   if (Depth > MaxConstantEvolvingDepth)
8138     return nullptr;
8139 
8140   // Otherwise, we can evaluate this instruction if all of its operands are
8141   // constant or derived from a PHI node themselves.
8142   PHINode *PHI = nullptr;
8143   for (Value *Op : UseInst->operands()) {
8144     if (isa<Constant>(Op)) continue;
8145 
8146     Instruction *OpInst = dyn_cast<Instruction>(Op);
8147     if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
8148 
8149     PHINode *P = dyn_cast<PHINode>(OpInst);
8150     if (!P)
8151       // If this operand is already visited, reuse the prior result.
8152       // We may have P != PHI if this is the deepest point at which the
8153       // inconsistent paths meet.
8154       P = PHIMap.lookup(OpInst);
8155     if (!P) {
8156       // Recurse and memoize the results, whether a phi is found or not.
8157       // This recursive call invalidates pointers into PHIMap.
8158       P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1);
8159       PHIMap[OpInst] = P;
8160     }
8161     if (!P)
8162       return nullptr;  // Not evolving from PHI
8163     if (PHI && PHI != P)
8164       return nullptr;  // Evolving from multiple different PHIs.
8165     PHI = P;
8166   }
8167   // This is a expression evolving from a constant PHI!
8168   return PHI;
8169 }
8170 
8171 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
8172 /// in the loop that V is derived from.  We allow arbitrary operations along the
8173 /// way, but the operands of an operation must either be constants or a value
8174 /// derived from a constant PHI.  If this expression does not fit with these
8175 /// constraints, return null.
8176 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
8177   Instruction *I = dyn_cast<Instruction>(V);
8178   if (!I || !canConstantEvolve(I, L)) return nullptr;
8179 
8180   if (PHINode *PN = dyn_cast<PHINode>(I))
8181     return PN;
8182 
8183   // Record non-constant instructions contained by the loop.
8184   DenseMap<Instruction *, PHINode *> PHIMap;
8185   return getConstantEvolvingPHIOperands(I, L, PHIMap, 0);
8186 }
8187 
8188 /// EvaluateExpression - Given an expression that passes the
8189 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
8190 /// in the loop has the value PHIVal.  If we can't fold this expression for some
8191 /// reason, return null.
8192 static Constant *EvaluateExpression(Value *V, const Loop *L,
8193                                     DenseMap<Instruction *, Constant *> &Vals,
8194                                     const DataLayout &DL,
8195                                     const TargetLibraryInfo *TLI) {
8196   // Convenient constant check, but redundant for recursive calls.
8197   if (Constant *C = dyn_cast<Constant>(V)) return C;
8198   Instruction *I = dyn_cast<Instruction>(V);
8199   if (!I) return nullptr;
8200 
8201   if (Constant *C = Vals.lookup(I)) return C;
8202 
8203   // An instruction inside the loop depends on a value outside the loop that we
8204   // weren't given a mapping for, or a value such as a call inside the loop.
8205   if (!canConstantEvolve(I, L)) return nullptr;
8206 
8207   // An unmapped PHI can be due to a branch or another loop inside this loop,
8208   // or due to this not being the initial iteration through a loop where we
8209   // couldn't compute the evolution of this particular PHI last time.
8210   if (isa<PHINode>(I)) return nullptr;
8211 
8212   std::vector<Constant*> Operands(I->getNumOperands());
8213 
8214   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
8215     Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
8216     if (!Operand) {
8217       Operands[i] = dyn_cast<Constant>(I->getOperand(i));
8218       if (!Operands[i]) return nullptr;
8219       continue;
8220     }
8221     Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
8222     Vals[Operand] = C;
8223     if (!C) return nullptr;
8224     Operands[i] = C;
8225   }
8226 
8227   if (CmpInst *CI = dyn_cast<CmpInst>(I))
8228     return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
8229                                            Operands[1], DL, TLI);
8230   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
8231     if (!LI->isVolatile())
8232       return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
8233   }
8234   return ConstantFoldInstOperands(I, Operands, DL, TLI);
8235 }
8236 
8237 
8238 // If every incoming value to PN except the one for BB is a specific Constant,
8239 // return that, else return nullptr.
8240 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
8241   Constant *IncomingVal = nullptr;
8242 
8243   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
8244     if (PN->getIncomingBlock(i) == BB)
8245       continue;
8246 
8247     auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
8248     if (!CurrentVal)
8249       return nullptr;
8250 
8251     if (IncomingVal != CurrentVal) {
8252       if (IncomingVal)
8253         return nullptr;
8254       IncomingVal = CurrentVal;
8255     }
8256   }
8257 
8258   return IncomingVal;
8259 }
8260 
8261 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
8262 /// in the header of its containing loop, we know the loop executes a
8263 /// constant number of times, and the PHI node is just a recurrence
8264 /// involving constants, fold it.
8265 Constant *
8266 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
8267                                                    const APInt &BEs,
8268                                                    const Loop *L) {
8269   auto I = ConstantEvolutionLoopExitValue.find(PN);
8270   if (I != ConstantEvolutionLoopExitValue.end())
8271     return I->second;
8272 
8273   if (BEs.ugt(MaxBruteForceIterations))
8274     return ConstantEvolutionLoopExitValue[PN] = nullptr;  // Not going to evaluate it.
8275 
8276   Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
8277 
8278   DenseMap<Instruction *, Constant *> CurrentIterVals;
8279   BasicBlock *Header = L->getHeader();
8280   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
8281 
8282   BasicBlock *Latch = L->getLoopLatch();
8283   if (!Latch)
8284     return nullptr;
8285 
8286   for (PHINode &PHI : Header->phis()) {
8287     if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
8288       CurrentIterVals[&PHI] = StartCST;
8289   }
8290   if (!CurrentIterVals.count(PN))
8291     return RetVal = nullptr;
8292 
8293   Value *BEValue = PN->getIncomingValueForBlock(Latch);
8294 
8295   // Execute the loop symbolically to determine the exit value.
8296   assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) &&
8297          "BEs is <= MaxBruteForceIterations which is an 'unsigned'!");
8298 
8299   unsigned NumIterations = BEs.getZExtValue(); // must be in range
8300   unsigned IterationNum = 0;
8301   const DataLayout &DL = getDataLayout();
8302   for (; ; ++IterationNum) {
8303     if (IterationNum == NumIterations)
8304       return RetVal = CurrentIterVals[PN];  // Got exit value!
8305 
8306     // Compute the value of the PHIs for the next iteration.
8307     // EvaluateExpression adds non-phi values to the CurrentIterVals map.
8308     DenseMap<Instruction *, Constant *> NextIterVals;
8309     Constant *NextPHI =
8310         EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
8311     if (!NextPHI)
8312       return nullptr;        // Couldn't evaluate!
8313     NextIterVals[PN] = NextPHI;
8314 
8315     bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
8316 
8317     // Also evaluate the other PHI nodes.  However, we don't get to stop if we
8318     // cease to be able to evaluate one of them or if they stop evolving,
8319     // because that doesn't necessarily prevent us from computing PN.
8320     SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
8321     for (const auto &I : CurrentIterVals) {
8322       PHINode *PHI = dyn_cast<PHINode>(I.first);
8323       if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
8324       PHIsToCompute.emplace_back(PHI, I.second);
8325     }
8326     // We use two distinct loops because EvaluateExpression may invalidate any
8327     // iterators into CurrentIterVals.
8328     for (const auto &I : PHIsToCompute) {
8329       PHINode *PHI = I.first;
8330       Constant *&NextPHI = NextIterVals[PHI];
8331       if (!NextPHI) {   // Not already computed.
8332         Value *BEValue = PHI->getIncomingValueForBlock(Latch);
8333         NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
8334       }
8335       if (NextPHI != I.second)
8336         StoppedEvolving = false;
8337     }
8338 
8339     // If all entries in CurrentIterVals == NextIterVals then we can stop
8340     // iterating, the loop can't continue to change.
8341     if (StoppedEvolving)
8342       return RetVal = CurrentIterVals[PN];
8343 
8344     CurrentIterVals.swap(NextIterVals);
8345   }
8346 }
8347 
8348 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
8349                                                           Value *Cond,
8350                                                           bool ExitWhen) {
8351   PHINode *PN = getConstantEvolvingPHI(Cond, L);
8352   if (!PN) return getCouldNotCompute();
8353 
8354   // If the loop is canonicalized, the PHI will have exactly two entries.
8355   // That's the only form we support here.
8356   if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
8357 
8358   DenseMap<Instruction *, Constant *> CurrentIterVals;
8359   BasicBlock *Header = L->getHeader();
8360   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
8361 
8362   BasicBlock *Latch = L->getLoopLatch();
8363   assert(Latch && "Should follow from NumIncomingValues == 2!");
8364 
8365   for (PHINode &PHI : Header->phis()) {
8366     if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
8367       CurrentIterVals[&PHI] = StartCST;
8368   }
8369   if (!CurrentIterVals.count(PN))
8370     return getCouldNotCompute();
8371 
8372   // Okay, we find a PHI node that defines the trip count of this loop.  Execute
8373   // the loop symbolically to determine when the condition gets a value of
8374   // "ExitWhen".
8375   unsigned MaxIterations = MaxBruteForceIterations;   // Limit analysis.
8376   const DataLayout &DL = getDataLayout();
8377   for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
8378     auto *CondVal = dyn_cast_or_null<ConstantInt>(
8379         EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
8380 
8381     // Couldn't symbolically evaluate.
8382     if (!CondVal) return getCouldNotCompute();
8383 
8384     if (CondVal->getValue() == uint64_t(ExitWhen)) {
8385       ++NumBruteForceTripCountsComputed;
8386       return getConstant(Type::getInt32Ty(getContext()), IterationNum);
8387     }
8388 
8389     // Update all the PHI nodes for the next iteration.
8390     DenseMap<Instruction *, Constant *> NextIterVals;
8391 
8392     // Create a list of which PHIs we need to compute. We want to do this before
8393     // calling EvaluateExpression on them because that may invalidate iterators
8394     // into CurrentIterVals.
8395     SmallVector<PHINode *, 8> PHIsToCompute;
8396     for (const auto &I : CurrentIterVals) {
8397       PHINode *PHI = dyn_cast<PHINode>(I.first);
8398       if (!PHI || PHI->getParent() != Header) continue;
8399       PHIsToCompute.push_back(PHI);
8400     }
8401     for (PHINode *PHI : PHIsToCompute) {
8402       Constant *&NextPHI = NextIterVals[PHI];
8403       if (NextPHI) continue;    // Already computed!
8404 
8405       Value *BEValue = PHI->getIncomingValueForBlock(Latch);
8406       NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
8407     }
8408     CurrentIterVals.swap(NextIterVals);
8409   }
8410 
8411   // Too many iterations were needed to evaluate.
8412   return getCouldNotCompute();
8413 }
8414 
8415 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
8416   SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
8417       ValuesAtScopes[V];
8418   // Check to see if we've folded this expression at this loop before.
8419   for (auto &LS : Values)
8420     if (LS.first == L)
8421       return LS.second ? LS.second : V;
8422 
8423   Values.emplace_back(L, nullptr);
8424 
8425   // Otherwise compute it.
8426   const SCEV *C = computeSCEVAtScope(V, L);
8427   for (auto &LS : reverse(ValuesAtScopes[V]))
8428     if (LS.first == L) {
8429       LS.second = C;
8430       break;
8431     }
8432   return C;
8433 }
8434 
8435 /// This builds up a Constant using the ConstantExpr interface.  That way, we
8436 /// will return Constants for objects which aren't represented by a
8437 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
8438 /// Returns NULL if the SCEV isn't representable as a Constant.
8439 static Constant *BuildConstantFromSCEV(const SCEV *V) {
8440   switch (V->getSCEVType()) {
8441   case scCouldNotCompute:
8442   case scAddRecExpr:
8443     return nullptr;
8444   case scConstant:
8445     return cast<SCEVConstant>(V)->getValue();
8446   case scUnknown:
8447     return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
8448   case scSignExtend: {
8449     const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
8450     if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
8451       return ConstantExpr::getSExt(CastOp, SS->getType());
8452     return nullptr;
8453   }
8454   case scZeroExtend: {
8455     const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
8456     if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
8457       return ConstantExpr::getZExt(CastOp, SZ->getType());
8458     return nullptr;
8459   }
8460   case scPtrToInt: {
8461     const SCEVPtrToIntExpr *P2I = cast<SCEVPtrToIntExpr>(V);
8462     if (Constant *CastOp = BuildConstantFromSCEV(P2I->getOperand()))
8463       return ConstantExpr::getPtrToInt(CastOp, P2I->getType());
8464 
8465     return nullptr;
8466   }
8467   case scTruncate: {
8468     const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
8469     if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
8470       return ConstantExpr::getTrunc(CastOp, ST->getType());
8471     return nullptr;
8472   }
8473   case scAddExpr: {
8474     const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
8475     if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
8476       if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
8477         unsigned AS = PTy->getAddressSpace();
8478         Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
8479         C = ConstantExpr::getBitCast(C, DestPtrTy);
8480       }
8481       for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
8482         Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
8483         if (!C2)
8484           return nullptr;
8485 
8486         // First pointer!
8487         if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
8488           unsigned AS = C2->getType()->getPointerAddressSpace();
8489           std::swap(C, C2);
8490           Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
8491           // The offsets have been converted to bytes.  We can add bytes to an
8492           // i8* by GEP with the byte count in the first index.
8493           C = ConstantExpr::getBitCast(C, DestPtrTy);
8494         }
8495 
8496         // Don't bother trying to sum two pointers. We probably can't
8497         // statically compute a load that results from it anyway.
8498         if (C2->getType()->isPointerTy())
8499           return nullptr;
8500 
8501         if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
8502           if (PTy->getElementType()->isStructTy())
8503             C2 = ConstantExpr::getIntegerCast(
8504                 C2, Type::getInt32Ty(C->getContext()), true);
8505           C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2);
8506         } else
8507           C = ConstantExpr::getAdd(C, C2);
8508       }
8509       return C;
8510     }
8511     return nullptr;
8512   }
8513   case scMulExpr: {
8514     const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
8515     if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
8516       // Don't bother with pointers at all.
8517       if (C->getType()->isPointerTy())
8518         return nullptr;
8519       for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
8520         Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
8521         if (!C2 || C2->getType()->isPointerTy())
8522           return nullptr;
8523         C = ConstantExpr::getMul(C, C2);
8524       }
8525       return C;
8526     }
8527     return nullptr;
8528   }
8529   case scUDivExpr: {
8530     const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
8531     if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
8532       if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
8533         if (LHS->getType() == RHS->getType())
8534           return ConstantExpr::getUDiv(LHS, RHS);
8535     return nullptr;
8536   }
8537   case scSMaxExpr:
8538   case scUMaxExpr:
8539   case scSMinExpr:
8540   case scUMinExpr:
8541     return nullptr; // TODO: smax, umax, smin, umax.
8542   }
8543   llvm_unreachable("Unknown SCEV kind!");
8544 }
8545 
8546 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
8547   if (isa<SCEVConstant>(V)) return V;
8548 
8549   // If this instruction is evolved from a constant-evolving PHI, compute the
8550   // exit value from the loop without using SCEVs.
8551   if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
8552     if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
8553       if (PHINode *PN = dyn_cast<PHINode>(I)) {
8554         const Loop *CurrLoop = this->LI[I->getParent()];
8555         // Looking for loop exit value.
8556         if (CurrLoop && CurrLoop->getParentLoop() == L &&
8557             PN->getParent() == CurrLoop->getHeader()) {
8558           // Okay, there is no closed form solution for the PHI node.  Check
8559           // to see if the loop that contains it has a known backedge-taken
8560           // count.  If so, we may be able to force computation of the exit
8561           // value.
8562           const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop);
8563           // This trivial case can show up in some degenerate cases where
8564           // the incoming IR has not yet been fully simplified.
8565           if (BackedgeTakenCount->isZero()) {
8566             Value *InitValue = nullptr;
8567             bool MultipleInitValues = false;
8568             for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
8569               if (!CurrLoop->contains(PN->getIncomingBlock(i))) {
8570                 if (!InitValue)
8571                   InitValue = PN->getIncomingValue(i);
8572                 else if (InitValue != PN->getIncomingValue(i)) {
8573                   MultipleInitValues = true;
8574                   break;
8575                 }
8576               }
8577             }
8578             if (!MultipleInitValues && InitValue)
8579               return getSCEV(InitValue);
8580           }
8581           // Do we have a loop invariant value flowing around the backedge
8582           // for a loop which must execute the backedge?
8583           if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
8584               isKnownPositive(BackedgeTakenCount) &&
8585               PN->getNumIncomingValues() == 2) {
8586 
8587             unsigned InLoopPred =
8588                 CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1;
8589             Value *BackedgeVal = PN->getIncomingValue(InLoopPred);
8590             if (CurrLoop->isLoopInvariant(BackedgeVal))
8591               return getSCEV(BackedgeVal);
8592           }
8593           if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
8594             // Okay, we know how many times the containing loop executes.  If
8595             // this is a constant evolving PHI node, get the final value at
8596             // the specified iteration number.
8597             Constant *RV = getConstantEvolutionLoopExitValue(
8598                 PN, BTCC->getAPInt(), CurrLoop);
8599             if (RV) return getSCEV(RV);
8600           }
8601         }
8602 
8603         // If there is a single-input Phi, evaluate it at our scope. If we can
8604         // prove that this replacement does not break LCSSA form, use new value.
8605         if (PN->getNumOperands() == 1) {
8606           const SCEV *Input = getSCEV(PN->getOperand(0));
8607           const SCEV *InputAtScope = getSCEVAtScope(Input, L);
8608           // TODO: We can generalize it using LI.replacementPreservesLCSSAForm,
8609           // for the simplest case just support constants.
8610           if (isa<SCEVConstant>(InputAtScope)) return InputAtScope;
8611         }
8612       }
8613 
8614       // Okay, this is an expression that we cannot symbolically evaluate
8615       // into a SCEV.  Check to see if it's possible to symbolically evaluate
8616       // the arguments into constants, and if so, try to constant propagate the
8617       // result.  This is particularly useful for computing loop exit values.
8618       if (CanConstantFold(I)) {
8619         SmallVector<Constant *, 4> Operands;
8620         bool MadeImprovement = false;
8621         for (Value *Op : I->operands()) {
8622           if (Constant *C = dyn_cast<Constant>(Op)) {
8623             Operands.push_back(C);
8624             continue;
8625           }
8626 
8627           // If any of the operands is non-constant and if they are
8628           // non-integer and non-pointer, don't even try to analyze them
8629           // with scev techniques.
8630           if (!isSCEVable(Op->getType()))
8631             return V;
8632 
8633           const SCEV *OrigV = getSCEV(Op);
8634           const SCEV *OpV = getSCEVAtScope(OrigV, L);
8635           MadeImprovement |= OrigV != OpV;
8636 
8637           Constant *C = BuildConstantFromSCEV(OpV);
8638           if (!C) return V;
8639           if (C->getType() != Op->getType())
8640             C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
8641                                                               Op->getType(),
8642                                                               false),
8643                                       C, Op->getType());
8644           Operands.push_back(C);
8645         }
8646 
8647         // Check to see if getSCEVAtScope actually made an improvement.
8648         if (MadeImprovement) {
8649           Constant *C = nullptr;
8650           const DataLayout &DL = getDataLayout();
8651           if (const CmpInst *CI = dyn_cast<CmpInst>(I))
8652             C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
8653                                                 Operands[1], DL, &TLI);
8654           else if (const LoadInst *Load = dyn_cast<LoadInst>(I)) {
8655             if (!Load->isVolatile())
8656               C = ConstantFoldLoadFromConstPtr(Operands[0], Load->getType(),
8657                                                DL);
8658           } else
8659             C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
8660           if (!C) return V;
8661           return getSCEV(C);
8662         }
8663       }
8664     }
8665 
8666     // This is some other type of SCEVUnknown, just return it.
8667     return V;
8668   }
8669 
8670   if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
8671     // Avoid performing the look-up in the common case where the specified
8672     // expression has no loop-variant portions.
8673     for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
8674       const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
8675       if (OpAtScope != Comm->getOperand(i)) {
8676         // Okay, at least one of these operands is loop variant but might be
8677         // foldable.  Build a new instance of the folded commutative expression.
8678         SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
8679                                             Comm->op_begin()+i);
8680         NewOps.push_back(OpAtScope);
8681 
8682         for (++i; i != e; ++i) {
8683           OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
8684           NewOps.push_back(OpAtScope);
8685         }
8686         if (isa<SCEVAddExpr>(Comm))
8687           return getAddExpr(NewOps, Comm->getNoWrapFlags());
8688         if (isa<SCEVMulExpr>(Comm))
8689           return getMulExpr(NewOps, Comm->getNoWrapFlags());
8690         if (isa<SCEVMinMaxExpr>(Comm))
8691           return getMinMaxExpr(Comm->getSCEVType(), NewOps);
8692         llvm_unreachable("Unknown commutative SCEV type!");
8693       }
8694     }
8695     // If we got here, all operands are loop invariant.
8696     return Comm;
8697   }
8698 
8699   if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
8700     const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
8701     const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
8702     if (LHS == Div->getLHS() && RHS == Div->getRHS())
8703       return Div;   // must be loop invariant
8704     return getUDivExpr(LHS, RHS);
8705   }
8706 
8707   // If this is a loop recurrence for a loop that does not contain L, then we
8708   // are dealing with the final value computed by the loop.
8709   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
8710     // First, attempt to evaluate each operand.
8711     // Avoid performing the look-up in the common case where the specified
8712     // expression has no loop-variant portions.
8713     for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
8714       const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
8715       if (OpAtScope == AddRec->getOperand(i))
8716         continue;
8717 
8718       // Okay, at least one of these operands is loop variant but might be
8719       // foldable.  Build a new instance of the folded commutative expression.
8720       SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
8721                                           AddRec->op_begin()+i);
8722       NewOps.push_back(OpAtScope);
8723       for (++i; i != e; ++i)
8724         NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
8725 
8726       const SCEV *FoldedRec =
8727         getAddRecExpr(NewOps, AddRec->getLoop(),
8728                       AddRec->getNoWrapFlags(SCEV::FlagNW));
8729       AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
8730       // The addrec may be folded to a nonrecurrence, for example, if the
8731       // induction variable is multiplied by zero after constant folding. Go
8732       // ahead and return the folded value.
8733       if (!AddRec)
8734         return FoldedRec;
8735       break;
8736     }
8737 
8738     // If the scope is outside the addrec's loop, evaluate it by using the
8739     // loop exit value of the addrec.
8740     if (!AddRec->getLoop()->contains(L)) {
8741       // To evaluate this recurrence, we need to know how many times the AddRec
8742       // loop iterates.  Compute this now.
8743       const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
8744       if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
8745 
8746       // Then, evaluate the AddRec.
8747       return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
8748     }
8749 
8750     return AddRec;
8751   }
8752 
8753   if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
8754     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8755     if (Op == Cast->getOperand())
8756       return Cast;  // must be loop invariant
8757     return getZeroExtendExpr(Op, Cast->getType());
8758   }
8759 
8760   if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
8761     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8762     if (Op == Cast->getOperand())
8763       return Cast;  // must be loop invariant
8764     return getSignExtendExpr(Op, Cast->getType());
8765   }
8766 
8767   if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
8768     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8769     if (Op == Cast->getOperand())
8770       return Cast;  // must be loop invariant
8771     return getTruncateExpr(Op, Cast->getType());
8772   }
8773 
8774   if (const SCEVPtrToIntExpr *Cast = dyn_cast<SCEVPtrToIntExpr>(V)) {
8775     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8776     if (Op == Cast->getOperand())
8777       return Cast; // must be loop invariant
8778     return getPtrToIntExpr(Op, Cast->getType());
8779   }
8780 
8781   llvm_unreachable("Unknown SCEV type!");
8782 }
8783 
8784 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
8785   return getSCEVAtScope(getSCEV(V), L);
8786 }
8787 
8788 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const {
8789   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S))
8790     return stripInjectiveFunctions(ZExt->getOperand());
8791   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S))
8792     return stripInjectiveFunctions(SExt->getOperand());
8793   return S;
8794 }
8795 
8796 /// Finds the minimum unsigned root of the following equation:
8797 ///
8798 ///     A * X = B (mod N)
8799 ///
8800 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
8801 /// A and B isn't important.
8802 ///
8803 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
8804 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B,
8805                                                ScalarEvolution &SE) {
8806   uint32_t BW = A.getBitWidth();
8807   assert(BW == SE.getTypeSizeInBits(B->getType()));
8808   assert(A != 0 && "A must be non-zero.");
8809 
8810   // 1. D = gcd(A, N)
8811   //
8812   // The gcd of A and N may have only one prime factor: 2. The number of
8813   // trailing zeros in A is its multiplicity
8814   uint32_t Mult2 = A.countTrailingZeros();
8815   // D = 2^Mult2
8816 
8817   // 2. Check if B is divisible by D.
8818   //
8819   // B is divisible by D if and only if the multiplicity of prime factor 2 for B
8820   // is not less than multiplicity of this prime factor for D.
8821   if (SE.GetMinTrailingZeros(B) < Mult2)
8822     return SE.getCouldNotCompute();
8823 
8824   // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
8825   // modulo (N / D).
8826   //
8827   // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
8828   // (N / D) in general. The inverse itself always fits into BW bits, though,
8829   // so we immediately truncate it.
8830   APInt AD = A.lshr(Mult2).zext(BW + 1);  // AD = A / D
8831   APInt Mod(BW + 1, 0);
8832   Mod.setBit(BW - Mult2);  // Mod = N / D
8833   APInt I = AD.multiplicativeInverse(Mod).trunc(BW);
8834 
8835   // 4. Compute the minimum unsigned root of the equation:
8836   // I * (B / D) mod (N / D)
8837   // To simplify the computation, we factor out the divide by D:
8838   // (I * B mod N) / D
8839   const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
8840   return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
8841 }
8842 
8843 /// For a given quadratic addrec, generate coefficients of the corresponding
8844 /// quadratic equation, multiplied by a common value to ensure that they are
8845 /// integers.
8846 /// The returned value is a tuple { A, B, C, M, BitWidth }, where
8847 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C
8848 /// were multiplied by, and BitWidth is the bit width of the original addrec
8849 /// coefficients.
8850 /// This function returns None if the addrec coefficients are not compile-
8851 /// time constants.
8852 static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>>
8853 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) {
8854   assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
8855   const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
8856   const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
8857   const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
8858   LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: "
8859                     << *AddRec << '\n');
8860 
8861   // We currently can only solve this if the coefficients are constants.
8862   if (!LC || !MC || !NC) {
8863     LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n");
8864     return None;
8865   }
8866 
8867   APInt L = LC->getAPInt();
8868   APInt M = MC->getAPInt();
8869   APInt N = NC->getAPInt();
8870   assert(!N.isNullValue() && "This is not a quadratic addrec");
8871 
8872   unsigned BitWidth = LC->getAPInt().getBitWidth();
8873   unsigned NewWidth = BitWidth + 1;
8874   LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: "
8875                     << BitWidth << '\n');
8876   // The sign-extension (as opposed to a zero-extension) here matches the
8877   // extension used in SolveQuadraticEquationWrap (with the same motivation).
8878   N = N.sext(NewWidth);
8879   M = M.sext(NewWidth);
8880   L = L.sext(NewWidth);
8881 
8882   // The increments are M, M+N, M+2N, ..., so the accumulated values are
8883   //   L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is,
8884   //   L+M, L+2M+N, L+3M+3N, ...
8885   // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N.
8886   //
8887   // The equation Acc = 0 is then
8888   //   L + nM + n(n-1)/2 N = 0,  or  2L + 2M n + n(n-1) N = 0.
8889   // In a quadratic form it becomes:
8890   //   N n^2 + (2M-N) n + 2L = 0.
8891 
8892   APInt A = N;
8893   APInt B = 2 * M - A;
8894   APInt C = 2 * L;
8895   APInt T = APInt(NewWidth, 2);
8896   LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B
8897                     << "x + " << C << ", coeff bw: " << NewWidth
8898                     << ", multiplied by " << T << '\n');
8899   return std::make_tuple(A, B, C, T, BitWidth);
8900 }
8901 
8902 /// Helper function to compare optional APInts:
8903 /// (a) if X and Y both exist, return min(X, Y),
8904 /// (b) if neither X nor Y exist, return None,
8905 /// (c) if exactly one of X and Y exists, return that value.
8906 static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) {
8907   if (X.hasValue() && Y.hasValue()) {
8908     unsigned W = std::max(X->getBitWidth(), Y->getBitWidth());
8909     APInt XW = X->sextOrSelf(W);
8910     APInt YW = Y->sextOrSelf(W);
8911     return XW.slt(YW) ? *X : *Y;
8912   }
8913   if (!X.hasValue() && !Y.hasValue())
8914     return None;
8915   return X.hasValue() ? *X : *Y;
8916 }
8917 
8918 /// Helper function to truncate an optional APInt to a given BitWidth.
8919 /// When solving addrec-related equations, it is preferable to return a value
8920 /// that has the same bit width as the original addrec's coefficients. If the
8921 /// solution fits in the original bit width, truncate it (except for i1).
8922 /// Returning a value of a different bit width may inhibit some optimizations.
8923 ///
8924 /// In general, a solution to a quadratic equation generated from an addrec
8925 /// may require BW+1 bits, where BW is the bit width of the addrec's
8926 /// coefficients. The reason is that the coefficients of the quadratic
8927 /// equation are BW+1 bits wide (to avoid truncation when converting from
8928 /// the addrec to the equation).
8929 static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) {
8930   if (!X.hasValue())
8931     return None;
8932   unsigned W = X->getBitWidth();
8933   if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth))
8934     return X->trunc(BitWidth);
8935   return X;
8936 }
8937 
8938 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n
8939 /// iterations. The values L, M, N are assumed to be signed, and they
8940 /// should all have the same bit widths.
8941 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW,
8942 /// where BW is the bit width of the addrec's coefficients.
8943 /// If the calculated value is a BW-bit integer (for BW > 1), it will be
8944 /// returned as such, otherwise the bit width of the returned value may
8945 /// be greater than BW.
8946 ///
8947 /// This function returns None if
8948 /// (a) the addrec coefficients are not constant, or
8949 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases
8950 ///     like x^2 = 5, no integer solutions exist, in other cases an integer
8951 ///     solution may exist, but SolveQuadraticEquationWrap may fail to find it.
8952 static Optional<APInt>
8953 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
8954   APInt A, B, C, M;
8955   unsigned BitWidth;
8956   auto T = GetQuadraticEquation(AddRec);
8957   if (!T.hasValue())
8958     return None;
8959 
8960   std::tie(A, B, C, M, BitWidth) = *T;
8961   LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n");
8962   Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1);
8963   if (!X.hasValue())
8964     return None;
8965 
8966   ConstantInt *CX = ConstantInt::get(SE.getContext(), *X);
8967   ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE);
8968   if (!V->isZero())
8969     return None;
8970 
8971   return TruncIfPossible(X, BitWidth);
8972 }
8973 
8974 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n
8975 /// iterations. The values M, N are assumed to be signed, and they
8976 /// should all have the same bit widths.
8977 /// Find the least n such that c(n) does not belong to the given range,
8978 /// while c(n-1) does.
8979 ///
8980 /// This function returns None if
8981 /// (a) the addrec coefficients are not constant, or
8982 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the
8983 ///     bounds of the range.
8984 static Optional<APInt>
8985 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec,
8986                           const ConstantRange &Range, ScalarEvolution &SE) {
8987   assert(AddRec->getOperand(0)->isZero() &&
8988          "Starting value of addrec should be 0");
8989   LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range "
8990                     << Range << ", addrec " << *AddRec << '\n');
8991   // This case is handled in getNumIterationsInRange. Here we can assume that
8992   // we start in the range.
8993   assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) &&
8994          "Addrec's initial value should be in range");
8995 
8996   APInt A, B, C, M;
8997   unsigned BitWidth;
8998   auto T = GetQuadraticEquation(AddRec);
8999   if (!T.hasValue())
9000     return None;
9001 
9002   // Be careful about the return value: there can be two reasons for not
9003   // returning an actual number. First, if no solutions to the equations
9004   // were found, and second, if the solutions don't leave the given range.
9005   // The first case means that the actual solution is "unknown", the second
9006   // means that it's known, but not valid. If the solution is unknown, we
9007   // cannot make any conclusions.
9008   // Return a pair: the optional solution and a flag indicating if the
9009   // solution was found.
9010   auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> {
9011     // Solve for signed overflow and unsigned overflow, pick the lower
9012     // solution.
9013     LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary "
9014                       << Bound << " (before multiplying by " << M << ")\n");
9015     Bound *= M; // The quadratic equation multiplier.
9016 
9017     Optional<APInt> SO = None;
9018     if (BitWidth > 1) {
9019       LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
9020                            "signed overflow\n");
9021       SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth);
9022     }
9023     LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
9024                          "unsigned overflow\n");
9025     Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound,
9026                                                               BitWidth+1);
9027 
9028     auto LeavesRange = [&] (const APInt &X) {
9029       ConstantInt *C0 = ConstantInt::get(SE.getContext(), X);
9030       ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE);
9031       if (Range.contains(V0->getValue()))
9032         return false;
9033       // X should be at least 1, so X-1 is non-negative.
9034       ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1);
9035       ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE);
9036       if (Range.contains(V1->getValue()))
9037         return true;
9038       return false;
9039     };
9040 
9041     // If SolveQuadraticEquationWrap returns None, it means that there can
9042     // be a solution, but the function failed to find it. We cannot treat it
9043     // as "no solution".
9044     if (!SO.hasValue() || !UO.hasValue())
9045       return { None, false };
9046 
9047     // Check the smaller value first to see if it leaves the range.
9048     // At this point, both SO and UO must have values.
9049     Optional<APInt> Min = MinOptional(SO, UO);
9050     if (LeavesRange(*Min))
9051       return { Min, true };
9052     Optional<APInt> Max = Min == SO ? UO : SO;
9053     if (LeavesRange(*Max))
9054       return { Max, true };
9055 
9056     // Solutions were found, but were eliminated, hence the "true".
9057     return { None, true };
9058   };
9059 
9060   std::tie(A, B, C, M, BitWidth) = *T;
9061   // Lower bound is inclusive, subtract 1 to represent the exiting value.
9062   APInt Lower = Range.getLower().sextOrSelf(A.getBitWidth()) - 1;
9063   APInt Upper = Range.getUpper().sextOrSelf(A.getBitWidth());
9064   auto SL = SolveForBoundary(Lower);
9065   auto SU = SolveForBoundary(Upper);
9066   // If any of the solutions was unknown, no meaninigful conclusions can
9067   // be made.
9068   if (!SL.second || !SU.second)
9069     return None;
9070 
9071   // Claim: The correct solution is not some value between Min and Max.
9072   //
9073   // Justification: Assuming that Min and Max are different values, one of
9074   // them is when the first signed overflow happens, the other is when the
9075   // first unsigned overflow happens. Crossing the range boundary is only
9076   // possible via an overflow (treating 0 as a special case of it, modeling
9077   // an overflow as crossing k*2^W for some k).
9078   //
9079   // The interesting case here is when Min was eliminated as an invalid
9080   // solution, but Max was not. The argument is that if there was another
9081   // overflow between Min and Max, it would also have been eliminated if
9082   // it was considered.
9083   //
9084   // For a given boundary, it is possible to have two overflows of the same
9085   // type (signed/unsigned) without having the other type in between: this
9086   // can happen when the vertex of the parabola is between the iterations
9087   // corresponding to the overflows. This is only possible when the two
9088   // overflows cross k*2^W for the same k. In such case, if the second one
9089   // left the range (and was the first one to do so), the first overflow
9090   // would have to enter the range, which would mean that either we had left
9091   // the range before or that we started outside of it. Both of these cases
9092   // are contradictions.
9093   //
9094   // Claim: In the case where SolveForBoundary returns None, the correct
9095   // solution is not some value between the Max for this boundary and the
9096   // Min of the other boundary.
9097   //
9098   // Justification: Assume that we had such Max_A and Min_B corresponding
9099   // to range boundaries A and B and such that Max_A < Min_B. If there was
9100   // a solution between Max_A and Min_B, it would have to be caused by an
9101   // overflow corresponding to either A or B. It cannot correspond to B,
9102   // since Min_B is the first occurrence of such an overflow. If it
9103   // corresponded to A, it would have to be either a signed or an unsigned
9104   // overflow that is larger than both eliminated overflows for A. But
9105   // between the eliminated overflows and this overflow, the values would
9106   // cover the entire value space, thus crossing the other boundary, which
9107   // is a contradiction.
9108 
9109   return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth);
9110 }
9111 
9112 ScalarEvolution::ExitLimit
9113 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit,
9114                               bool AllowPredicates) {
9115 
9116   // This is only used for loops with a "x != y" exit test. The exit condition
9117   // is now expressed as a single expression, V = x-y. So the exit test is
9118   // effectively V != 0.  We know and take advantage of the fact that this
9119   // expression only being used in a comparison by zero context.
9120 
9121   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
9122   // If the value is a constant
9123   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
9124     // If the value is already zero, the branch will execute zero times.
9125     if (C->getValue()->isZero()) return C;
9126     return getCouldNotCompute();  // Otherwise it will loop infinitely.
9127   }
9128 
9129   const SCEVAddRecExpr *AddRec =
9130       dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V));
9131 
9132   if (!AddRec && AllowPredicates)
9133     // Try to make this an AddRec using runtime tests, in the first X
9134     // iterations of this loop, where X is the SCEV expression found by the
9135     // algorithm below.
9136     AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
9137 
9138   if (!AddRec || AddRec->getLoop() != L)
9139     return getCouldNotCompute();
9140 
9141   // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
9142   // the quadratic equation to solve it.
9143   if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
9144     // We can only use this value if the chrec ends up with an exact zero
9145     // value at this index.  When solving for "X*X != 5", for example, we
9146     // should not accept a root of 2.
9147     if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) {
9148       const auto *R = cast<SCEVConstant>(getConstant(S.getValue()));
9149       return ExitLimit(R, R, false, Predicates);
9150     }
9151     return getCouldNotCompute();
9152   }
9153 
9154   // Otherwise we can only handle this if it is affine.
9155   if (!AddRec->isAffine())
9156     return getCouldNotCompute();
9157 
9158   // If this is an affine expression, the execution count of this branch is
9159   // the minimum unsigned root of the following equation:
9160   //
9161   //     Start + Step*N = 0 (mod 2^BW)
9162   //
9163   // equivalent to:
9164   //
9165   //             Step*N = -Start (mod 2^BW)
9166   //
9167   // where BW is the common bit width of Start and Step.
9168 
9169   // Get the initial value for the loop.
9170   const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
9171   const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
9172 
9173   // For now we handle only constant steps.
9174   //
9175   // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
9176   // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
9177   // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
9178   // We have not yet seen any such cases.
9179   const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
9180   if (!StepC || StepC->getValue()->isZero())
9181     return getCouldNotCompute();
9182 
9183   // For positive steps (counting up until unsigned overflow):
9184   //   N = -Start/Step (as unsigned)
9185   // For negative steps (counting down to zero):
9186   //   N = Start/-Step
9187   // First compute the unsigned distance from zero in the direction of Step.
9188   bool CountDown = StepC->getAPInt().isNegative();
9189   const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
9190 
9191   // Handle unitary steps, which cannot wraparound.
9192   // 1*N = -Start; -1*N = Start (mod 2^BW), so:
9193   //   N = Distance (as unsigned)
9194   if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) {
9195     APInt MaxBECount = getUnsignedRangeMax(applyLoopGuards(Distance, L));
9196     APInt MaxBECountBase = getUnsignedRangeMax(Distance);
9197     if (MaxBECountBase.ult(MaxBECount))
9198       MaxBECount = MaxBECountBase;
9199 
9200     // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
9201     // we end up with a loop whose backedge-taken count is n - 1.  Detect this
9202     // case, and see if we can improve the bound.
9203     //
9204     // Explicitly handling this here is necessary because getUnsignedRange
9205     // isn't context-sensitive; it doesn't know that we only care about the
9206     // range inside the loop.
9207     const SCEV *Zero = getZero(Distance->getType());
9208     const SCEV *One = getOne(Distance->getType());
9209     const SCEV *DistancePlusOne = getAddExpr(Distance, One);
9210     if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
9211       // If Distance + 1 doesn't overflow, we can compute the maximum distance
9212       // as "unsigned_max(Distance + 1) - 1".
9213       ConstantRange CR = getUnsignedRange(DistancePlusOne);
9214       MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1);
9215     }
9216     return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates);
9217   }
9218 
9219   // If the condition controls loop exit (the loop exits only if the expression
9220   // is true) and the addition is no-wrap we can use unsigned divide to
9221   // compute the backedge count.  In this case, the step may not divide the
9222   // distance, but we don't care because if the condition is "missed" the loop
9223   // will have undefined behavior due to wrapping.
9224   if (ControlsExit && AddRec->hasNoSelfWrap() &&
9225       loopHasNoAbnormalExits(AddRec->getLoop())) {
9226     const SCEV *Exact =
9227         getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
9228     const SCEV *Max =
9229         Exact == getCouldNotCompute()
9230             ? Exact
9231             : getConstant(getUnsignedRangeMax(Exact));
9232     return ExitLimit(Exact, Max, false, Predicates);
9233   }
9234 
9235   // Solve the general equation.
9236   const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(),
9237                                                getNegativeSCEV(Start), *this);
9238   const SCEV *M = E == getCouldNotCompute()
9239                       ? E
9240                       : getConstant(getUnsignedRangeMax(E));
9241   return ExitLimit(E, M, false, Predicates);
9242 }
9243 
9244 ScalarEvolution::ExitLimit
9245 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
9246   // Loops that look like: while (X == 0) are very strange indeed.  We don't
9247   // handle them yet except for the trivial case.  This could be expanded in the
9248   // future as needed.
9249 
9250   // If the value is a constant, check to see if it is known to be non-zero
9251   // already.  If so, the backedge will execute zero times.
9252   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
9253     if (!C->getValue()->isZero())
9254       return getZero(C->getType());
9255     return getCouldNotCompute();  // Otherwise it will loop infinitely.
9256   }
9257 
9258   // We could implement others, but I really doubt anyone writes loops like
9259   // this, and if they did, they would already be constant folded.
9260   return getCouldNotCompute();
9261 }
9262 
9263 std::pair<const BasicBlock *, const BasicBlock *>
9264 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB)
9265     const {
9266   // If the block has a unique predecessor, then there is no path from the
9267   // predecessor to the block that does not go through the direct edge
9268   // from the predecessor to the block.
9269   if (const BasicBlock *Pred = BB->getSinglePredecessor())
9270     return {Pred, BB};
9271 
9272   // A loop's header is defined to be a block that dominates the loop.
9273   // If the header has a unique predecessor outside the loop, it must be
9274   // a block that has exactly one successor that can reach the loop.
9275   if (const Loop *L = LI.getLoopFor(BB))
9276     return {L->getLoopPredecessor(), L->getHeader()};
9277 
9278   return {nullptr, nullptr};
9279 }
9280 
9281 /// SCEV structural equivalence is usually sufficient for testing whether two
9282 /// expressions are equal, however for the purposes of looking for a condition
9283 /// guarding a loop, it can be useful to be a little more general, since a
9284 /// front-end may have replicated the controlling expression.
9285 static bool HasSameValue(const SCEV *A, const SCEV *B) {
9286   // Quick check to see if they are the same SCEV.
9287   if (A == B) return true;
9288 
9289   auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
9290     // Not all instructions that are "identical" compute the same value.  For
9291     // instance, two distinct alloca instructions allocating the same type are
9292     // identical and do not read memory; but compute distinct values.
9293     return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
9294   };
9295 
9296   // Otherwise, if they're both SCEVUnknown, it's possible that they hold
9297   // two different instructions with the same value. Check for this case.
9298   if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
9299     if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
9300       if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
9301         if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
9302           if (ComputesEqualValues(AI, BI))
9303             return true;
9304 
9305   // Otherwise assume they may have a different value.
9306   return false;
9307 }
9308 
9309 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
9310                                            const SCEV *&LHS, const SCEV *&RHS,
9311                                            unsigned Depth) {
9312   bool Changed = false;
9313   // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or
9314   // '0 != 0'.
9315   auto TrivialCase = [&](bool TriviallyTrue) {
9316     LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
9317     Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
9318     return true;
9319   };
9320   // If we hit the max recursion limit bail out.
9321   if (Depth >= 3)
9322     return false;
9323 
9324   // Canonicalize a constant to the right side.
9325   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
9326     // Check for both operands constant.
9327     if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
9328       if (ConstantExpr::getICmp(Pred,
9329                                 LHSC->getValue(),
9330                                 RHSC->getValue())->isNullValue())
9331         return TrivialCase(false);
9332       else
9333         return TrivialCase(true);
9334     }
9335     // Otherwise swap the operands to put the constant on the right.
9336     std::swap(LHS, RHS);
9337     Pred = ICmpInst::getSwappedPredicate(Pred);
9338     Changed = true;
9339   }
9340 
9341   // If we're comparing an addrec with a value which is loop-invariant in the
9342   // addrec's loop, put the addrec on the left. Also make a dominance check,
9343   // as both operands could be addrecs loop-invariant in each other's loop.
9344   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
9345     const Loop *L = AR->getLoop();
9346     if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
9347       std::swap(LHS, RHS);
9348       Pred = ICmpInst::getSwappedPredicate(Pred);
9349       Changed = true;
9350     }
9351   }
9352 
9353   // If there's a constant operand, canonicalize comparisons with boundary
9354   // cases, and canonicalize *-or-equal comparisons to regular comparisons.
9355   if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
9356     const APInt &RA = RC->getAPInt();
9357 
9358     bool SimplifiedByConstantRange = false;
9359 
9360     if (!ICmpInst::isEquality(Pred)) {
9361       ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA);
9362       if (ExactCR.isFullSet())
9363         return TrivialCase(true);
9364       else if (ExactCR.isEmptySet())
9365         return TrivialCase(false);
9366 
9367       APInt NewRHS;
9368       CmpInst::Predicate NewPred;
9369       if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
9370           ICmpInst::isEquality(NewPred)) {
9371         // We were able to convert an inequality to an equality.
9372         Pred = NewPred;
9373         RHS = getConstant(NewRHS);
9374         Changed = SimplifiedByConstantRange = true;
9375       }
9376     }
9377 
9378     if (!SimplifiedByConstantRange) {
9379       switch (Pred) {
9380       default:
9381         break;
9382       case ICmpInst::ICMP_EQ:
9383       case ICmpInst::ICMP_NE:
9384         // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
9385         if (!RA)
9386           if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
9387             if (const SCEVMulExpr *ME =
9388                     dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
9389               if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
9390                   ME->getOperand(0)->isAllOnesValue()) {
9391                 RHS = AE->getOperand(1);
9392                 LHS = ME->getOperand(1);
9393                 Changed = true;
9394               }
9395         break;
9396 
9397 
9398         // The "Should have been caught earlier!" messages refer to the fact
9399         // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
9400         // should have fired on the corresponding cases, and canonicalized the
9401         // check to trivial case.
9402 
9403       case ICmpInst::ICMP_UGE:
9404         assert(!RA.isMinValue() && "Should have been caught earlier!");
9405         Pred = ICmpInst::ICMP_UGT;
9406         RHS = getConstant(RA - 1);
9407         Changed = true;
9408         break;
9409       case ICmpInst::ICMP_ULE:
9410         assert(!RA.isMaxValue() && "Should have been caught earlier!");
9411         Pred = ICmpInst::ICMP_ULT;
9412         RHS = getConstant(RA + 1);
9413         Changed = true;
9414         break;
9415       case ICmpInst::ICMP_SGE:
9416         assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
9417         Pred = ICmpInst::ICMP_SGT;
9418         RHS = getConstant(RA - 1);
9419         Changed = true;
9420         break;
9421       case ICmpInst::ICMP_SLE:
9422         assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
9423         Pred = ICmpInst::ICMP_SLT;
9424         RHS = getConstant(RA + 1);
9425         Changed = true;
9426         break;
9427       }
9428     }
9429   }
9430 
9431   // Check for obvious equality.
9432   if (HasSameValue(LHS, RHS)) {
9433     if (ICmpInst::isTrueWhenEqual(Pred))
9434       return TrivialCase(true);
9435     if (ICmpInst::isFalseWhenEqual(Pred))
9436       return TrivialCase(false);
9437   }
9438 
9439   // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
9440   // adding or subtracting 1 from one of the operands.
9441   switch (Pred) {
9442   case ICmpInst::ICMP_SLE:
9443     if (!getSignedRangeMax(RHS).isMaxSignedValue()) {
9444       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
9445                        SCEV::FlagNSW);
9446       Pred = ICmpInst::ICMP_SLT;
9447       Changed = true;
9448     } else if (!getSignedRangeMin(LHS).isMinSignedValue()) {
9449       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
9450                        SCEV::FlagNSW);
9451       Pred = ICmpInst::ICMP_SLT;
9452       Changed = true;
9453     }
9454     break;
9455   case ICmpInst::ICMP_SGE:
9456     if (!getSignedRangeMin(RHS).isMinSignedValue()) {
9457       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
9458                        SCEV::FlagNSW);
9459       Pred = ICmpInst::ICMP_SGT;
9460       Changed = true;
9461     } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) {
9462       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
9463                        SCEV::FlagNSW);
9464       Pred = ICmpInst::ICMP_SGT;
9465       Changed = true;
9466     }
9467     break;
9468   case ICmpInst::ICMP_ULE:
9469     if (!getUnsignedRangeMax(RHS).isMaxValue()) {
9470       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
9471                        SCEV::FlagNUW);
9472       Pred = ICmpInst::ICMP_ULT;
9473       Changed = true;
9474     } else if (!getUnsignedRangeMin(LHS).isMinValue()) {
9475       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
9476       Pred = ICmpInst::ICMP_ULT;
9477       Changed = true;
9478     }
9479     break;
9480   case ICmpInst::ICMP_UGE:
9481     if (!getUnsignedRangeMin(RHS).isMinValue()) {
9482       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
9483       Pred = ICmpInst::ICMP_UGT;
9484       Changed = true;
9485     } else if (!getUnsignedRangeMax(LHS).isMaxValue()) {
9486       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
9487                        SCEV::FlagNUW);
9488       Pred = ICmpInst::ICMP_UGT;
9489       Changed = true;
9490     }
9491     break;
9492   default:
9493     break;
9494   }
9495 
9496   // TODO: More simplifications are possible here.
9497 
9498   // Recursively simplify until we either hit a recursion limit or nothing
9499   // changes.
9500   if (Changed)
9501     return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
9502 
9503   return Changed;
9504 }
9505 
9506 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
9507   return getSignedRangeMax(S).isNegative();
9508 }
9509 
9510 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
9511   return getSignedRangeMin(S).isStrictlyPositive();
9512 }
9513 
9514 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
9515   return !getSignedRangeMin(S).isNegative();
9516 }
9517 
9518 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
9519   return !getSignedRangeMax(S).isStrictlyPositive();
9520 }
9521 
9522 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
9523   return isKnownNegative(S) || isKnownPositive(S);
9524 }
9525 
9526 std::pair<const SCEV *, const SCEV *>
9527 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) {
9528   // Compute SCEV on entry of loop L.
9529   const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this);
9530   if (Start == getCouldNotCompute())
9531     return { Start, Start };
9532   // Compute post increment SCEV for loop L.
9533   const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this);
9534   assert(PostInc != getCouldNotCompute() && "Unexpected could not compute");
9535   return { Start, PostInc };
9536 }
9537 
9538 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred,
9539                                           const SCEV *LHS, const SCEV *RHS) {
9540   // First collect all loops.
9541   SmallPtrSet<const Loop *, 8> LoopsUsed;
9542   getUsedLoops(LHS, LoopsUsed);
9543   getUsedLoops(RHS, LoopsUsed);
9544 
9545   if (LoopsUsed.empty())
9546     return false;
9547 
9548   // Domination relationship must be a linear order on collected loops.
9549 #ifndef NDEBUG
9550   for (auto *L1 : LoopsUsed)
9551     for (auto *L2 : LoopsUsed)
9552       assert((DT.dominates(L1->getHeader(), L2->getHeader()) ||
9553               DT.dominates(L2->getHeader(), L1->getHeader())) &&
9554              "Domination relationship is not a linear order");
9555 #endif
9556 
9557   const Loop *MDL =
9558       *std::max_element(LoopsUsed.begin(), LoopsUsed.end(),
9559                         [&](const Loop *L1, const Loop *L2) {
9560          return DT.properlyDominates(L1->getHeader(), L2->getHeader());
9561        });
9562 
9563   // Get init and post increment value for LHS.
9564   auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS);
9565   // if LHS contains unknown non-invariant SCEV then bail out.
9566   if (SplitLHS.first == getCouldNotCompute())
9567     return false;
9568   assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC");
9569   // Get init and post increment value for RHS.
9570   auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS);
9571   // if RHS contains unknown non-invariant SCEV then bail out.
9572   if (SplitRHS.first == getCouldNotCompute())
9573     return false;
9574   assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC");
9575   // It is possible that init SCEV contains an invariant load but it does
9576   // not dominate MDL and is not available at MDL loop entry, so we should
9577   // check it here.
9578   if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) ||
9579       !isAvailableAtLoopEntry(SplitRHS.first, MDL))
9580     return false;
9581 
9582   // It seems backedge guard check is faster than entry one so in some cases
9583   // it can speed up whole estimation by short circuit
9584   return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second,
9585                                      SplitRHS.second) &&
9586          isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first);
9587 }
9588 
9589 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
9590                                        const SCEV *LHS, const SCEV *RHS) {
9591   // Canonicalize the inputs first.
9592   (void)SimplifyICmpOperands(Pred, LHS, RHS);
9593 
9594   if (isKnownViaInduction(Pred, LHS, RHS))
9595     return true;
9596 
9597   if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
9598     return true;
9599 
9600   // Otherwise see what can be done with some simple reasoning.
9601   return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS);
9602 }
9603 
9604 Optional<bool> ScalarEvolution::evaluatePredicate(ICmpInst::Predicate Pred,
9605                                                   const SCEV *LHS,
9606                                                   const SCEV *RHS) {
9607   if (isKnownPredicate(Pred, LHS, RHS))
9608     return true;
9609   else if (isKnownPredicate(ICmpInst::getInversePredicate(Pred), LHS, RHS))
9610     return false;
9611   return None;
9612 }
9613 
9614 bool ScalarEvolution::isKnownPredicateAt(ICmpInst::Predicate Pred,
9615                                          const SCEV *LHS, const SCEV *RHS,
9616                                          const Instruction *Context) {
9617   // TODO: Analyze guards and assumes from Context's block.
9618   return isKnownPredicate(Pred, LHS, RHS) ||
9619          isBasicBlockEntryGuardedByCond(Context->getParent(), Pred, LHS, RHS);
9620 }
9621 
9622 Optional<bool>
9623 ScalarEvolution::evaluatePredicateAt(ICmpInst::Predicate Pred, const SCEV *LHS,
9624                                      const SCEV *RHS,
9625                                      const Instruction *Context) {
9626   Optional<bool> KnownWithoutContext = evaluatePredicate(Pred, LHS, RHS);
9627   if (KnownWithoutContext)
9628     return KnownWithoutContext;
9629 
9630   if (isBasicBlockEntryGuardedByCond(Context->getParent(), Pred, LHS, RHS))
9631     return true;
9632   else if (isBasicBlockEntryGuardedByCond(Context->getParent(),
9633                                           ICmpInst::getInversePredicate(Pred),
9634                                           LHS, RHS))
9635     return false;
9636   return None;
9637 }
9638 
9639 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred,
9640                                               const SCEVAddRecExpr *LHS,
9641                                               const SCEV *RHS) {
9642   const Loop *L = LHS->getLoop();
9643   return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) &&
9644          isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS);
9645 }
9646 
9647 Optional<ScalarEvolution::MonotonicPredicateType>
9648 ScalarEvolution::getMonotonicPredicateType(const SCEVAddRecExpr *LHS,
9649                                            ICmpInst::Predicate Pred) {
9650   auto Result = getMonotonicPredicateTypeImpl(LHS, Pred);
9651 
9652 #ifndef NDEBUG
9653   // Verify an invariant: inverting the predicate should turn a monotonically
9654   // increasing change to a monotonically decreasing one, and vice versa.
9655   if (Result) {
9656     auto ResultSwapped =
9657         getMonotonicPredicateTypeImpl(LHS, ICmpInst::getSwappedPredicate(Pred));
9658 
9659     assert(ResultSwapped.hasValue() && "should be able to analyze both!");
9660     assert(ResultSwapped.getValue() != Result.getValue() &&
9661            "monotonicity should flip as we flip the predicate");
9662   }
9663 #endif
9664 
9665   return Result;
9666 }
9667 
9668 Optional<ScalarEvolution::MonotonicPredicateType>
9669 ScalarEvolution::getMonotonicPredicateTypeImpl(const SCEVAddRecExpr *LHS,
9670                                                ICmpInst::Predicate Pred) {
9671   // A zero step value for LHS means the induction variable is essentially a
9672   // loop invariant value. We don't really depend on the predicate actually
9673   // flipping from false to true (for increasing predicates, and the other way
9674   // around for decreasing predicates), all we care about is that *if* the
9675   // predicate changes then it only changes from false to true.
9676   //
9677   // A zero step value in itself is not very useful, but there may be places
9678   // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
9679   // as general as possible.
9680 
9681   // Only handle LE/LT/GE/GT predicates.
9682   if (!ICmpInst::isRelational(Pred))
9683     return None;
9684 
9685   bool IsGreater = ICmpInst::isGE(Pred) || ICmpInst::isGT(Pred);
9686   assert((IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) &&
9687          "Should be greater or less!");
9688 
9689   // Check that AR does not wrap.
9690   if (ICmpInst::isUnsigned(Pred)) {
9691     if (!LHS->hasNoUnsignedWrap())
9692       return None;
9693     return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
9694   } else {
9695     assert(ICmpInst::isSigned(Pred) &&
9696            "Relational predicate is either signed or unsigned!");
9697     if (!LHS->hasNoSignedWrap())
9698       return None;
9699 
9700     const SCEV *Step = LHS->getStepRecurrence(*this);
9701 
9702     if (isKnownNonNegative(Step))
9703       return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
9704 
9705     if (isKnownNonPositive(Step))
9706       return !IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
9707 
9708     return None;
9709   }
9710 }
9711 
9712 Optional<ScalarEvolution::LoopInvariantPredicate>
9713 ScalarEvolution::getLoopInvariantPredicate(ICmpInst::Predicate Pred,
9714                                            const SCEV *LHS, const SCEV *RHS,
9715                                            const Loop *L) {
9716 
9717   // If there is a loop-invariant, force it into the RHS, otherwise bail out.
9718   if (!isLoopInvariant(RHS, L)) {
9719     if (!isLoopInvariant(LHS, L))
9720       return None;
9721 
9722     std::swap(LHS, RHS);
9723     Pred = ICmpInst::getSwappedPredicate(Pred);
9724   }
9725 
9726   const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
9727   if (!ArLHS || ArLHS->getLoop() != L)
9728     return None;
9729 
9730   auto MonotonicType = getMonotonicPredicateType(ArLHS, Pred);
9731   if (!MonotonicType)
9732     return None;
9733   // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
9734   // true as the loop iterates, and the backedge is control dependent on
9735   // "ArLHS `Pred` RHS" == true then we can reason as follows:
9736   //
9737   //   * if the predicate was false in the first iteration then the predicate
9738   //     is never evaluated again, since the loop exits without taking the
9739   //     backedge.
9740   //   * if the predicate was true in the first iteration then it will
9741   //     continue to be true for all future iterations since it is
9742   //     monotonically increasing.
9743   //
9744   // For both the above possibilities, we can replace the loop varying
9745   // predicate with its value on the first iteration of the loop (which is
9746   // loop invariant).
9747   //
9748   // A similar reasoning applies for a monotonically decreasing predicate, by
9749   // replacing true with false and false with true in the above two bullets.
9750   bool Increasing = *MonotonicType == ScalarEvolution::MonotonicallyIncreasing;
9751   auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
9752 
9753   if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
9754     return None;
9755 
9756   return ScalarEvolution::LoopInvariantPredicate(Pred, ArLHS->getStart(), RHS);
9757 }
9758 
9759 Optional<ScalarEvolution::LoopInvariantPredicate>
9760 ScalarEvolution::getLoopInvariantExitCondDuringFirstIterations(
9761     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
9762     const Instruction *Context, const SCEV *MaxIter) {
9763   // Try to prove the following set of facts:
9764   // - The predicate is monotonic in the iteration space.
9765   // - If the check does not fail on the 1st iteration:
9766   //   - No overflow will happen during first MaxIter iterations;
9767   //   - It will not fail on the MaxIter'th iteration.
9768   // If the check does fail on the 1st iteration, we leave the loop and no
9769   // other checks matter.
9770 
9771   // If there is a loop-invariant, force it into the RHS, otherwise bail out.
9772   if (!isLoopInvariant(RHS, L)) {
9773     if (!isLoopInvariant(LHS, L))
9774       return None;
9775 
9776     std::swap(LHS, RHS);
9777     Pred = ICmpInst::getSwappedPredicate(Pred);
9778   }
9779 
9780   auto *AR = dyn_cast<SCEVAddRecExpr>(LHS);
9781   if (!AR || AR->getLoop() != L)
9782     return None;
9783 
9784   // The predicate must be relational (i.e. <, <=, >=, >).
9785   if (!ICmpInst::isRelational(Pred))
9786     return None;
9787 
9788   // TODO: Support steps other than +/- 1.
9789   const SCEV *Step = AR->getStepRecurrence(*this);
9790   auto *One = getOne(Step->getType());
9791   auto *MinusOne = getNegativeSCEV(One);
9792   if (Step != One && Step != MinusOne)
9793     return None;
9794 
9795   // Type mismatch here means that MaxIter is potentially larger than max
9796   // unsigned value in start type, which mean we cannot prove no wrap for the
9797   // indvar.
9798   if (AR->getType() != MaxIter->getType())
9799     return None;
9800 
9801   // Value of IV on suggested last iteration.
9802   const SCEV *Last = AR->evaluateAtIteration(MaxIter, *this);
9803   // Does it still meet the requirement?
9804   if (!isLoopBackedgeGuardedByCond(L, Pred, Last, RHS))
9805     return None;
9806   // Because step is +/- 1 and MaxIter has same type as Start (i.e. it does
9807   // not exceed max unsigned value of this type), this effectively proves
9808   // that there is no wrap during the iteration. To prove that there is no
9809   // signed/unsigned wrap, we need to check that
9810   // Start <= Last for step = 1 or Start >= Last for step = -1.
9811   ICmpInst::Predicate NoOverflowPred =
9812       CmpInst::isSigned(Pred) ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
9813   if (Step == MinusOne)
9814     NoOverflowPred = CmpInst::getSwappedPredicate(NoOverflowPred);
9815   const SCEV *Start = AR->getStart();
9816   if (!isKnownPredicateAt(NoOverflowPred, Start, Last, Context))
9817     return None;
9818 
9819   // Everything is fine.
9820   return ScalarEvolution::LoopInvariantPredicate(Pred, Start, RHS);
9821 }
9822 
9823 bool ScalarEvolution::isKnownPredicateViaConstantRanges(
9824     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
9825   if (HasSameValue(LHS, RHS))
9826     return ICmpInst::isTrueWhenEqual(Pred);
9827 
9828   // This code is split out from isKnownPredicate because it is called from
9829   // within isLoopEntryGuardedByCond.
9830 
9831   auto CheckRanges = [&](const ConstantRange &RangeLHS,
9832                          const ConstantRange &RangeRHS) {
9833     return RangeLHS.icmp(Pred, RangeRHS);
9834   };
9835 
9836   // The check at the top of the function catches the case where the values are
9837   // known to be equal.
9838   if (Pred == CmpInst::ICMP_EQ)
9839     return false;
9840 
9841   if (Pred == CmpInst::ICMP_NE)
9842     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) ||
9843            CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) ||
9844            isKnownNonZero(getMinusSCEV(LHS, RHS));
9845 
9846   if (CmpInst::isSigned(Pred))
9847     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS));
9848 
9849   return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS));
9850 }
9851 
9852 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
9853                                                     const SCEV *LHS,
9854                                                     const SCEV *RHS) {
9855   // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer.
9856   // Return Y via OutY.
9857   auto MatchBinaryAddToConst =
9858       [this](const SCEV *Result, const SCEV *X, APInt &OutY,
9859              SCEV::NoWrapFlags ExpectedFlags) {
9860     const SCEV *NonConstOp, *ConstOp;
9861     SCEV::NoWrapFlags FlagsPresent;
9862 
9863     if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) ||
9864         !isa<SCEVConstant>(ConstOp) || NonConstOp != X)
9865       return false;
9866 
9867     OutY = cast<SCEVConstant>(ConstOp)->getAPInt();
9868     return (FlagsPresent & ExpectedFlags) == ExpectedFlags;
9869   };
9870 
9871   APInt C;
9872 
9873   switch (Pred) {
9874   default:
9875     break;
9876 
9877   case ICmpInst::ICMP_SGE:
9878     std::swap(LHS, RHS);
9879     LLVM_FALLTHROUGH;
9880   case ICmpInst::ICMP_SLE:
9881     // X s<= (X + C)<nsw> if C >= 0
9882     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative())
9883       return true;
9884 
9885     // (X + C)<nsw> s<= X if C <= 0
9886     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) &&
9887         !C.isStrictlyPositive())
9888       return true;
9889     break;
9890 
9891   case ICmpInst::ICMP_SGT:
9892     std::swap(LHS, RHS);
9893     LLVM_FALLTHROUGH;
9894   case ICmpInst::ICMP_SLT:
9895     // X s< (X + C)<nsw> if C > 0
9896     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) &&
9897         C.isStrictlyPositive())
9898       return true;
9899 
9900     // (X + C)<nsw> s< X if C < 0
9901     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative())
9902       return true;
9903     break;
9904 
9905   case ICmpInst::ICMP_UGE:
9906     std::swap(LHS, RHS);
9907     LLVM_FALLTHROUGH;
9908   case ICmpInst::ICMP_ULE:
9909     // X u<= (X + C)<nuw> for any C
9910     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNUW))
9911       return true;
9912     break;
9913 
9914   case ICmpInst::ICMP_UGT:
9915     std::swap(LHS, RHS);
9916     LLVM_FALLTHROUGH;
9917   case ICmpInst::ICMP_ULT:
9918     // X u< (X + C)<nuw> if C != 0
9919     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNUW) && !C.isNullValue())
9920       return true;
9921     break;
9922   }
9923 
9924   return false;
9925 }
9926 
9927 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
9928                                                    const SCEV *LHS,
9929                                                    const SCEV *RHS) {
9930   if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
9931     return false;
9932 
9933   // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
9934   // the stack can result in exponential time complexity.
9935   SaveAndRestore<bool> Restore(ProvingSplitPredicate, true);
9936 
9937   // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
9938   //
9939   // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
9940   // isKnownPredicate.  isKnownPredicate is more powerful, but also more
9941   // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
9942   // interesting cases seen in practice.  We can consider "upgrading" L >= 0 to
9943   // use isKnownPredicate later if needed.
9944   return isKnownNonNegative(RHS) &&
9945          isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
9946          isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
9947 }
9948 
9949 bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB,
9950                                         ICmpInst::Predicate Pred,
9951                                         const SCEV *LHS, const SCEV *RHS) {
9952   // No need to even try if we know the module has no guards.
9953   if (!HasGuards)
9954     return false;
9955 
9956   return any_of(*BB, [&](const Instruction &I) {
9957     using namespace llvm::PatternMatch;
9958 
9959     Value *Condition;
9960     return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
9961                          m_Value(Condition))) &&
9962            isImpliedCond(Pred, LHS, RHS, Condition, false);
9963   });
9964 }
9965 
9966 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
9967 /// protected by a conditional between LHS and RHS.  This is used to
9968 /// to eliminate casts.
9969 bool
9970 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
9971                                              ICmpInst::Predicate Pred,
9972                                              const SCEV *LHS, const SCEV *RHS) {
9973   // Interpret a null as meaning no loop, where there is obviously no guard
9974   // (interprocedural conditions notwithstanding).
9975   if (!L) return true;
9976 
9977   if (VerifyIR)
9978     assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) &&
9979            "This cannot be done on broken IR!");
9980 
9981 
9982   if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
9983     return true;
9984 
9985   BasicBlock *Latch = L->getLoopLatch();
9986   if (!Latch)
9987     return false;
9988 
9989   BranchInst *LoopContinuePredicate =
9990     dyn_cast<BranchInst>(Latch->getTerminator());
9991   if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
9992       isImpliedCond(Pred, LHS, RHS,
9993                     LoopContinuePredicate->getCondition(),
9994                     LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
9995     return true;
9996 
9997   // We don't want more than one activation of the following loops on the stack
9998   // -- that can lead to O(n!) time complexity.
9999   if (WalkingBEDominatingConds)
10000     return false;
10001 
10002   SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true);
10003 
10004   // See if we can exploit a trip count to prove the predicate.
10005   const auto &BETakenInfo = getBackedgeTakenInfo(L);
10006   const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
10007   if (LatchBECount != getCouldNotCompute()) {
10008     // We know that Latch branches back to the loop header exactly
10009     // LatchBECount times.  This means the backdege condition at Latch is
10010     // equivalent to  "{0,+,1} u< LatchBECount".
10011     Type *Ty = LatchBECount->getType();
10012     auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
10013     const SCEV *LoopCounter =
10014       getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
10015     if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
10016                       LatchBECount))
10017       return true;
10018   }
10019 
10020   // Check conditions due to any @llvm.assume intrinsics.
10021   for (auto &AssumeVH : AC.assumptions()) {
10022     if (!AssumeVH)
10023       continue;
10024     auto *CI = cast<CallInst>(AssumeVH);
10025     if (!DT.dominates(CI, Latch->getTerminator()))
10026       continue;
10027 
10028     if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
10029       return true;
10030   }
10031 
10032   // If the loop is not reachable from the entry block, we risk running into an
10033   // infinite loop as we walk up into the dom tree.  These loops do not matter
10034   // anyway, so we just return a conservative answer when we see them.
10035   if (!DT.isReachableFromEntry(L->getHeader()))
10036     return false;
10037 
10038   if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
10039     return true;
10040 
10041   for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
10042        DTN != HeaderDTN; DTN = DTN->getIDom()) {
10043     assert(DTN && "should reach the loop header before reaching the root!");
10044 
10045     BasicBlock *BB = DTN->getBlock();
10046     if (isImpliedViaGuard(BB, Pred, LHS, RHS))
10047       return true;
10048 
10049     BasicBlock *PBB = BB->getSinglePredecessor();
10050     if (!PBB)
10051       continue;
10052 
10053     BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
10054     if (!ContinuePredicate || !ContinuePredicate->isConditional())
10055       continue;
10056 
10057     Value *Condition = ContinuePredicate->getCondition();
10058 
10059     // If we have an edge `E` within the loop body that dominates the only
10060     // latch, the condition guarding `E` also guards the backedge.  This
10061     // reasoning works only for loops with a single latch.
10062 
10063     BasicBlockEdge DominatingEdge(PBB, BB);
10064     if (DominatingEdge.isSingleEdge()) {
10065       // We're constructively (and conservatively) enumerating edges within the
10066       // loop body that dominate the latch.  The dominator tree better agree
10067       // with us on this:
10068       assert(DT.dominates(DominatingEdge, Latch) && "should be!");
10069 
10070       if (isImpliedCond(Pred, LHS, RHS, Condition,
10071                         BB != ContinuePredicate->getSuccessor(0)))
10072         return true;
10073     }
10074   }
10075 
10076   return false;
10077 }
10078 
10079 bool ScalarEvolution::isBasicBlockEntryGuardedByCond(const BasicBlock *BB,
10080                                                      ICmpInst::Predicate Pred,
10081                                                      const SCEV *LHS,
10082                                                      const SCEV *RHS) {
10083   if (VerifyIR)
10084     assert(!verifyFunction(*BB->getParent(), &dbgs()) &&
10085            "This cannot be done on broken IR!");
10086 
10087   // If we cannot prove strict comparison (e.g. a > b), maybe we can prove
10088   // the facts (a >= b && a != b) separately. A typical situation is when the
10089   // non-strict comparison is known from ranges and non-equality is known from
10090   // dominating predicates. If we are proving strict comparison, we always try
10091   // to prove non-equality and non-strict comparison separately.
10092   auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred);
10093   const bool ProvingStrictComparison = (Pred != NonStrictPredicate);
10094   bool ProvedNonStrictComparison = false;
10095   bool ProvedNonEquality = false;
10096 
10097   auto SplitAndProve =
10098     [&](std::function<bool(ICmpInst::Predicate)> Fn) -> bool {
10099     if (!ProvedNonStrictComparison)
10100       ProvedNonStrictComparison = Fn(NonStrictPredicate);
10101     if (!ProvedNonEquality)
10102       ProvedNonEquality = Fn(ICmpInst::ICMP_NE);
10103     if (ProvedNonStrictComparison && ProvedNonEquality)
10104       return true;
10105     return false;
10106   };
10107 
10108   if (ProvingStrictComparison) {
10109     auto ProofFn = [&](ICmpInst::Predicate P) {
10110       return isKnownViaNonRecursiveReasoning(P, LHS, RHS);
10111     };
10112     if (SplitAndProve(ProofFn))
10113       return true;
10114   }
10115 
10116   // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard.
10117   auto ProveViaGuard = [&](const BasicBlock *Block) {
10118     if (isImpliedViaGuard(Block, Pred, LHS, RHS))
10119       return true;
10120     if (ProvingStrictComparison) {
10121       auto ProofFn = [&](ICmpInst::Predicate P) {
10122         return isImpliedViaGuard(Block, P, LHS, RHS);
10123       };
10124       if (SplitAndProve(ProofFn))
10125         return true;
10126     }
10127     return false;
10128   };
10129 
10130   // Try to prove (Pred, LHS, RHS) using isImpliedCond.
10131   auto ProveViaCond = [&](const Value *Condition, bool Inverse) {
10132     const Instruction *Context = &BB->front();
10133     if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse, Context))
10134       return true;
10135     if (ProvingStrictComparison) {
10136       auto ProofFn = [&](ICmpInst::Predicate P) {
10137         return isImpliedCond(P, LHS, RHS, Condition, Inverse, Context);
10138       };
10139       if (SplitAndProve(ProofFn))
10140         return true;
10141     }
10142     return false;
10143   };
10144 
10145   // Starting at the block's predecessor, climb up the predecessor chain, as long
10146   // as there are predecessors that can be found that have unique successors
10147   // leading to the original block.
10148   const Loop *ContainingLoop = LI.getLoopFor(BB);
10149   const BasicBlock *PredBB;
10150   if (ContainingLoop && ContainingLoop->getHeader() == BB)
10151     PredBB = ContainingLoop->getLoopPredecessor();
10152   else
10153     PredBB = BB->getSinglePredecessor();
10154   for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB);
10155        Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
10156     if (ProveViaGuard(Pair.first))
10157       return true;
10158 
10159     const BranchInst *LoopEntryPredicate =
10160         dyn_cast<BranchInst>(Pair.first->getTerminator());
10161     if (!LoopEntryPredicate ||
10162         LoopEntryPredicate->isUnconditional())
10163       continue;
10164 
10165     if (ProveViaCond(LoopEntryPredicate->getCondition(),
10166                      LoopEntryPredicate->getSuccessor(0) != Pair.second))
10167       return true;
10168   }
10169 
10170   // Check conditions due to any @llvm.assume intrinsics.
10171   for (auto &AssumeVH : AC.assumptions()) {
10172     if (!AssumeVH)
10173       continue;
10174     auto *CI = cast<CallInst>(AssumeVH);
10175     if (!DT.dominates(CI, BB))
10176       continue;
10177 
10178     if (ProveViaCond(CI->getArgOperand(0), false))
10179       return true;
10180   }
10181 
10182   return false;
10183 }
10184 
10185 bool ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
10186                                                ICmpInst::Predicate Pred,
10187                                                const SCEV *LHS,
10188                                                const SCEV *RHS) {
10189   // Interpret a null as meaning no loop, where there is obviously no guard
10190   // (interprocedural conditions notwithstanding).
10191   if (!L)
10192     return false;
10193 
10194   // Both LHS and RHS must be available at loop entry.
10195   assert(isAvailableAtLoopEntry(LHS, L) &&
10196          "LHS is not available at Loop Entry");
10197   assert(isAvailableAtLoopEntry(RHS, L) &&
10198          "RHS is not available at Loop Entry");
10199 
10200   if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
10201     return true;
10202 
10203   return isBasicBlockEntryGuardedByCond(L->getHeader(), Pred, LHS, RHS);
10204 }
10205 
10206 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
10207                                     const SCEV *RHS,
10208                                     const Value *FoundCondValue, bool Inverse,
10209                                     const Instruction *Context) {
10210   // False conditions implies anything. Do not bother analyzing it further.
10211   if (FoundCondValue ==
10212       ConstantInt::getBool(FoundCondValue->getContext(), Inverse))
10213     return true;
10214 
10215   if (!PendingLoopPredicates.insert(FoundCondValue).second)
10216     return false;
10217 
10218   auto ClearOnExit =
10219       make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
10220 
10221   // Recursively handle And and Or conditions.
10222   const Value *Op0, *Op1;
10223   if (match(FoundCondValue, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
10224     if (!Inverse)
10225       return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, Context) ||
10226               isImpliedCond(Pred, LHS, RHS, Op1, Inverse, Context);
10227   } else if (match(FoundCondValue, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) {
10228     if (Inverse)
10229       return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, Context) ||
10230               isImpliedCond(Pred, LHS, RHS, Op1, Inverse, Context);
10231   }
10232 
10233   const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
10234   if (!ICI) return false;
10235 
10236   // Now that we found a conditional branch that dominates the loop or controls
10237   // the loop latch. Check to see if it is the comparison we are looking for.
10238   ICmpInst::Predicate FoundPred;
10239   if (Inverse)
10240     FoundPred = ICI->getInversePredicate();
10241   else
10242     FoundPred = ICI->getPredicate();
10243 
10244   const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
10245   const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
10246 
10247   return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, Context);
10248 }
10249 
10250 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
10251                                     const SCEV *RHS,
10252                                     ICmpInst::Predicate FoundPred,
10253                                     const SCEV *FoundLHS, const SCEV *FoundRHS,
10254                                     const Instruction *Context) {
10255   // Balance the types.
10256   if (getTypeSizeInBits(LHS->getType()) <
10257       getTypeSizeInBits(FoundLHS->getType())) {
10258     // For unsigned and equality predicates, try to prove that both found
10259     // operands fit into narrow unsigned range. If so, try to prove facts in
10260     // narrow types.
10261     if (!CmpInst::isSigned(FoundPred)) {
10262       auto *NarrowType = LHS->getType();
10263       auto *WideType = FoundLHS->getType();
10264       auto BitWidth = getTypeSizeInBits(NarrowType);
10265       const SCEV *MaxValue = getZeroExtendExpr(
10266           getConstant(APInt::getMaxValue(BitWidth)), WideType);
10267       if (isKnownPredicate(ICmpInst::ICMP_ULE, FoundLHS, MaxValue) &&
10268           isKnownPredicate(ICmpInst::ICMP_ULE, FoundRHS, MaxValue)) {
10269         const SCEV *TruncFoundLHS = getTruncateExpr(FoundLHS, NarrowType);
10270         const SCEV *TruncFoundRHS = getTruncateExpr(FoundRHS, NarrowType);
10271         if (isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, TruncFoundLHS,
10272                                        TruncFoundRHS, Context))
10273           return true;
10274       }
10275     }
10276 
10277     if (CmpInst::isSigned(Pred)) {
10278       LHS = getSignExtendExpr(LHS, FoundLHS->getType());
10279       RHS = getSignExtendExpr(RHS, FoundLHS->getType());
10280     } else {
10281       LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
10282       RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
10283     }
10284   } else if (getTypeSizeInBits(LHS->getType()) >
10285       getTypeSizeInBits(FoundLHS->getType())) {
10286     if (CmpInst::isSigned(FoundPred)) {
10287       FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
10288       FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
10289     } else {
10290       FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
10291       FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
10292     }
10293   }
10294   return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS,
10295                                     FoundRHS, Context);
10296 }
10297 
10298 bool ScalarEvolution::isImpliedCondBalancedTypes(
10299     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
10300     ICmpInst::Predicate FoundPred, const SCEV *FoundLHS, const SCEV *FoundRHS,
10301     const Instruction *Context) {
10302   assert(getTypeSizeInBits(LHS->getType()) ==
10303              getTypeSizeInBits(FoundLHS->getType()) &&
10304          "Types should be balanced!");
10305   // Canonicalize the query to match the way instcombine will have
10306   // canonicalized the comparison.
10307   if (SimplifyICmpOperands(Pred, LHS, RHS))
10308     if (LHS == RHS)
10309       return CmpInst::isTrueWhenEqual(Pred);
10310   if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
10311     if (FoundLHS == FoundRHS)
10312       return CmpInst::isFalseWhenEqual(FoundPred);
10313 
10314   // Check to see if we can make the LHS or RHS match.
10315   if (LHS == FoundRHS || RHS == FoundLHS) {
10316     if (isa<SCEVConstant>(RHS)) {
10317       std::swap(FoundLHS, FoundRHS);
10318       FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
10319     } else {
10320       std::swap(LHS, RHS);
10321       Pred = ICmpInst::getSwappedPredicate(Pred);
10322     }
10323   }
10324 
10325   // Check whether the found predicate is the same as the desired predicate.
10326   if (FoundPred == Pred)
10327     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context);
10328 
10329   // Check whether swapping the found predicate makes it the same as the
10330   // desired predicate.
10331   if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
10332     // We can write the implication
10333     // 0.  LHS Pred      RHS  <-   FoundLHS SwapPred  FoundRHS
10334     // using one of the following ways:
10335     // 1.  LHS Pred      RHS  <-   FoundRHS Pred      FoundLHS
10336     // 2.  RHS SwapPred  LHS  <-   FoundLHS SwapPred  FoundRHS
10337     // 3.  LHS Pred      RHS  <-  ~FoundLHS Pred     ~FoundRHS
10338     // 4. ~LHS SwapPred ~RHS  <-   FoundLHS SwapPred  FoundRHS
10339     // Forms 1. and 2. require swapping the operands of one condition. Don't
10340     // do this if it would break canonical constant/addrec ordering.
10341     if (!isa<SCEVConstant>(RHS) && !isa<SCEVAddRecExpr>(LHS))
10342       return isImpliedCondOperands(FoundPred, RHS, LHS, FoundLHS, FoundRHS,
10343                                    Context);
10344     if (!isa<SCEVConstant>(FoundRHS) && !isa<SCEVAddRecExpr>(FoundLHS))
10345       return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS, Context);
10346 
10347     // There's no clear preference between forms 3. and 4., try both.
10348     return isImpliedCondOperands(FoundPred, getNotSCEV(LHS), getNotSCEV(RHS),
10349                                  FoundLHS, FoundRHS, Context) ||
10350            isImpliedCondOperands(Pred, LHS, RHS, getNotSCEV(FoundLHS),
10351                                  getNotSCEV(FoundRHS), Context);
10352   }
10353 
10354   // Unsigned comparison is the same as signed comparison when both the operands
10355   // are non-negative.
10356   if (CmpInst::isUnsigned(FoundPred) &&
10357       CmpInst::getSignedPredicate(FoundPred) == Pred &&
10358       isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS))
10359     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context);
10360 
10361   // Check if we can make progress by sharpening ranges.
10362   if (FoundPred == ICmpInst::ICMP_NE &&
10363       (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
10364 
10365     const SCEVConstant *C = nullptr;
10366     const SCEV *V = nullptr;
10367 
10368     if (isa<SCEVConstant>(FoundLHS)) {
10369       C = cast<SCEVConstant>(FoundLHS);
10370       V = FoundRHS;
10371     } else {
10372       C = cast<SCEVConstant>(FoundRHS);
10373       V = FoundLHS;
10374     }
10375 
10376     // The guarding predicate tells us that C != V. If the known range
10377     // of V is [C, t), we can sharpen the range to [C + 1, t).  The
10378     // range we consider has to correspond to same signedness as the
10379     // predicate we're interested in folding.
10380 
10381     APInt Min = ICmpInst::isSigned(Pred) ?
10382         getSignedRangeMin(V) : getUnsignedRangeMin(V);
10383 
10384     if (Min == C->getAPInt()) {
10385       // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
10386       // This is true even if (Min + 1) wraps around -- in case of
10387       // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
10388 
10389       APInt SharperMin = Min + 1;
10390 
10391       switch (Pred) {
10392         case ICmpInst::ICMP_SGE:
10393         case ICmpInst::ICMP_UGE:
10394           // We know V `Pred` SharperMin.  If this implies LHS `Pred`
10395           // RHS, we're done.
10396           if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(SharperMin),
10397                                     Context))
10398             return true;
10399           LLVM_FALLTHROUGH;
10400 
10401         case ICmpInst::ICMP_SGT:
10402         case ICmpInst::ICMP_UGT:
10403           // We know from the range information that (V `Pred` Min ||
10404           // V == Min).  We know from the guarding condition that !(V
10405           // == Min).  This gives us
10406           //
10407           //       V `Pred` Min || V == Min && !(V == Min)
10408           //   =>  V `Pred` Min
10409           //
10410           // If V `Pred` Min implies LHS `Pred` RHS, we're done.
10411 
10412           if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min),
10413                                     Context))
10414             return true;
10415           break;
10416 
10417         // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively.
10418         case ICmpInst::ICMP_SLE:
10419         case ICmpInst::ICMP_ULE:
10420           if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS,
10421                                     LHS, V, getConstant(SharperMin), Context))
10422             return true;
10423           LLVM_FALLTHROUGH;
10424 
10425         case ICmpInst::ICMP_SLT:
10426         case ICmpInst::ICMP_ULT:
10427           if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS,
10428                                     LHS, V, getConstant(Min), Context))
10429             return true;
10430           break;
10431 
10432         default:
10433           // No change
10434           break;
10435       }
10436     }
10437   }
10438 
10439   // Check whether the actual condition is beyond sufficient.
10440   if (FoundPred == ICmpInst::ICMP_EQ)
10441     if (ICmpInst::isTrueWhenEqual(Pred))
10442       if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context))
10443         return true;
10444   if (Pred == ICmpInst::ICMP_NE)
10445     if (!ICmpInst::isTrueWhenEqual(FoundPred))
10446       if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS,
10447                                 Context))
10448         return true;
10449 
10450   // Otherwise assume the worst.
10451   return false;
10452 }
10453 
10454 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
10455                                      const SCEV *&L, const SCEV *&R,
10456                                      SCEV::NoWrapFlags &Flags) {
10457   const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
10458   if (!AE || AE->getNumOperands() != 2)
10459     return false;
10460 
10461   L = AE->getOperand(0);
10462   R = AE->getOperand(1);
10463   Flags = AE->getNoWrapFlags();
10464   return true;
10465 }
10466 
10467 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More,
10468                                                            const SCEV *Less) {
10469   // We avoid subtracting expressions here because this function is usually
10470   // fairly deep in the call stack (i.e. is called many times).
10471 
10472   // X - X = 0.
10473   if (More == Less)
10474     return APInt(getTypeSizeInBits(More->getType()), 0);
10475 
10476   if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
10477     const auto *LAR = cast<SCEVAddRecExpr>(Less);
10478     const auto *MAR = cast<SCEVAddRecExpr>(More);
10479 
10480     if (LAR->getLoop() != MAR->getLoop())
10481       return None;
10482 
10483     // We look at affine expressions only; not for correctness but to keep
10484     // getStepRecurrence cheap.
10485     if (!LAR->isAffine() || !MAR->isAffine())
10486       return None;
10487 
10488     if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
10489       return None;
10490 
10491     Less = LAR->getStart();
10492     More = MAR->getStart();
10493 
10494     // fall through
10495   }
10496 
10497   if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
10498     const auto &M = cast<SCEVConstant>(More)->getAPInt();
10499     const auto &L = cast<SCEVConstant>(Less)->getAPInt();
10500     return M - L;
10501   }
10502 
10503   SCEV::NoWrapFlags Flags;
10504   const SCEV *LLess = nullptr, *RLess = nullptr;
10505   const SCEV *LMore = nullptr, *RMore = nullptr;
10506   const SCEVConstant *C1 = nullptr, *C2 = nullptr;
10507   // Compare (X + C1) vs X.
10508   if (splitBinaryAdd(Less, LLess, RLess, Flags))
10509     if ((C1 = dyn_cast<SCEVConstant>(LLess)))
10510       if (RLess == More)
10511         return -(C1->getAPInt());
10512 
10513   // Compare X vs (X + C2).
10514   if (splitBinaryAdd(More, LMore, RMore, Flags))
10515     if ((C2 = dyn_cast<SCEVConstant>(LMore)))
10516       if (RMore == Less)
10517         return C2->getAPInt();
10518 
10519   // Compare (X + C1) vs (X + C2).
10520   if (C1 && C2 && RLess == RMore)
10521     return C2->getAPInt() - C1->getAPInt();
10522 
10523   return None;
10524 }
10525 
10526 bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart(
10527     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
10528     const SCEV *FoundLHS, const SCEV *FoundRHS, const Instruction *Context) {
10529   // Try to recognize the following pattern:
10530   //
10531   //   FoundRHS = ...
10532   // ...
10533   // loop:
10534   //   FoundLHS = {Start,+,W}
10535   // context_bb: // Basic block from the same loop
10536   //   known(Pred, FoundLHS, FoundRHS)
10537   //
10538   // If some predicate is known in the context of a loop, it is also known on
10539   // each iteration of this loop, including the first iteration. Therefore, in
10540   // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to
10541   // prove the original pred using this fact.
10542   if (!Context)
10543     return false;
10544   const BasicBlock *ContextBB = Context->getParent();
10545   // Make sure AR varies in the context block.
10546   if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) {
10547     const Loop *L = AR->getLoop();
10548     // Make sure that context belongs to the loop and executes on 1st iteration
10549     // (if it ever executes at all).
10550     if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch()))
10551       return false;
10552     if (!isAvailableAtLoopEntry(FoundRHS, AR->getLoop()))
10553       return false;
10554     return isImpliedCondOperands(Pred, LHS, RHS, AR->getStart(), FoundRHS);
10555   }
10556 
10557   if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) {
10558     const Loop *L = AR->getLoop();
10559     // Make sure that context belongs to the loop and executes on 1st iteration
10560     // (if it ever executes at all).
10561     if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch()))
10562       return false;
10563     if (!isAvailableAtLoopEntry(FoundLHS, AR->getLoop()))
10564       return false;
10565     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->getStart());
10566   }
10567 
10568   return false;
10569 }
10570 
10571 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
10572     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
10573     const SCEV *FoundLHS, const SCEV *FoundRHS) {
10574   if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
10575     return false;
10576 
10577   const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
10578   if (!AddRecLHS)
10579     return false;
10580 
10581   const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
10582   if (!AddRecFoundLHS)
10583     return false;
10584 
10585   // We'd like to let SCEV reason about control dependencies, so we constrain
10586   // both the inequalities to be about add recurrences on the same loop.  This
10587   // way we can use isLoopEntryGuardedByCond later.
10588 
10589   const Loop *L = AddRecFoundLHS->getLoop();
10590   if (L != AddRecLHS->getLoop())
10591     return false;
10592 
10593   //  FoundLHS u< FoundRHS u< -C =>  (FoundLHS + C) u< (FoundRHS + C) ... (1)
10594   //
10595   //  FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
10596   //                                                                  ... (2)
10597   //
10598   // Informal proof for (2), assuming (1) [*]:
10599   //
10600   // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
10601   //
10602   // Then
10603   //
10604   //       FoundLHS s< FoundRHS s< INT_MIN - C
10605   // <=>  (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C   [ using (3) ]
10606   // <=>  (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
10607   // <=>  (FoundLHS + INT_MIN + C + INT_MIN) s<
10608   //                        (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
10609   // <=>  FoundLHS + C s< FoundRHS + C
10610   //
10611   // [*]: (1) can be proved by ruling out overflow.
10612   //
10613   // [**]: This can be proved by analyzing all the four possibilities:
10614   //    (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
10615   //    (A s>= 0, B s>= 0).
10616   //
10617   // Note:
10618   // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
10619   // will not sign underflow.  For instance, say FoundLHS = (i8 -128), FoundRHS
10620   // = (i8 -127) and C = (i8 -100).  Then INT_MIN - C = (i8 -28), and FoundRHS
10621   // s< (INT_MIN - C).  Lack of sign overflow / underflow in "FoundRHS + C" is
10622   // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
10623   // C)".
10624 
10625   Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
10626   Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
10627   if (!LDiff || !RDiff || *LDiff != *RDiff)
10628     return false;
10629 
10630   if (LDiff->isMinValue())
10631     return true;
10632 
10633   APInt FoundRHSLimit;
10634 
10635   if (Pred == CmpInst::ICMP_ULT) {
10636     FoundRHSLimit = -(*RDiff);
10637   } else {
10638     assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
10639     FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
10640   }
10641 
10642   // Try to prove (1) or (2), as needed.
10643   return isAvailableAtLoopEntry(FoundRHS, L) &&
10644          isLoopEntryGuardedByCond(L, Pred, FoundRHS,
10645                                   getConstant(FoundRHSLimit));
10646 }
10647 
10648 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred,
10649                                         const SCEV *LHS, const SCEV *RHS,
10650                                         const SCEV *FoundLHS,
10651                                         const SCEV *FoundRHS, unsigned Depth) {
10652   const PHINode *LPhi = nullptr, *RPhi = nullptr;
10653 
10654   auto ClearOnExit = make_scope_exit([&]() {
10655     if (LPhi) {
10656       bool Erased = PendingMerges.erase(LPhi);
10657       assert(Erased && "Failed to erase LPhi!");
10658       (void)Erased;
10659     }
10660     if (RPhi) {
10661       bool Erased = PendingMerges.erase(RPhi);
10662       assert(Erased && "Failed to erase RPhi!");
10663       (void)Erased;
10664     }
10665   });
10666 
10667   // Find respective Phis and check that they are not being pending.
10668   if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS))
10669     if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) {
10670       if (!PendingMerges.insert(Phi).second)
10671         return false;
10672       LPhi = Phi;
10673     }
10674   if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS))
10675     if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) {
10676       // If we detect a loop of Phi nodes being processed by this method, for
10677       // example:
10678       //
10679       //   %a = phi i32 [ %some1, %preheader ], [ %b, %latch ]
10680       //   %b = phi i32 [ %some2, %preheader ], [ %a, %latch ]
10681       //
10682       // we don't want to deal with a case that complex, so return conservative
10683       // answer false.
10684       if (!PendingMerges.insert(Phi).second)
10685         return false;
10686       RPhi = Phi;
10687     }
10688 
10689   // If none of LHS, RHS is a Phi, nothing to do here.
10690   if (!LPhi && !RPhi)
10691     return false;
10692 
10693   // If there is a SCEVUnknown Phi we are interested in, make it left.
10694   if (!LPhi) {
10695     std::swap(LHS, RHS);
10696     std::swap(FoundLHS, FoundRHS);
10697     std::swap(LPhi, RPhi);
10698     Pred = ICmpInst::getSwappedPredicate(Pred);
10699   }
10700 
10701   assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!");
10702   const BasicBlock *LBB = LPhi->getParent();
10703   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
10704 
10705   auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) {
10706     return isKnownViaNonRecursiveReasoning(Pred, S1, S2) ||
10707            isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) ||
10708            isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth);
10709   };
10710 
10711   if (RPhi && RPhi->getParent() == LBB) {
10712     // Case one: RHS is also a SCEVUnknown Phi from the same basic block.
10713     // If we compare two Phis from the same block, and for each entry block
10714     // the predicate is true for incoming values from this block, then the
10715     // predicate is also true for the Phis.
10716     for (const BasicBlock *IncBB : predecessors(LBB)) {
10717       const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
10718       const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB));
10719       if (!ProvedEasily(L, R))
10720         return false;
10721     }
10722   } else if (RAR && RAR->getLoop()->getHeader() == LBB) {
10723     // Case two: RHS is also a Phi from the same basic block, and it is an
10724     // AddRec. It means that there is a loop which has both AddRec and Unknown
10725     // PHIs, for it we can compare incoming values of AddRec from above the loop
10726     // and latch with their respective incoming values of LPhi.
10727     // TODO: Generalize to handle loops with many inputs in a header.
10728     if (LPhi->getNumIncomingValues() != 2) return false;
10729 
10730     auto *RLoop = RAR->getLoop();
10731     auto *Predecessor = RLoop->getLoopPredecessor();
10732     assert(Predecessor && "Loop with AddRec with no predecessor?");
10733     const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor));
10734     if (!ProvedEasily(L1, RAR->getStart()))
10735       return false;
10736     auto *Latch = RLoop->getLoopLatch();
10737     assert(Latch && "Loop with AddRec with no latch?");
10738     const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch));
10739     if (!ProvedEasily(L2, RAR->getPostIncExpr(*this)))
10740       return false;
10741   } else {
10742     // In all other cases go over inputs of LHS and compare each of them to RHS,
10743     // the predicate is true for (LHS, RHS) if it is true for all such pairs.
10744     // At this point RHS is either a non-Phi, or it is a Phi from some block
10745     // different from LBB.
10746     for (const BasicBlock *IncBB : predecessors(LBB)) {
10747       // Check that RHS is available in this block.
10748       if (!dominates(RHS, IncBB))
10749         return false;
10750       const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
10751       if (!ProvedEasily(L, RHS))
10752         return false;
10753     }
10754   }
10755   return true;
10756 }
10757 
10758 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
10759                                             const SCEV *LHS, const SCEV *RHS,
10760                                             const SCEV *FoundLHS,
10761                                             const SCEV *FoundRHS,
10762                                             const Instruction *Context) {
10763   if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
10764     return true;
10765 
10766   if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
10767     return true;
10768 
10769   if (isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS,
10770                                           Context))
10771     return true;
10772 
10773   return isImpliedCondOperandsHelper(Pred, LHS, RHS,
10774                                      FoundLHS, FoundRHS);
10775 }
10776 
10777 /// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values?
10778 template <typename MinMaxExprType>
10779 static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr,
10780                                  const SCEV *Candidate) {
10781   const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr);
10782   if (!MinMaxExpr)
10783     return false;
10784 
10785   return is_contained(MinMaxExpr->operands(), Candidate);
10786 }
10787 
10788 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
10789                                            ICmpInst::Predicate Pred,
10790                                            const SCEV *LHS, const SCEV *RHS) {
10791   // If both sides are affine addrecs for the same loop, with equal
10792   // steps, and we know the recurrences don't wrap, then we only
10793   // need to check the predicate on the starting values.
10794 
10795   if (!ICmpInst::isRelational(Pred))
10796     return false;
10797 
10798   const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
10799   if (!LAR)
10800     return false;
10801   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
10802   if (!RAR)
10803     return false;
10804   if (LAR->getLoop() != RAR->getLoop())
10805     return false;
10806   if (!LAR->isAffine() || !RAR->isAffine())
10807     return false;
10808 
10809   if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
10810     return false;
10811 
10812   SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
10813                          SCEV::FlagNSW : SCEV::FlagNUW;
10814   if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
10815     return false;
10816 
10817   return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
10818 }
10819 
10820 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
10821 /// expression?
10822 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
10823                                         ICmpInst::Predicate Pred,
10824                                         const SCEV *LHS, const SCEV *RHS) {
10825   switch (Pred) {
10826   default:
10827     return false;
10828 
10829   case ICmpInst::ICMP_SGE:
10830     std::swap(LHS, RHS);
10831     LLVM_FALLTHROUGH;
10832   case ICmpInst::ICMP_SLE:
10833     return
10834         // min(A, ...) <= A
10835         IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) ||
10836         // A <= max(A, ...)
10837         IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
10838 
10839   case ICmpInst::ICMP_UGE:
10840     std::swap(LHS, RHS);
10841     LLVM_FALLTHROUGH;
10842   case ICmpInst::ICMP_ULE:
10843     return
10844         // min(A, ...) <= A
10845         IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) ||
10846         // A <= max(A, ...)
10847         IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
10848   }
10849 
10850   llvm_unreachable("covered switch fell through?!");
10851 }
10852 
10853 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred,
10854                                              const SCEV *LHS, const SCEV *RHS,
10855                                              const SCEV *FoundLHS,
10856                                              const SCEV *FoundRHS,
10857                                              unsigned Depth) {
10858   assert(getTypeSizeInBits(LHS->getType()) ==
10859              getTypeSizeInBits(RHS->getType()) &&
10860          "LHS and RHS have different sizes?");
10861   assert(getTypeSizeInBits(FoundLHS->getType()) ==
10862              getTypeSizeInBits(FoundRHS->getType()) &&
10863          "FoundLHS and FoundRHS have different sizes?");
10864   // We want to avoid hurting the compile time with analysis of too big trees.
10865   if (Depth > MaxSCEVOperationsImplicationDepth)
10866     return false;
10867 
10868   // We only want to work with GT comparison so far.
10869   if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT) {
10870     Pred = CmpInst::getSwappedPredicate(Pred);
10871     std::swap(LHS, RHS);
10872     std::swap(FoundLHS, FoundRHS);
10873   }
10874 
10875   // For unsigned, try to reduce it to corresponding signed comparison.
10876   if (Pred == ICmpInst::ICMP_UGT)
10877     // We can replace unsigned predicate with its signed counterpart if all
10878     // involved values are non-negative.
10879     // TODO: We could have better support for unsigned.
10880     if (isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) {
10881       // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing
10882       // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us
10883       // use this fact to prove that LHS and RHS are non-negative.
10884       const SCEV *MinusOne = getMinusOne(LHS->getType());
10885       if (isImpliedCondOperands(ICmpInst::ICMP_SGT, LHS, MinusOne, FoundLHS,
10886                                 FoundRHS) &&
10887           isImpliedCondOperands(ICmpInst::ICMP_SGT, RHS, MinusOne, FoundLHS,
10888                                 FoundRHS))
10889         Pred = ICmpInst::ICMP_SGT;
10890     }
10891 
10892   if (Pred != ICmpInst::ICMP_SGT)
10893     return false;
10894 
10895   auto GetOpFromSExt = [&](const SCEV *S) {
10896     if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
10897       return Ext->getOperand();
10898     // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
10899     // the constant in some cases.
10900     return S;
10901   };
10902 
10903   // Acquire values from extensions.
10904   auto *OrigLHS = LHS;
10905   auto *OrigFoundLHS = FoundLHS;
10906   LHS = GetOpFromSExt(LHS);
10907   FoundLHS = GetOpFromSExt(FoundLHS);
10908 
10909   // Is the SGT predicate can be proved trivially or using the found context.
10910   auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
10911     return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
10912            isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
10913                                   FoundRHS, Depth + 1);
10914   };
10915 
10916   if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
10917     // We want to avoid creation of any new non-constant SCEV. Since we are
10918     // going to compare the operands to RHS, we should be certain that we don't
10919     // need any size extensions for this. So let's decline all cases when the
10920     // sizes of types of LHS and RHS do not match.
10921     // TODO: Maybe try to get RHS from sext to catch more cases?
10922     if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType()))
10923       return false;
10924 
10925     // Should not overflow.
10926     if (!LHSAddExpr->hasNoSignedWrap())
10927       return false;
10928 
10929     auto *LL = LHSAddExpr->getOperand(0);
10930     auto *LR = LHSAddExpr->getOperand(1);
10931     auto *MinusOne = getMinusOne(RHS->getType());
10932 
10933     // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
10934     auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
10935       return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
10936     };
10937     // Try to prove the following rule:
10938     // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
10939     // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
10940     if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
10941       return true;
10942   } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
10943     Value *LL, *LR;
10944     // FIXME: Once we have SDiv implemented, we can get rid of this matching.
10945 
10946     using namespace llvm::PatternMatch;
10947 
10948     if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
10949       // Rules for division.
10950       // We are going to perform some comparisons with Denominator and its
10951       // derivative expressions. In general case, creating a SCEV for it may
10952       // lead to a complex analysis of the entire graph, and in particular it
10953       // can request trip count recalculation for the same loop. This would
10954       // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
10955       // this, we only want to create SCEVs that are constants in this section.
10956       // So we bail if Denominator is not a constant.
10957       if (!isa<ConstantInt>(LR))
10958         return false;
10959 
10960       auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
10961 
10962       // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
10963       // then a SCEV for the numerator already exists and matches with FoundLHS.
10964       auto *Numerator = getExistingSCEV(LL);
10965       if (!Numerator || Numerator->getType() != FoundLHS->getType())
10966         return false;
10967 
10968       // Make sure that the numerator matches with FoundLHS and the denominator
10969       // is positive.
10970       if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
10971         return false;
10972 
10973       auto *DTy = Denominator->getType();
10974       auto *FRHSTy = FoundRHS->getType();
10975       if (DTy->isPointerTy() != FRHSTy->isPointerTy())
10976         // One of types is a pointer and another one is not. We cannot extend
10977         // them properly to a wider type, so let us just reject this case.
10978         // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
10979         // to avoid this check.
10980         return false;
10981 
10982       // Given that:
10983       // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
10984       auto *WTy = getWiderType(DTy, FRHSTy);
10985       auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
10986       auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
10987 
10988       // Try to prove the following rule:
10989       // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
10990       // For example, given that FoundLHS > 2. It means that FoundLHS is at
10991       // least 3. If we divide it by Denominator < 4, we will have at least 1.
10992       auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
10993       if (isKnownNonPositive(RHS) &&
10994           IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
10995         return true;
10996 
10997       // Try to prove the following rule:
10998       // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
10999       // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
11000       // If we divide it by Denominator > 2, then:
11001       // 1. If FoundLHS is negative, then the result is 0.
11002       // 2. If FoundLHS is non-negative, then the result is non-negative.
11003       // Anyways, the result is non-negative.
11004       auto *MinusOne = getMinusOne(WTy);
11005       auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
11006       if (isKnownNegative(RHS) &&
11007           IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
11008         return true;
11009     }
11010   }
11011 
11012   // If our expression contained SCEVUnknown Phis, and we split it down and now
11013   // need to prove something for them, try to prove the predicate for every
11014   // possible incoming values of those Phis.
11015   if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1))
11016     return true;
11017 
11018   return false;
11019 }
11020 
11021 static bool isKnownPredicateExtendIdiom(ICmpInst::Predicate Pred,
11022                                         const SCEV *LHS, const SCEV *RHS) {
11023   // zext x u<= sext x, sext x s<= zext x
11024   switch (Pred) {
11025   case ICmpInst::ICMP_SGE:
11026     std::swap(LHS, RHS);
11027     LLVM_FALLTHROUGH;
11028   case ICmpInst::ICMP_SLE: {
11029     // If operand >=s 0 then ZExt == SExt.  If operand <s 0 then SExt <s ZExt.
11030     const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(LHS);
11031     const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(RHS);
11032     if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand())
11033       return true;
11034     break;
11035   }
11036   case ICmpInst::ICMP_UGE:
11037     std::swap(LHS, RHS);
11038     LLVM_FALLTHROUGH;
11039   case ICmpInst::ICMP_ULE: {
11040     // If operand >=s 0 then ZExt == SExt.  If operand <s 0 then ZExt <u SExt.
11041     const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS);
11042     const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(RHS);
11043     if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand())
11044       return true;
11045     break;
11046   }
11047   default:
11048     break;
11049   };
11050   return false;
11051 }
11052 
11053 bool
11054 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred,
11055                                            const SCEV *LHS, const SCEV *RHS) {
11056   return isKnownPredicateExtendIdiom(Pred, LHS, RHS) ||
11057          isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
11058          IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
11059          IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
11060          isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
11061 }
11062 
11063 bool
11064 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
11065                                              const SCEV *LHS, const SCEV *RHS,
11066                                              const SCEV *FoundLHS,
11067                                              const SCEV *FoundRHS) {
11068   switch (Pred) {
11069   default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
11070   case ICmpInst::ICMP_EQ:
11071   case ICmpInst::ICMP_NE:
11072     if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
11073       return true;
11074     break;
11075   case ICmpInst::ICMP_SLT:
11076   case ICmpInst::ICMP_SLE:
11077     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
11078         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS))
11079       return true;
11080     break;
11081   case ICmpInst::ICMP_SGT:
11082   case ICmpInst::ICMP_SGE:
11083     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
11084         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS))
11085       return true;
11086     break;
11087   case ICmpInst::ICMP_ULT:
11088   case ICmpInst::ICMP_ULE:
11089     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
11090         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS))
11091       return true;
11092     break;
11093   case ICmpInst::ICMP_UGT:
11094   case ICmpInst::ICMP_UGE:
11095     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
11096         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS))
11097       return true;
11098     break;
11099   }
11100 
11101   // Maybe it can be proved via operations?
11102   if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
11103     return true;
11104 
11105   return false;
11106 }
11107 
11108 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
11109                                                      const SCEV *LHS,
11110                                                      const SCEV *RHS,
11111                                                      const SCEV *FoundLHS,
11112                                                      const SCEV *FoundRHS) {
11113   if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
11114     // The restriction on `FoundRHS` be lifted easily -- it exists only to
11115     // reduce the compile time impact of this optimization.
11116     return false;
11117 
11118   Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
11119   if (!Addend)
11120     return false;
11121 
11122   const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
11123 
11124   // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
11125   // antecedent "`FoundLHS` `Pred` `FoundRHS`".
11126   ConstantRange FoundLHSRange =
11127       ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS);
11128 
11129   // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
11130   ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
11131 
11132   // We can also compute the range of values for `LHS` that satisfy the
11133   // consequent, "`LHS` `Pred` `RHS`":
11134   const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
11135   // The antecedent implies the consequent if every value of `LHS` that
11136   // satisfies the antecedent also satisfies the consequent.
11137   return LHSRange.icmp(Pred, ConstRHS);
11138 }
11139 
11140 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
11141                                          bool IsSigned, bool NoWrap) {
11142   assert(isKnownPositive(Stride) && "Positive stride expected!");
11143 
11144   if (NoWrap) return false;
11145 
11146   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
11147   const SCEV *One = getOne(Stride->getType());
11148 
11149   if (IsSigned) {
11150     APInt MaxRHS = getSignedRangeMax(RHS);
11151     APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
11152     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
11153 
11154     // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
11155     return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS);
11156   }
11157 
11158   APInt MaxRHS = getUnsignedRangeMax(RHS);
11159   APInt MaxValue = APInt::getMaxValue(BitWidth);
11160   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
11161 
11162   // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
11163   return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS);
11164 }
11165 
11166 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
11167                                          bool IsSigned, bool NoWrap) {
11168   if (NoWrap) return false;
11169 
11170   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
11171   const SCEV *One = getOne(Stride->getType());
11172 
11173   if (IsSigned) {
11174     APInt MinRHS = getSignedRangeMin(RHS);
11175     APInt MinValue = APInt::getSignedMinValue(BitWidth);
11176     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
11177 
11178     // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
11179     return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS);
11180   }
11181 
11182   APInt MinRHS = getUnsignedRangeMin(RHS);
11183   APInt MinValue = APInt::getMinValue(BitWidth);
11184   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
11185 
11186   // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
11187   return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS);
11188 }
11189 
11190 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step,
11191                                             bool Equality) {
11192   const SCEV *One = getOne(Step->getType());
11193   Delta = Equality ? getAddExpr(Delta, Step)
11194                    : getAddExpr(Delta, getMinusSCEV(Step, One));
11195   return getUDivExpr(Delta, Step);
11196 }
11197 
11198 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start,
11199                                                     const SCEV *Stride,
11200                                                     const SCEV *End,
11201                                                     unsigned BitWidth,
11202                                                     bool IsSigned) {
11203 
11204   assert(!isKnownNonPositive(Stride) &&
11205          "Stride is expected strictly positive!");
11206   // Calculate the maximum backedge count based on the range of values
11207   // permitted by Start, End, and Stride.
11208   const SCEV *MaxBECount;
11209   APInt MinStart =
11210       IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start);
11211 
11212   APInt StrideForMaxBECount =
11213       IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride);
11214 
11215   // We already know that the stride is positive, so we paper over conservatism
11216   // in our range computation by forcing StrideForMaxBECount to be at least one.
11217   // In theory this is unnecessary, but we expect MaxBECount to be a
11218   // SCEVConstant, and (udiv <constant> 0) is not constant folded by SCEV (there
11219   // is nothing to constant fold it to).
11220   APInt One(BitWidth, 1, IsSigned);
11221   StrideForMaxBECount = APIntOps::smax(One, StrideForMaxBECount);
11222 
11223   APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth)
11224                             : APInt::getMaxValue(BitWidth);
11225   APInt Limit = MaxValue - (StrideForMaxBECount - 1);
11226 
11227   // Although End can be a MAX expression we estimate MaxEnd considering only
11228   // the case End = RHS of the loop termination condition. This is safe because
11229   // in the other case (End - Start) is zero, leading to a zero maximum backedge
11230   // taken count.
11231   APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit)
11232                           : APIntOps::umin(getUnsignedRangeMax(End), Limit);
11233 
11234   MaxBECount = computeBECount(getConstant(MaxEnd - MinStart) /* Delta */,
11235                               getConstant(StrideForMaxBECount) /* Step */,
11236                               false /* Equality */);
11237 
11238   return MaxBECount;
11239 }
11240 
11241 ScalarEvolution::ExitLimit
11242 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
11243                                   const Loop *L, bool IsSigned,
11244                                   bool ControlsExit, bool AllowPredicates) {
11245   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
11246 
11247   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
11248   bool PredicatedIV = false;
11249 
11250   if (!IV && AllowPredicates) {
11251     // Try to make this an AddRec using runtime tests, in the first X
11252     // iterations of this loop, where X is the SCEV expression found by the
11253     // algorithm below.
11254     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
11255     PredicatedIV = true;
11256   }
11257 
11258   // Avoid weird loops
11259   if (!IV || IV->getLoop() != L || !IV->isAffine())
11260     return getCouldNotCompute();
11261 
11262   bool NoWrap = ControlsExit &&
11263                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
11264 
11265   const SCEV *Stride = IV->getStepRecurrence(*this);
11266 
11267   bool PositiveStride = isKnownPositive(Stride);
11268 
11269   // Avoid negative or zero stride values.
11270   if (!PositiveStride) {
11271     // We can compute the correct backedge taken count for loops with unknown
11272     // strides if we can prove that the loop is not an infinite loop with side
11273     // effects. Here's the loop structure we are trying to handle -
11274     //
11275     // i = start
11276     // do {
11277     //   A[i] = i;
11278     //   i += s;
11279     // } while (i < end);
11280     //
11281     // The backedge taken count for such loops is evaluated as -
11282     // (max(end, start + stride) - start - 1) /u stride
11283     //
11284     // The additional preconditions that we need to check to prove correctness
11285     // of the above formula is as follows -
11286     //
11287     // a) IV is either nuw or nsw depending upon signedness (indicated by the
11288     //    NoWrap flag).
11289     // b) loop is single exit with no side effects.
11290     //
11291     //
11292     // Precondition a) implies that if the stride is negative, this is a single
11293     // trip loop. The backedge taken count formula reduces to zero in this case.
11294     //
11295     // Precondition b) implies that the unknown stride cannot be zero otherwise
11296     // we have UB.
11297     //
11298     // The positive stride case is the same as isKnownPositive(Stride) returning
11299     // true (original behavior of the function).
11300     //
11301     // We want to make sure that the stride is truly unknown as there are edge
11302     // cases where ScalarEvolution propagates no wrap flags to the
11303     // post-increment/decrement IV even though the increment/decrement operation
11304     // itself is wrapping. The computed backedge taken count may be wrong in
11305     // such cases. This is prevented by checking that the stride is not known to
11306     // be either positive or non-positive. For example, no wrap flags are
11307     // propagated to the post-increment IV of this loop with a trip count of 2 -
11308     //
11309     // unsigned char i;
11310     // for(i=127; i<128; i+=129)
11311     //   A[i] = i;
11312     //
11313     if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) ||
11314         !loopHasNoSideEffects(L))
11315       return getCouldNotCompute();
11316   } else if (!Stride->isOne() &&
11317              doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap))
11318     // Avoid proven overflow cases: this will ensure that the backedge taken
11319     // count will not generate any unsigned overflow. Relaxed no-overflow
11320     // conditions exploit NoWrapFlags, allowing to optimize in presence of
11321     // undefined behaviors like the case of C language.
11322     return getCouldNotCompute();
11323 
11324   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT
11325                                       : ICmpInst::ICMP_ULT;
11326   const SCEV *Start = IV->getStart();
11327   const SCEV *End = RHS;
11328   // When the RHS is not invariant, we do not know the end bound of the loop and
11329   // cannot calculate the ExactBECount needed by ExitLimit. However, we can
11330   // calculate the MaxBECount, given the start, stride and max value for the end
11331   // bound of the loop (RHS), and the fact that IV does not overflow (which is
11332   // checked above).
11333   if (!isLoopInvariant(RHS, L)) {
11334     const SCEV *MaxBECount = computeMaxBECountForLT(
11335         Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
11336     return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount,
11337                      false /*MaxOrZero*/, Predicates);
11338   }
11339   // If the backedge is taken at least once, then it will be taken
11340   // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start
11341   // is the LHS value of the less-than comparison the first time it is evaluated
11342   // and End is the RHS.
11343   const SCEV *BECountIfBackedgeTaken =
11344     computeBECount(getMinusSCEV(End, Start), Stride, false);
11345   // If the loop entry is guarded by the result of the backedge test of the
11346   // first loop iteration, then we know the backedge will be taken at least
11347   // once and so the backedge taken count is as above. If not then we use the
11348   // expression (max(End,Start)-Start)/Stride to describe the backedge count,
11349   // as if the backedge is taken at least once max(End,Start) is End and so the
11350   // result is as above, and if not max(End,Start) is Start so we get a backedge
11351   // count of zero.
11352   const SCEV *BECount;
11353   if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS))
11354     BECount = BECountIfBackedgeTaken;
11355   else {
11356     // If we know that RHS >= Start in the context of loop, then we know that
11357     // max(RHS, Start) = RHS at this point.
11358     if (isLoopEntryGuardedByCond(
11359             L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, RHS, Start))
11360       End = RHS;
11361     else
11362       End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
11363     BECount = computeBECount(getMinusSCEV(End, Start), Stride, false);
11364   }
11365 
11366   const SCEV *MaxBECount;
11367   bool MaxOrZero = false;
11368   if (isa<SCEVConstant>(BECount))
11369     MaxBECount = BECount;
11370   else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) {
11371     // If we know exactly how many times the backedge will be taken if it's
11372     // taken at least once, then the backedge count will either be that or
11373     // zero.
11374     MaxBECount = BECountIfBackedgeTaken;
11375     MaxOrZero = true;
11376   } else {
11377     MaxBECount = computeMaxBECountForLT(
11378         Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
11379   }
11380 
11381   if (isa<SCEVCouldNotCompute>(MaxBECount) &&
11382       !isa<SCEVCouldNotCompute>(BECount))
11383     MaxBECount = getConstant(getUnsignedRangeMax(BECount));
11384 
11385   return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates);
11386 }
11387 
11388 ScalarEvolution::ExitLimit
11389 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
11390                                      const Loop *L, bool IsSigned,
11391                                      bool ControlsExit, bool AllowPredicates) {
11392   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
11393   // We handle only IV > Invariant
11394   if (!isLoopInvariant(RHS, L))
11395     return getCouldNotCompute();
11396 
11397   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
11398   if (!IV && AllowPredicates)
11399     // Try to make this an AddRec using runtime tests, in the first X
11400     // iterations of this loop, where X is the SCEV expression found by the
11401     // algorithm below.
11402     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
11403 
11404   // Avoid weird loops
11405   if (!IV || IV->getLoop() != L || !IV->isAffine())
11406     return getCouldNotCompute();
11407 
11408   bool NoWrap = ControlsExit &&
11409                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
11410 
11411   const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
11412 
11413   // Avoid negative or zero stride values
11414   if (!isKnownPositive(Stride))
11415     return getCouldNotCompute();
11416 
11417   // Avoid proven overflow cases: this will ensure that the backedge taken count
11418   // will not generate any unsigned overflow. Relaxed no-overflow conditions
11419   // exploit NoWrapFlags, allowing to optimize in presence of undefined
11420   // behaviors like the case of C language.
11421   if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap))
11422     return getCouldNotCompute();
11423 
11424   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT
11425                                       : ICmpInst::ICMP_UGT;
11426 
11427   const SCEV *Start = IV->getStart();
11428   const SCEV *End = RHS;
11429   if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) {
11430     // If we know that Start >= RHS in the context of loop, then we know that
11431     // min(RHS, Start) = RHS at this point.
11432     if (isLoopEntryGuardedByCond(
11433             L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, RHS))
11434       End = RHS;
11435     else
11436       End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
11437   }
11438 
11439   const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false);
11440 
11441   APInt MaxStart = IsSigned ? getSignedRangeMax(Start)
11442                             : getUnsignedRangeMax(Start);
11443 
11444   APInt MinStride = IsSigned ? getSignedRangeMin(Stride)
11445                              : getUnsignedRangeMin(Stride);
11446 
11447   unsigned BitWidth = getTypeSizeInBits(LHS->getType());
11448   APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
11449                          : APInt::getMinValue(BitWidth) + (MinStride - 1);
11450 
11451   // Although End can be a MIN expression we estimate MinEnd considering only
11452   // the case End = RHS. This is safe because in the other case (Start - End)
11453   // is zero, leading to a zero maximum backedge taken count.
11454   APInt MinEnd =
11455     IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit)
11456              : APIntOps::umax(getUnsignedRangeMin(RHS), Limit);
11457 
11458   const SCEV *MaxBECount = isa<SCEVConstant>(BECount)
11459                                ? BECount
11460                                : computeBECount(getConstant(MaxStart - MinEnd),
11461                                                 getConstant(MinStride), false);
11462 
11463   if (isa<SCEVCouldNotCompute>(MaxBECount))
11464     MaxBECount = BECount;
11465 
11466   return ExitLimit(BECount, MaxBECount, false, Predicates);
11467 }
11468 
11469 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range,
11470                                                     ScalarEvolution &SE) const {
11471   if (Range.isFullSet())  // Infinite loop.
11472     return SE.getCouldNotCompute();
11473 
11474   // If the start is a non-zero constant, shift the range to simplify things.
11475   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
11476     if (!SC->getValue()->isZero()) {
11477       SmallVector<const SCEV *, 4> Operands(operands());
11478       Operands[0] = SE.getZero(SC->getType());
11479       const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
11480                                              getNoWrapFlags(FlagNW));
11481       if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
11482         return ShiftedAddRec->getNumIterationsInRange(
11483             Range.subtract(SC->getAPInt()), SE);
11484       // This is strange and shouldn't happen.
11485       return SE.getCouldNotCompute();
11486     }
11487 
11488   // The only time we can solve this is when we have all constant indices.
11489   // Otherwise, we cannot determine the overflow conditions.
11490   if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
11491     return SE.getCouldNotCompute();
11492 
11493   // Okay at this point we know that all elements of the chrec are constants and
11494   // that the start element is zero.
11495 
11496   // First check to see if the range contains zero.  If not, the first
11497   // iteration exits.
11498   unsigned BitWidth = SE.getTypeSizeInBits(getType());
11499   if (!Range.contains(APInt(BitWidth, 0)))
11500     return SE.getZero(getType());
11501 
11502   if (isAffine()) {
11503     // If this is an affine expression then we have this situation:
11504     //   Solve {0,+,A} in Range  ===  Ax in Range
11505 
11506     // We know that zero is in the range.  If A is positive then we know that
11507     // the upper value of the range must be the first possible exit value.
11508     // If A is negative then the lower of the range is the last possible loop
11509     // value.  Also note that we already checked for a full range.
11510     APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
11511     APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower();
11512 
11513     // The exit value should be (End+A)/A.
11514     APInt ExitVal = (End + A).udiv(A);
11515     ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
11516 
11517     // Evaluate at the exit value.  If we really did fall out of the valid
11518     // range, then we computed our trip count, otherwise wrap around or other
11519     // things must have happened.
11520     ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
11521     if (Range.contains(Val->getValue()))
11522       return SE.getCouldNotCompute();  // Something strange happened
11523 
11524     // Ensure that the previous value is in the range.  This is a sanity check.
11525     assert(Range.contains(
11526            EvaluateConstantChrecAtConstant(this,
11527            ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&
11528            "Linear scev computation is off in a bad way!");
11529     return SE.getConstant(ExitValue);
11530   }
11531 
11532   if (isQuadratic()) {
11533     if (auto S = SolveQuadraticAddRecRange(this, Range, SE))
11534       return SE.getConstant(S.getValue());
11535   }
11536 
11537   return SE.getCouldNotCompute();
11538 }
11539 
11540 const SCEVAddRecExpr *
11541 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const {
11542   assert(getNumOperands() > 1 && "AddRec with zero step?");
11543   // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)),
11544   // but in this case we cannot guarantee that the value returned will be an
11545   // AddRec because SCEV does not have a fixed point where it stops
11546   // simplification: it is legal to return ({rec1} + {rec2}). For example, it
11547   // may happen if we reach arithmetic depth limit while simplifying. So we
11548   // construct the returned value explicitly.
11549   SmallVector<const SCEV *, 3> Ops;
11550   // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and
11551   // (this + Step) is {A+B,+,B+C,+...,+,N}.
11552   for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i)
11553     Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1)));
11554   // We know that the last operand is not a constant zero (otherwise it would
11555   // have been popped out earlier). This guarantees us that if the result has
11556   // the same last operand, then it will also not be popped out, meaning that
11557   // the returned value will be an AddRec.
11558   const SCEV *Last = getOperand(getNumOperands() - 1);
11559   assert(!Last->isZero() && "Recurrency with zero step?");
11560   Ops.push_back(Last);
11561   return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(),
11562                                                SCEV::FlagAnyWrap));
11563 }
11564 
11565 // Return true when S contains at least an undef value.
11566 static inline bool containsUndefs(const SCEV *S) {
11567   return SCEVExprContains(S, [](const SCEV *S) {
11568     if (const auto *SU = dyn_cast<SCEVUnknown>(S))
11569       return isa<UndefValue>(SU->getValue());
11570     return false;
11571   });
11572 }
11573 
11574 namespace {
11575 
11576 // Collect all steps of SCEV expressions.
11577 struct SCEVCollectStrides {
11578   ScalarEvolution &SE;
11579   SmallVectorImpl<const SCEV *> &Strides;
11580 
11581   SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S)
11582       : SE(SE), Strides(S) {}
11583 
11584   bool follow(const SCEV *S) {
11585     if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
11586       Strides.push_back(AR->getStepRecurrence(SE));
11587     return true;
11588   }
11589 
11590   bool isDone() const { return false; }
11591 };
11592 
11593 // Collect all SCEVUnknown and SCEVMulExpr expressions.
11594 struct SCEVCollectTerms {
11595   SmallVectorImpl<const SCEV *> &Terms;
11596 
11597   SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) : Terms(T) {}
11598 
11599   bool follow(const SCEV *S) {
11600     if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) ||
11601         isa<SCEVSignExtendExpr>(S)) {
11602       if (!containsUndefs(S))
11603         Terms.push_back(S);
11604 
11605       // Stop recursion: once we collected a term, do not walk its operands.
11606       return false;
11607     }
11608 
11609     // Keep looking.
11610     return true;
11611   }
11612 
11613   bool isDone() const { return false; }
11614 };
11615 
11616 // Check if a SCEV contains an AddRecExpr.
11617 struct SCEVHasAddRec {
11618   bool &ContainsAddRec;
11619 
11620   SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) {
11621     ContainsAddRec = false;
11622   }
11623 
11624   bool follow(const SCEV *S) {
11625     if (isa<SCEVAddRecExpr>(S)) {
11626       ContainsAddRec = true;
11627 
11628       // Stop recursion: once we collected a term, do not walk its operands.
11629       return false;
11630     }
11631 
11632     // Keep looking.
11633     return true;
11634   }
11635 
11636   bool isDone() const { return false; }
11637 };
11638 
11639 // Find factors that are multiplied with an expression that (possibly as a
11640 // subexpression) contains an AddRecExpr. In the expression:
11641 //
11642 //  8 * (100 +  %p * %q * (%a + {0, +, 1}_loop))
11643 //
11644 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)"
11645 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size
11646 // parameters as they form a product with an induction variable.
11647 //
11648 // This collector expects all array size parameters to be in the same MulExpr.
11649 // It might be necessary to later add support for collecting parameters that are
11650 // spread over different nested MulExpr.
11651 struct SCEVCollectAddRecMultiplies {
11652   SmallVectorImpl<const SCEV *> &Terms;
11653   ScalarEvolution &SE;
11654 
11655   SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE)
11656       : Terms(T), SE(SE) {}
11657 
11658   bool follow(const SCEV *S) {
11659     if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) {
11660       bool HasAddRec = false;
11661       SmallVector<const SCEV *, 0> Operands;
11662       for (auto Op : Mul->operands()) {
11663         const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op);
11664         if (Unknown && !isa<CallInst>(Unknown->getValue())) {
11665           Operands.push_back(Op);
11666         } else if (Unknown) {
11667           HasAddRec = true;
11668         } else {
11669           bool ContainsAddRec = false;
11670           SCEVHasAddRec ContiansAddRec(ContainsAddRec);
11671           visitAll(Op, ContiansAddRec);
11672           HasAddRec |= ContainsAddRec;
11673         }
11674       }
11675       if (Operands.size() == 0)
11676         return true;
11677 
11678       if (!HasAddRec)
11679         return false;
11680 
11681       Terms.push_back(SE.getMulExpr(Operands));
11682       // Stop recursion: once we collected a term, do not walk its operands.
11683       return false;
11684     }
11685 
11686     // Keep looking.
11687     return true;
11688   }
11689 
11690   bool isDone() const { return false; }
11691 };
11692 
11693 } // end anonymous namespace
11694 
11695 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in
11696 /// two places:
11697 ///   1) The strides of AddRec expressions.
11698 ///   2) Unknowns that are multiplied with AddRec expressions.
11699 void ScalarEvolution::collectParametricTerms(const SCEV *Expr,
11700     SmallVectorImpl<const SCEV *> &Terms) {
11701   SmallVector<const SCEV *, 4> Strides;
11702   SCEVCollectStrides StrideCollector(*this, Strides);
11703   visitAll(Expr, StrideCollector);
11704 
11705   LLVM_DEBUG({
11706     dbgs() << "Strides:\n";
11707     for (const SCEV *S : Strides)
11708       dbgs() << *S << "\n";
11709   });
11710 
11711   for (const SCEV *S : Strides) {
11712     SCEVCollectTerms TermCollector(Terms);
11713     visitAll(S, TermCollector);
11714   }
11715 
11716   LLVM_DEBUG({
11717     dbgs() << "Terms:\n";
11718     for (const SCEV *T : Terms)
11719       dbgs() << *T << "\n";
11720   });
11721 
11722   SCEVCollectAddRecMultiplies MulCollector(Terms, *this);
11723   visitAll(Expr, MulCollector);
11724 }
11725 
11726 static bool findArrayDimensionsRec(ScalarEvolution &SE,
11727                                    SmallVectorImpl<const SCEV *> &Terms,
11728                                    SmallVectorImpl<const SCEV *> &Sizes) {
11729   int Last = Terms.size() - 1;
11730   const SCEV *Step = Terms[Last];
11731 
11732   // End of recursion.
11733   if (Last == 0) {
11734     if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) {
11735       SmallVector<const SCEV *, 2> Qs;
11736       for (const SCEV *Op : M->operands())
11737         if (!isa<SCEVConstant>(Op))
11738           Qs.push_back(Op);
11739 
11740       Step = SE.getMulExpr(Qs);
11741     }
11742 
11743     Sizes.push_back(Step);
11744     return true;
11745   }
11746 
11747   for (const SCEV *&Term : Terms) {
11748     // Normalize the terms before the next call to findArrayDimensionsRec.
11749     const SCEV *Q, *R;
11750     SCEVDivision::divide(SE, Term, Step, &Q, &R);
11751 
11752     // Bail out when GCD does not evenly divide one of the terms.
11753     if (!R->isZero())
11754       return false;
11755 
11756     Term = Q;
11757   }
11758 
11759   // Remove all SCEVConstants.
11760   erase_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); });
11761 
11762   if (Terms.size() > 0)
11763     if (!findArrayDimensionsRec(SE, Terms, Sizes))
11764       return false;
11765 
11766   Sizes.push_back(Step);
11767   return true;
11768 }
11769 
11770 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter.
11771 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) {
11772   for (const SCEV *T : Terms)
11773     if (SCEVExprContains(T, [](const SCEV *S) { return isa<SCEVUnknown>(S); }))
11774       return true;
11775 
11776   return false;
11777 }
11778 
11779 // Return the number of product terms in S.
11780 static inline int numberOfTerms(const SCEV *S) {
11781   if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S))
11782     return Expr->getNumOperands();
11783   return 1;
11784 }
11785 
11786 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) {
11787   if (isa<SCEVConstant>(T))
11788     return nullptr;
11789 
11790   if (isa<SCEVUnknown>(T))
11791     return T;
11792 
11793   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) {
11794     SmallVector<const SCEV *, 2> Factors;
11795     for (const SCEV *Op : M->operands())
11796       if (!isa<SCEVConstant>(Op))
11797         Factors.push_back(Op);
11798 
11799     return SE.getMulExpr(Factors);
11800   }
11801 
11802   return T;
11803 }
11804 
11805 /// Return the size of an element read or written by Inst.
11806 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
11807   Type *Ty;
11808   if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
11809     Ty = Store->getValueOperand()->getType();
11810   else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
11811     Ty = Load->getType();
11812   else
11813     return nullptr;
11814 
11815   Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
11816   return getSizeOfExpr(ETy, Ty);
11817 }
11818 
11819 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
11820                                           SmallVectorImpl<const SCEV *> &Sizes,
11821                                           const SCEV *ElementSize) {
11822   if (Terms.size() < 1 || !ElementSize)
11823     return;
11824 
11825   // Early return when Terms do not contain parameters: we do not delinearize
11826   // non parametric SCEVs.
11827   if (!containsParameters(Terms))
11828     return;
11829 
11830   LLVM_DEBUG({
11831     dbgs() << "Terms:\n";
11832     for (const SCEV *T : Terms)
11833       dbgs() << *T << "\n";
11834   });
11835 
11836   // Remove duplicates.
11837   array_pod_sort(Terms.begin(), Terms.end());
11838   Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end());
11839 
11840   // Put larger terms first.
11841   llvm::sort(Terms, [](const SCEV *LHS, const SCEV *RHS) {
11842     return numberOfTerms(LHS) > numberOfTerms(RHS);
11843   });
11844 
11845   // Try to divide all terms by the element size. If term is not divisible by
11846   // element size, proceed with the original term.
11847   for (const SCEV *&Term : Terms) {
11848     const SCEV *Q, *R;
11849     SCEVDivision::divide(*this, Term, ElementSize, &Q, &R);
11850     if (!Q->isZero())
11851       Term = Q;
11852   }
11853 
11854   SmallVector<const SCEV *, 4> NewTerms;
11855 
11856   // Remove constant factors.
11857   for (const SCEV *T : Terms)
11858     if (const SCEV *NewT = removeConstantFactors(*this, T))
11859       NewTerms.push_back(NewT);
11860 
11861   LLVM_DEBUG({
11862     dbgs() << "Terms after sorting:\n";
11863     for (const SCEV *T : NewTerms)
11864       dbgs() << *T << "\n";
11865   });
11866 
11867   if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) {
11868     Sizes.clear();
11869     return;
11870   }
11871 
11872   // The last element to be pushed into Sizes is the size of an element.
11873   Sizes.push_back(ElementSize);
11874 
11875   LLVM_DEBUG({
11876     dbgs() << "Sizes:\n";
11877     for (const SCEV *S : Sizes)
11878       dbgs() << *S << "\n";
11879   });
11880 }
11881 
11882 void ScalarEvolution::computeAccessFunctions(
11883     const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts,
11884     SmallVectorImpl<const SCEV *> &Sizes) {
11885   // Early exit in case this SCEV is not an affine multivariate function.
11886   if (Sizes.empty())
11887     return;
11888 
11889   if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr))
11890     if (!AR->isAffine())
11891       return;
11892 
11893   const SCEV *Res = Expr;
11894   int Last = Sizes.size() - 1;
11895   for (int i = Last; i >= 0; i--) {
11896     const SCEV *Q, *R;
11897     SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R);
11898 
11899     LLVM_DEBUG({
11900       dbgs() << "Res: " << *Res << "\n";
11901       dbgs() << "Sizes[i]: " << *Sizes[i] << "\n";
11902       dbgs() << "Res divided by Sizes[i]:\n";
11903       dbgs() << "Quotient: " << *Q << "\n";
11904       dbgs() << "Remainder: " << *R << "\n";
11905     });
11906 
11907     Res = Q;
11908 
11909     // Do not record the last subscript corresponding to the size of elements in
11910     // the array.
11911     if (i == Last) {
11912 
11913       // Bail out if the remainder is too complex.
11914       if (isa<SCEVAddRecExpr>(R)) {
11915         Subscripts.clear();
11916         Sizes.clear();
11917         return;
11918       }
11919 
11920       continue;
11921     }
11922 
11923     // Record the access function for the current subscript.
11924     Subscripts.push_back(R);
11925   }
11926 
11927   // Also push in last position the remainder of the last division: it will be
11928   // the access function of the innermost dimension.
11929   Subscripts.push_back(Res);
11930 
11931   std::reverse(Subscripts.begin(), Subscripts.end());
11932 
11933   LLVM_DEBUG({
11934     dbgs() << "Subscripts:\n";
11935     for (const SCEV *S : Subscripts)
11936       dbgs() << *S << "\n";
11937   });
11938 }
11939 
11940 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and
11941 /// sizes of an array access. Returns the remainder of the delinearization that
11942 /// is the offset start of the array.  The SCEV->delinearize algorithm computes
11943 /// the multiples of SCEV coefficients: that is a pattern matching of sub
11944 /// expressions in the stride and base of a SCEV corresponding to the
11945 /// computation of a GCD (greatest common divisor) of base and stride.  When
11946 /// SCEV->delinearize fails, it returns the SCEV unchanged.
11947 ///
11948 /// For example: when analyzing the memory access A[i][j][k] in this loop nest
11949 ///
11950 ///  void foo(long n, long m, long o, double A[n][m][o]) {
11951 ///
11952 ///    for (long i = 0; i < n; i++)
11953 ///      for (long j = 0; j < m; j++)
11954 ///        for (long k = 0; k < o; k++)
11955 ///          A[i][j][k] = 1.0;
11956 ///  }
11957 ///
11958 /// the delinearization input is the following AddRec SCEV:
11959 ///
11960 ///  AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k>
11961 ///
11962 /// From this SCEV, we are able to say that the base offset of the access is %A
11963 /// because it appears as an offset that does not divide any of the strides in
11964 /// the loops:
11965 ///
11966 ///  CHECK: Base offset: %A
11967 ///
11968 /// and then SCEV->delinearize determines the size of some of the dimensions of
11969 /// the array as these are the multiples by which the strides are happening:
11970 ///
11971 ///  CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes.
11972 ///
11973 /// Note that the outermost dimension remains of UnknownSize because there are
11974 /// no strides that would help identifying the size of the last dimension: when
11975 /// the array has been statically allocated, one could compute the size of that
11976 /// dimension by dividing the overall size of the array by the size of the known
11977 /// dimensions: %m * %o * 8.
11978 ///
11979 /// Finally delinearize provides the access functions for the array reference
11980 /// that does correspond to A[i][j][k] of the above C testcase:
11981 ///
11982 ///  CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>]
11983 ///
11984 /// The testcases are checking the output of a function pass:
11985 /// DelinearizationPass that walks through all loads and stores of a function
11986 /// asking for the SCEV of the memory access with respect to all enclosing
11987 /// loops, calling SCEV->delinearize on that and printing the results.
11988 void ScalarEvolution::delinearize(const SCEV *Expr,
11989                                  SmallVectorImpl<const SCEV *> &Subscripts,
11990                                  SmallVectorImpl<const SCEV *> &Sizes,
11991                                  const SCEV *ElementSize) {
11992   // First step: collect parametric terms.
11993   SmallVector<const SCEV *, 4> Terms;
11994   collectParametricTerms(Expr, Terms);
11995 
11996   if (Terms.empty())
11997     return;
11998 
11999   // Second step: find subscript sizes.
12000   findArrayDimensions(Terms, Sizes, ElementSize);
12001 
12002   if (Sizes.empty())
12003     return;
12004 
12005   // Third step: compute the access functions for each subscript.
12006   computeAccessFunctions(Expr, Subscripts, Sizes);
12007 
12008   if (Subscripts.empty())
12009     return;
12010 
12011   LLVM_DEBUG({
12012     dbgs() << "succeeded to delinearize " << *Expr << "\n";
12013     dbgs() << "ArrayDecl[UnknownSize]";
12014     for (const SCEV *S : Sizes)
12015       dbgs() << "[" << *S << "]";
12016 
12017     dbgs() << "\nArrayRef";
12018     for (const SCEV *S : Subscripts)
12019       dbgs() << "[" << *S << "]";
12020     dbgs() << "\n";
12021   });
12022 }
12023 
12024 bool ScalarEvolution::getIndexExpressionsFromGEP(
12025     const GetElementPtrInst *GEP, SmallVectorImpl<const SCEV *> &Subscripts,
12026     SmallVectorImpl<int> &Sizes) {
12027   assert(Subscripts.empty() && Sizes.empty() &&
12028          "Expected output lists to be empty on entry to this function.");
12029   assert(GEP && "getIndexExpressionsFromGEP called with a null GEP");
12030   Type *Ty = GEP->getPointerOperandType();
12031   bool DroppedFirstDim = false;
12032   for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
12033     const SCEV *Expr = getSCEV(GEP->getOperand(i));
12034     if (i == 1) {
12035       if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
12036         Ty = PtrTy->getElementType();
12037       } else if (auto *ArrayTy = dyn_cast<ArrayType>(Ty)) {
12038         Ty = ArrayTy->getElementType();
12039       } else {
12040         Subscripts.clear();
12041         Sizes.clear();
12042         return false;
12043       }
12044       if (auto *Const = dyn_cast<SCEVConstant>(Expr))
12045         if (Const->getValue()->isZero()) {
12046           DroppedFirstDim = true;
12047           continue;
12048         }
12049       Subscripts.push_back(Expr);
12050       continue;
12051     }
12052 
12053     auto *ArrayTy = dyn_cast<ArrayType>(Ty);
12054     if (!ArrayTy) {
12055       Subscripts.clear();
12056       Sizes.clear();
12057       return false;
12058     }
12059 
12060     Subscripts.push_back(Expr);
12061     if (!(DroppedFirstDim && i == 2))
12062       Sizes.push_back(ArrayTy->getNumElements());
12063 
12064     Ty = ArrayTy->getElementType();
12065   }
12066   return !Subscripts.empty();
12067 }
12068 
12069 //===----------------------------------------------------------------------===//
12070 //                   SCEVCallbackVH Class Implementation
12071 //===----------------------------------------------------------------------===//
12072 
12073 void ScalarEvolution::SCEVCallbackVH::deleted() {
12074   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
12075   if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
12076     SE->ConstantEvolutionLoopExitValue.erase(PN);
12077   SE->eraseValueFromMap(getValPtr());
12078   // this now dangles!
12079 }
12080 
12081 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
12082   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
12083 
12084   // Forget all the expressions associated with users of the old value,
12085   // so that future queries will recompute the expressions using the new
12086   // value.
12087   Value *Old = getValPtr();
12088   SmallVector<User *, 16> Worklist(Old->users());
12089   SmallPtrSet<User *, 8> Visited;
12090   while (!Worklist.empty()) {
12091     User *U = Worklist.pop_back_val();
12092     // Deleting the Old value will cause this to dangle. Postpone
12093     // that until everything else is done.
12094     if (U == Old)
12095       continue;
12096     if (!Visited.insert(U).second)
12097       continue;
12098     if (PHINode *PN = dyn_cast<PHINode>(U))
12099       SE->ConstantEvolutionLoopExitValue.erase(PN);
12100     SE->eraseValueFromMap(U);
12101     llvm::append_range(Worklist, U->users());
12102   }
12103   // Delete the Old value.
12104   if (PHINode *PN = dyn_cast<PHINode>(Old))
12105     SE->ConstantEvolutionLoopExitValue.erase(PN);
12106   SE->eraseValueFromMap(Old);
12107   // this now dangles!
12108 }
12109 
12110 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
12111   : CallbackVH(V), SE(se) {}
12112 
12113 //===----------------------------------------------------------------------===//
12114 //                   ScalarEvolution Class Implementation
12115 //===----------------------------------------------------------------------===//
12116 
12117 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
12118                                  AssumptionCache &AC, DominatorTree &DT,
12119                                  LoopInfo &LI)
12120     : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
12121       CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64),
12122       LoopDispositions(64), BlockDispositions(64) {
12123   // To use guards for proving predicates, we need to scan every instruction in
12124   // relevant basic blocks, and not just terminators.  Doing this is a waste of
12125   // time if the IR does not actually contain any calls to
12126   // @llvm.experimental.guard, so do a quick check and remember this beforehand.
12127   //
12128   // This pessimizes the case where a pass that preserves ScalarEvolution wants
12129   // to _add_ guards to the module when there weren't any before, and wants
12130   // ScalarEvolution to optimize based on those guards.  For now we prefer to be
12131   // efficient in lieu of being smart in that rather obscure case.
12132 
12133   auto *GuardDecl = F.getParent()->getFunction(
12134       Intrinsic::getName(Intrinsic::experimental_guard));
12135   HasGuards = GuardDecl && !GuardDecl->use_empty();
12136 }
12137 
12138 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
12139     : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT),
12140       LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
12141       ValueExprMap(std::move(Arg.ValueExprMap)),
12142       PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
12143       PendingPhiRanges(std::move(Arg.PendingPhiRanges)),
12144       PendingMerges(std::move(Arg.PendingMerges)),
12145       MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)),
12146       BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
12147       PredicatedBackedgeTakenCounts(
12148           std::move(Arg.PredicatedBackedgeTakenCounts)),
12149       ConstantEvolutionLoopExitValue(
12150           std::move(Arg.ConstantEvolutionLoopExitValue)),
12151       ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
12152       LoopDispositions(std::move(Arg.LoopDispositions)),
12153       LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
12154       BlockDispositions(std::move(Arg.BlockDispositions)),
12155       UnsignedRanges(std::move(Arg.UnsignedRanges)),
12156       SignedRanges(std::move(Arg.SignedRanges)),
12157       UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
12158       UniquePreds(std::move(Arg.UniquePreds)),
12159       SCEVAllocator(std::move(Arg.SCEVAllocator)),
12160       LoopUsers(std::move(Arg.LoopUsers)),
12161       PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)),
12162       FirstUnknown(Arg.FirstUnknown) {
12163   Arg.FirstUnknown = nullptr;
12164 }
12165 
12166 ScalarEvolution::~ScalarEvolution() {
12167   // Iterate through all the SCEVUnknown instances and call their
12168   // destructors, so that they release their references to their values.
12169   for (SCEVUnknown *U = FirstUnknown; U;) {
12170     SCEVUnknown *Tmp = U;
12171     U = U->Next;
12172     Tmp->~SCEVUnknown();
12173   }
12174   FirstUnknown = nullptr;
12175 
12176   ExprValueMap.clear();
12177   ValueExprMap.clear();
12178   HasRecMap.clear();
12179 
12180   // Free any extra memory created for ExitNotTakenInfo in the unlikely event
12181   // that a loop had multiple computable exits.
12182   for (auto &BTCI : BackedgeTakenCounts)
12183     BTCI.second.clear();
12184   for (auto &BTCI : PredicatedBackedgeTakenCounts)
12185     BTCI.second.clear();
12186 
12187   assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
12188   assert(PendingPhiRanges.empty() && "getRangeRef garbage");
12189   assert(PendingMerges.empty() && "isImpliedViaMerge garbage");
12190   assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
12191   assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
12192 }
12193 
12194 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
12195   return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
12196 }
12197 
12198 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
12199                           const Loop *L) {
12200   // Print all inner loops first
12201   for (Loop *I : *L)
12202     PrintLoopInfo(OS, SE, I);
12203 
12204   OS << "Loop ";
12205   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12206   OS << ": ";
12207 
12208   SmallVector<BasicBlock *, 8> ExitingBlocks;
12209   L->getExitingBlocks(ExitingBlocks);
12210   if (ExitingBlocks.size() != 1)
12211     OS << "<multiple exits> ";
12212 
12213   if (SE->hasLoopInvariantBackedgeTakenCount(L))
12214     OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L) << "\n";
12215   else
12216     OS << "Unpredictable backedge-taken count.\n";
12217 
12218   if (ExitingBlocks.size() > 1)
12219     for (BasicBlock *ExitingBlock : ExitingBlocks) {
12220       OS << "  exit count for " << ExitingBlock->getName() << ": "
12221          << *SE->getExitCount(L, ExitingBlock) << "\n";
12222     }
12223 
12224   OS << "Loop ";
12225   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12226   OS << ": ";
12227 
12228   if (!isa<SCEVCouldNotCompute>(SE->getConstantMaxBackedgeTakenCount(L))) {
12229     OS << "max backedge-taken count is " << *SE->getConstantMaxBackedgeTakenCount(L);
12230     if (SE->isBackedgeTakenCountMaxOrZero(L))
12231       OS << ", actual taken count either this or zero.";
12232   } else {
12233     OS << "Unpredictable max backedge-taken count. ";
12234   }
12235 
12236   OS << "\n"
12237         "Loop ";
12238   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12239   OS << ": ";
12240 
12241   SCEVUnionPredicate Pred;
12242   auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred);
12243   if (!isa<SCEVCouldNotCompute>(PBT)) {
12244     OS << "Predicated backedge-taken count is " << *PBT << "\n";
12245     OS << " Predicates:\n";
12246     Pred.print(OS, 4);
12247   } else {
12248     OS << "Unpredictable predicated backedge-taken count. ";
12249   }
12250   OS << "\n";
12251 
12252   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
12253     OS << "Loop ";
12254     L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12255     OS << ": ";
12256     OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
12257   }
12258 }
12259 
12260 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) {
12261   switch (LD) {
12262   case ScalarEvolution::LoopVariant:
12263     return "Variant";
12264   case ScalarEvolution::LoopInvariant:
12265     return "Invariant";
12266   case ScalarEvolution::LoopComputable:
12267     return "Computable";
12268   }
12269   llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!");
12270 }
12271 
12272 void ScalarEvolution::print(raw_ostream &OS) const {
12273   // ScalarEvolution's implementation of the print method is to print
12274   // out SCEV values of all instructions that are interesting. Doing
12275   // this potentially causes it to create new SCEV objects though,
12276   // which technically conflicts with the const qualifier. This isn't
12277   // observable from outside the class though, so casting away the
12278   // const isn't dangerous.
12279   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
12280 
12281   if (ClassifyExpressions) {
12282     OS << "Classifying expressions for: ";
12283     F.printAsOperand(OS, /*PrintType=*/false);
12284     OS << "\n";
12285     for (Instruction &I : instructions(F))
12286       if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
12287         OS << I << '\n';
12288         OS << "  -->  ";
12289         const SCEV *SV = SE.getSCEV(&I);
12290         SV->print(OS);
12291         if (!isa<SCEVCouldNotCompute>(SV)) {
12292           OS << " U: ";
12293           SE.getUnsignedRange(SV).print(OS);
12294           OS << " S: ";
12295           SE.getSignedRange(SV).print(OS);
12296         }
12297 
12298         const Loop *L = LI.getLoopFor(I.getParent());
12299 
12300         const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
12301         if (AtUse != SV) {
12302           OS << "  -->  ";
12303           AtUse->print(OS);
12304           if (!isa<SCEVCouldNotCompute>(AtUse)) {
12305             OS << " U: ";
12306             SE.getUnsignedRange(AtUse).print(OS);
12307             OS << " S: ";
12308             SE.getSignedRange(AtUse).print(OS);
12309           }
12310         }
12311 
12312         if (L) {
12313           OS << "\t\t" "Exits: ";
12314           const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
12315           if (!SE.isLoopInvariant(ExitValue, L)) {
12316             OS << "<<Unknown>>";
12317           } else {
12318             OS << *ExitValue;
12319           }
12320 
12321           bool First = true;
12322           for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
12323             if (First) {
12324               OS << "\t\t" "LoopDispositions: { ";
12325               First = false;
12326             } else {
12327               OS << ", ";
12328             }
12329 
12330             Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12331             OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter));
12332           }
12333 
12334           for (auto *InnerL : depth_first(L)) {
12335             if (InnerL == L)
12336               continue;
12337             if (First) {
12338               OS << "\t\t" "LoopDispositions: { ";
12339               First = false;
12340             } else {
12341               OS << ", ";
12342             }
12343 
12344             InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12345             OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL));
12346           }
12347 
12348           OS << " }";
12349         }
12350 
12351         OS << "\n";
12352       }
12353   }
12354 
12355   OS << "Determining loop execution counts for: ";
12356   F.printAsOperand(OS, /*PrintType=*/false);
12357   OS << "\n";
12358   for (Loop *I : LI)
12359     PrintLoopInfo(OS, &SE, I);
12360 }
12361 
12362 ScalarEvolution::LoopDisposition
12363 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
12364   auto &Values = LoopDispositions[S];
12365   for (auto &V : Values) {
12366     if (V.getPointer() == L)
12367       return V.getInt();
12368   }
12369   Values.emplace_back(L, LoopVariant);
12370   LoopDisposition D = computeLoopDisposition(S, L);
12371   auto &Values2 = LoopDispositions[S];
12372   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
12373     if (V.getPointer() == L) {
12374       V.setInt(D);
12375       break;
12376     }
12377   }
12378   return D;
12379 }
12380 
12381 ScalarEvolution::LoopDisposition
12382 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
12383   switch (S->getSCEVType()) {
12384   case scConstant:
12385     return LoopInvariant;
12386   case scPtrToInt:
12387   case scTruncate:
12388   case scZeroExtend:
12389   case scSignExtend:
12390     return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
12391   case scAddRecExpr: {
12392     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
12393 
12394     // If L is the addrec's loop, it's computable.
12395     if (AR->getLoop() == L)
12396       return LoopComputable;
12397 
12398     // Add recurrences are never invariant in the function-body (null loop).
12399     if (!L)
12400       return LoopVariant;
12401 
12402     // Everything that is not defined at loop entry is variant.
12403     if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader()))
12404       return LoopVariant;
12405     assert(!L->contains(AR->getLoop()) && "Containing loop's header does not"
12406            " dominate the contained loop's header?");
12407 
12408     // This recurrence is invariant w.r.t. L if AR's loop contains L.
12409     if (AR->getLoop()->contains(L))
12410       return LoopInvariant;
12411 
12412     // This recurrence is variant w.r.t. L if any of its operands
12413     // are variant.
12414     for (auto *Op : AR->operands())
12415       if (!isLoopInvariant(Op, L))
12416         return LoopVariant;
12417 
12418     // Otherwise it's loop-invariant.
12419     return LoopInvariant;
12420   }
12421   case scAddExpr:
12422   case scMulExpr:
12423   case scUMaxExpr:
12424   case scSMaxExpr:
12425   case scUMinExpr:
12426   case scSMinExpr: {
12427     bool HasVarying = false;
12428     for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) {
12429       LoopDisposition D = getLoopDisposition(Op, L);
12430       if (D == LoopVariant)
12431         return LoopVariant;
12432       if (D == LoopComputable)
12433         HasVarying = true;
12434     }
12435     return HasVarying ? LoopComputable : LoopInvariant;
12436   }
12437   case scUDivExpr: {
12438     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
12439     LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
12440     if (LD == LoopVariant)
12441       return LoopVariant;
12442     LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
12443     if (RD == LoopVariant)
12444       return LoopVariant;
12445     return (LD == LoopInvariant && RD == LoopInvariant) ?
12446            LoopInvariant : LoopComputable;
12447   }
12448   case scUnknown:
12449     // All non-instruction values are loop invariant.  All instructions are loop
12450     // invariant if they are not contained in the specified loop.
12451     // Instructions are never considered invariant in the function body
12452     // (null loop) because they are defined within the "loop".
12453     if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
12454       return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
12455     return LoopInvariant;
12456   case scCouldNotCompute:
12457     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
12458   }
12459   llvm_unreachable("Unknown SCEV kind!");
12460 }
12461 
12462 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
12463   return getLoopDisposition(S, L) == LoopInvariant;
12464 }
12465 
12466 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
12467   return getLoopDisposition(S, L) == LoopComputable;
12468 }
12469 
12470 ScalarEvolution::BlockDisposition
12471 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
12472   auto &Values = BlockDispositions[S];
12473   for (auto &V : Values) {
12474     if (V.getPointer() == BB)
12475       return V.getInt();
12476   }
12477   Values.emplace_back(BB, DoesNotDominateBlock);
12478   BlockDisposition D = computeBlockDisposition(S, BB);
12479   auto &Values2 = BlockDispositions[S];
12480   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
12481     if (V.getPointer() == BB) {
12482       V.setInt(D);
12483       break;
12484     }
12485   }
12486   return D;
12487 }
12488 
12489 ScalarEvolution::BlockDisposition
12490 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
12491   switch (S->getSCEVType()) {
12492   case scConstant:
12493     return ProperlyDominatesBlock;
12494   case scPtrToInt:
12495   case scTruncate:
12496   case scZeroExtend:
12497   case scSignExtend:
12498     return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
12499   case scAddRecExpr: {
12500     // This uses a "dominates" query instead of "properly dominates" query
12501     // to test for proper dominance too, because the instruction which
12502     // produces the addrec's value is a PHI, and a PHI effectively properly
12503     // dominates its entire containing block.
12504     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
12505     if (!DT.dominates(AR->getLoop()->getHeader(), BB))
12506       return DoesNotDominateBlock;
12507 
12508     // Fall through into SCEVNAryExpr handling.
12509     LLVM_FALLTHROUGH;
12510   }
12511   case scAddExpr:
12512   case scMulExpr:
12513   case scUMaxExpr:
12514   case scSMaxExpr:
12515   case scUMinExpr:
12516   case scSMinExpr: {
12517     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
12518     bool Proper = true;
12519     for (const SCEV *NAryOp : NAry->operands()) {
12520       BlockDisposition D = getBlockDisposition(NAryOp, BB);
12521       if (D == DoesNotDominateBlock)
12522         return DoesNotDominateBlock;
12523       if (D == DominatesBlock)
12524         Proper = false;
12525     }
12526     return Proper ? ProperlyDominatesBlock : DominatesBlock;
12527   }
12528   case scUDivExpr: {
12529     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
12530     const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
12531     BlockDisposition LD = getBlockDisposition(LHS, BB);
12532     if (LD == DoesNotDominateBlock)
12533       return DoesNotDominateBlock;
12534     BlockDisposition RD = getBlockDisposition(RHS, BB);
12535     if (RD == DoesNotDominateBlock)
12536       return DoesNotDominateBlock;
12537     return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
12538       ProperlyDominatesBlock : DominatesBlock;
12539   }
12540   case scUnknown:
12541     if (Instruction *I =
12542           dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
12543       if (I->getParent() == BB)
12544         return DominatesBlock;
12545       if (DT.properlyDominates(I->getParent(), BB))
12546         return ProperlyDominatesBlock;
12547       return DoesNotDominateBlock;
12548     }
12549     return ProperlyDominatesBlock;
12550   case scCouldNotCompute:
12551     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
12552   }
12553   llvm_unreachable("Unknown SCEV kind!");
12554 }
12555 
12556 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
12557   return getBlockDisposition(S, BB) >= DominatesBlock;
12558 }
12559 
12560 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
12561   return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
12562 }
12563 
12564 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
12565   return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; });
12566 }
12567 
12568 bool ScalarEvolution::ExitLimit::hasOperand(const SCEV *S) const {
12569   auto IsS = [&](const SCEV *X) { return S == X; };
12570   auto ContainsS = [&](const SCEV *X) {
12571     return !isa<SCEVCouldNotCompute>(X) && SCEVExprContains(X, IsS);
12572   };
12573   return ContainsS(ExactNotTaken) || ContainsS(MaxNotTaken);
12574 }
12575 
12576 void
12577 ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
12578   ValuesAtScopes.erase(S);
12579   LoopDispositions.erase(S);
12580   BlockDispositions.erase(S);
12581   UnsignedRanges.erase(S);
12582   SignedRanges.erase(S);
12583   ExprValueMap.erase(S);
12584   HasRecMap.erase(S);
12585   MinTrailingZerosCache.erase(S);
12586 
12587   for (auto I = PredicatedSCEVRewrites.begin();
12588        I != PredicatedSCEVRewrites.end();) {
12589     std::pair<const SCEV *, const Loop *> Entry = I->first;
12590     if (Entry.first == S)
12591       PredicatedSCEVRewrites.erase(I++);
12592     else
12593       ++I;
12594   }
12595 
12596   auto RemoveSCEVFromBackedgeMap =
12597       [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
12598         for (auto I = Map.begin(), E = Map.end(); I != E;) {
12599           BackedgeTakenInfo &BEInfo = I->second;
12600           if (BEInfo.hasOperand(S, this)) {
12601             BEInfo.clear();
12602             Map.erase(I++);
12603           } else
12604             ++I;
12605         }
12606       };
12607 
12608   RemoveSCEVFromBackedgeMap(BackedgeTakenCounts);
12609   RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts);
12610 }
12611 
12612 void
12613 ScalarEvolution::getUsedLoops(const SCEV *S,
12614                               SmallPtrSetImpl<const Loop *> &LoopsUsed) {
12615   struct FindUsedLoops {
12616     FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed)
12617         : LoopsUsed(LoopsUsed) {}
12618     SmallPtrSetImpl<const Loop *> &LoopsUsed;
12619     bool follow(const SCEV *S) {
12620       if (auto *AR = dyn_cast<SCEVAddRecExpr>(S))
12621         LoopsUsed.insert(AR->getLoop());
12622       return true;
12623     }
12624 
12625     bool isDone() const { return false; }
12626   };
12627 
12628   FindUsedLoops F(LoopsUsed);
12629   SCEVTraversal<FindUsedLoops>(F).visitAll(S);
12630 }
12631 
12632 void ScalarEvolution::addToLoopUseLists(const SCEV *S) {
12633   SmallPtrSet<const Loop *, 8> LoopsUsed;
12634   getUsedLoops(S, LoopsUsed);
12635   for (auto *L : LoopsUsed)
12636     LoopUsers[L].push_back(S);
12637 }
12638 
12639 void ScalarEvolution::verify() const {
12640   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
12641   ScalarEvolution SE2(F, TLI, AC, DT, LI);
12642 
12643   SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end());
12644 
12645   // Map's SCEV expressions from one ScalarEvolution "universe" to another.
12646   struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> {
12647     SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {}
12648 
12649     const SCEV *visitConstant(const SCEVConstant *Constant) {
12650       return SE.getConstant(Constant->getAPInt());
12651     }
12652 
12653     const SCEV *visitUnknown(const SCEVUnknown *Expr) {
12654       return SE.getUnknown(Expr->getValue());
12655     }
12656 
12657     const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
12658       return SE.getCouldNotCompute();
12659     }
12660   };
12661 
12662   SCEVMapper SCM(SE2);
12663 
12664   while (!LoopStack.empty()) {
12665     auto *L = LoopStack.pop_back_val();
12666     llvm::append_range(LoopStack, *L);
12667 
12668     auto *CurBECount = SCM.visit(
12669         const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L));
12670     auto *NewBECount = SE2.getBackedgeTakenCount(L);
12671 
12672     if (CurBECount == SE2.getCouldNotCompute() ||
12673         NewBECount == SE2.getCouldNotCompute()) {
12674       // NB! This situation is legal, but is very suspicious -- whatever pass
12675       // change the loop to make a trip count go from could not compute to
12676       // computable or vice-versa *should have* invalidated SCEV.  However, we
12677       // choose not to assert here (for now) since we don't want false
12678       // positives.
12679       continue;
12680     }
12681 
12682     if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) {
12683       // SCEV treats "undef" as an unknown but consistent value (i.e. it does
12684       // not propagate undef aggressively).  This means we can (and do) fail
12685       // verification in cases where a transform makes the trip count of a loop
12686       // go from "undef" to "undef+1" (say).  The transform is fine, since in
12687       // both cases the loop iterates "undef" times, but SCEV thinks we
12688       // increased the trip count of the loop by 1 incorrectly.
12689       continue;
12690     }
12691 
12692     if (SE.getTypeSizeInBits(CurBECount->getType()) >
12693         SE.getTypeSizeInBits(NewBECount->getType()))
12694       NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType());
12695     else if (SE.getTypeSizeInBits(CurBECount->getType()) <
12696              SE.getTypeSizeInBits(NewBECount->getType()))
12697       CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType());
12698 
12699     const SCEV *Delta = SE2.getMinusSCEV(CurBECount, NewBECount);
12700 
12701     // Unless VerifySCEVStrict is set, we only compare constant deltas.
12702     if ((VerifySCEVStrict || isa<SCEVConstant>(Delta)) && !Delta->isZero()) {
12703       dbgs() << "Trip Count for " << *L << " Changed!\n";
12704       dbgs() << "Old: " << *CurBECount << "\n";
12705       dbgs() << "New: " << *NewBECount << "\n";
12706       dbgs() << "Delta: " << *Delta << "\n";
12707       std::abort();
12708     }
12709   }
12710 
12711   // Collect all valid loops currently in LoopInfo.
12712   SmallPtrSet<Loop *, 32> ValidLoops;
12713   SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end());
12714   while (!Worklist.empty()) {
12715     Loop *L = Worklist.pop_back_val();
12716     if (ValidLoops.contains(L))
12717       continue;
12718     ValidLoops.insert(L);
12719     Worklist.append(L->begin(), L->end());
12720   }
12721   // Check for SCEV expressions referencing invalid/deleted loops.
12722   for (auto &KV : ValueExprMap) {
12723     auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second);
12724     if (!AR)
12725       continue;
12726     assert(ValidLoops.contains(AR->getLoop()) &&
12727            "AddRec references invalid loop");
12728   }
12729 }
12730 
12731 bool ScalarEvolution::invalidate(
12732     Function &F, const PreservedAnalyses &PA,
12733     FunctionAnalysisManager::Invalidator &Inv) {
12734   // Invalidate the ScalarEvolution object whenever it isn't preserved or one
12735   // of its dependencies is invalidated.
12736   auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
12737   return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
12738          Inv.invalidate<AssumptionAnalysis>(F, PA) ||
12739          Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
12740          Inv.invalidate<LoopAnalysis>(F, PA);
12741 }
12742 
12743 AnalysisKey ScalarEvolutionAnalysis::Key;
12744 
12745 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
12746                                              FunctionAnalysisManager &AM) {
12747   return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F),
12748                          AM.getResult<AssumptionAnalysis>(F),
12749                          AM.getResult<DominatorTreeAnalysis>(F),
12750                          AM.getResult<LoopAnalysis>(F));
12751 }
12752 
12753 PreservedAnalyses
12754 ScalarEvolutionVerifierPass::run(Function &F, FunctionAnalysisManager &AM) {
12755   AM.getResult<ScalarEvolutionAnalysis>(F).verify();
12756   return PreservedAnalyses::all();
12757 }
12758 
12759 PreservedAnalyses
12760 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
12761   // For compatibility with opt's -analyze feature under legacy pass manager
12762   // which was not ported to NPM. This keeps tests using
12763   // update_analyze_test_checks.py working.
12764   OS << "Printing analysis 'Scalar Evolution Analysis' for function '"
12765      << F.getName() << "':\n";
12766   AM.getResult<ScalarEvolutionAnalysis>(F).print(OS);
12767   return PreservedAnalyses::all();
12768 }
12769 
12770 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
12771                       "Scalar Evolution Analysis", false, true)
12772 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
12773 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
12774 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
12775 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
12776 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
12777                     "Scalar Evolution Analysis", false, true)
12778 
12779 char ScalarEvolutionWrapperPass::ID = 0;
12780 
12781 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
12782   initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
12783 }
12784 
12785 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
12786   SE.reset(new ScalarEvolution(
12787       F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F),
12788       getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
12789       getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
12790       getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
12791   return false;
12792 }
12793 
12794 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
12795 
12796 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
12797   SE->print(OS);
12798 }
12799 
12800 void ScalarEvolutionWrapperPass::verifyAnalysis() const {
12801   if (!VerifySCEV)
12802     return;
12803 
12804   SE->verify();
12805 }
12806 
12807 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
12808   AU.setPreservesAll();
12809   AU.addRequiredTransitive<AssumptionCacheTracker>();
12810   AU.addRequiredTransitive<LoopInfoWrapperPass>();
12811   AU.addRequiredTransitive<DominatorTreeWrapperPass>();
12812   AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
12813 }
12814 
12815 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS,
12816                                                         const SCEV *RHS) {
12817   FoldingSetNodeID ID;
12818   assert(LHS->getType() == RHS->getType() &&
12819          "Type mismatch between LHS and RHS");
12820   // Unique this node based on the arguments
12821   ID.AddInteger(SCEVPredicate::P_Equal);
12822   ID.AddPointer(LHS);
12823   ID.AddPointer(RHS);
12824   void *IP = nullptr;
12825   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
12826     return S;
12827   SCEVEqualPredicate *Eq = new (SCEVAllocator)
12828       SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS);
12829   UniquePreds.InsertNode(Eq, IP);
12830   return Eq;
12831 }
12832 
12833 const SCEVPredicate *ScalarEvolution::getWrapPredicate(
12834     const SCEVAddRecExpr *AR,
12835     SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
12836   FoldingSetNodeID ID;
12837   // Unique this node based on the arguments
12838   ID.AddInteger(SCEVPredicate::P_Wrap);
12839   ID.AddPointer(AR);
12840   ID.AddInteger(AddedFlags);
12841   void *IP = nullptr;
12842   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
12843     return S;
12844   auto *OF = new (SCEVAllocator)
12845       SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
12846   UniquePreds.InsertNode(OF, IP);
12847   return OF;
12848 }
12849 
12850 namespace {
12851 
12852 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
12853 public:
12854 
12855   /// Rewrites \p S in the context of a loop L and the SCEV predication
12856   /// infrastructure.
12857   ///
12858   /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
12859   /// equivalences present in \p Pred.
12860   ///
12861   /// If \p NewPreds is non-null, rewrite is free to add further predicates to
12862   /// \p NewPreds such that the result will be an AddRecExpr.
12863   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
12864                              SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
12865                              SCEVUnionPredicate *Pred) {
12866     SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
12867     return Rewriter.visit(S);
12868   }
12869 
12870   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
12871     if (Pred) {
12872       auto ExprPreds = Pred->getPredicatesForExpr(Expr);
12873       for (auto *Pred : ExprPreds)
12874         if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred))
12875           if (IPred->getLHS() == Expr)
12876             return IPred->getRHS();
12877     }
12878     return convertToAddRecWithPreds(Expr);
12879   }
12880 
12881   const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
12882     const SCEV *Operand = visit(Expr->getOperand());
12883     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
12884     if (AR && AR->getLoop() == L && AR->isAffine()) {
12885       // This couldn't be folded because the operand didn't have the nuw
12886       // flag. Add the nusw flag as an assumption that we could make.
12887       const SCEV *Step = AR->getStepRecurrence(SE);
12888       Type *Ty = Expr->getType();
12889       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
12890         return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
12891                                 SE.getSignExtendExpr(Step, Ty), L,
12892                                 AR->getNoWrapFlags());
12893     }
12894     return SE.getZeroExtendExpr(Operand, Expr->getType());
12895   }
12896 
12897   const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
12898     const SCEV *Operand = visit(Expr->getOperand());
12899     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
12900     if (AR && AR->getLoop() == L && AR->isAffine()) {
12901       // This couldn't be folded because the operand didn't have the nsw
12902       // flag. Add the nssw flag as an assumption that we could make.
12903       const SCEV *Step = AR->getStepRecurrence(SE);
12904       Type *Ty = Expr->getType();
12905       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
12906         return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
12907                                 SE.getSignExtendExpr(Step, Ty), L,
12908                                 AR->getNoWrapFlags());
12909     }
12910     return SE.getSignExtendExpr(Operand, Expr->getType());
12911   }
12912 
12913 private:
12914   explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE,
12915                         SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
12916                         SCEVUnionPredicate *Pred)
12917       : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
12918 
12919   bool addOverflowAssumption(const SCEVPredicate *P) {
12920     if (!NewPreds) {
12921       // Check if we've already made this assumption.
12922       return Pred && Pred->implies(P);
12923     }
12924     NewPreds->insert(P);
12925     return true;
12926   }
12927 
12928   bool addOverflowAssumption(const SCEVAddRecExpr *AR,
12929                              SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
12930     auto *A = SE.getWrapPredicate(AR, AddedFlags);
12931     return addOverflowAssumption(A);
12932   }
12933 
12934   // If \p Expr represents a PHINode, we try to see if it can be represented
12935   // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible
12936   // to add this predicate as a runtime overflow check, we return the AddRec.
12937   // If \p Expr does not meet these conditions (is not a PHI node, or we
12938   // couldn't create an AddRec for it, or couldn't add the predicate), we just
12939   // return \p Expr.
12940   const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) {
12941     if (!isa<PHINode>(Expr->getValue()))
12942       return Expr;
12943     Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
12944     PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr);
12945     if (!PredicatedRewrite)
12946       return Expr;
12947     for (auto *P : PredicatedRewrite->second){
12948       // Wrap predicates from outer loops are not supported.
12949       if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) {
12950         auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr());
12951         if (L != AR->getLoop())
12952           return Expr;
12953       }
12954       if (!addOverflowAssumption(P))
12955         return Expr;
12956     }
12957     return PredicatedRewrite->first;
12958   }
12959 
12960   SmallPtrSetImpl<const SCEVPredicate *> *NewPreds;
12961   SCEVUnionPredicate *Pred;
12962   const Loop *L;
12963 };
12964 
12965 } // end anonymous namespace
12966 
12967 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
12968                                                    SCEVUnionPredicate &Preds) {
12969   return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
12970 }
12971 
12972 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates(
12973     const SCEV *S, const Loop *L,
12974     SmallPtrSetImpl<const SCEVPredicate *> &Preds) {
12975   SmallPtrSet<const SCEVPredicate *, 4> TransformPreds;
12976   S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
12977   auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
12978 
12979   if (!AddRec)
12980     return nullptr;
12981 
12982   // Since the transformation was successful, we can now transfer the SCEV
12983   // predicates.
12984   for (auto *P : TransformPreds)
12985     Preds.insert(P);
12986 
12987   return AddRec;
12988 }
12989 
12990 /// SCEV predicates
12991 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
12992                              SCEVPredicateKind Kind)
12993     : FastID(ID), Kind(Kind) {}
12994 
12995 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID,
12996                                        const SCEV *LHS, const SCEV *RHS)
12997     : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {
12998   assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match");
12999   assert(LHS != RHS && "LHS and RHS are the same SCEV");
13000 }
13001 
13002 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const {
13003   const auto *Op = dyn_cast<SCEVEqualPredicate>(N);
13004 
13005   if (!Op)
13006     return false;
13007 
13008   return Op->LHS == LHS && Op->RHS == RHS;
13009 }
13010 
13011 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; }
13012 
13013 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; }
13014 
13015 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const {
13016   OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
13017 }
13018 
13019 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
13020                                      const SCEVAddRecExpr *AR,
13021                                      IncrementWrapFlags Flags)
13022     : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
13023 
13024 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; }
13025 
13026 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const {
13027   const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
13028 
13029   return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags;
13030 }
13031 
13032 bool SCEVWrapPredicate::isAlwaysTrue() const {
13033   SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
13034   IncrementWrapFlags IFlags = Flags;
13035 
13036   if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
13037     IFlags = clearFlags(IFlags, IncrementNSSW);
13038 
13039   return IFlags == IncrementAnyWrap;
13040 }
13041 
13042 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
13043   OS.indent(Depth) << *getExpr() << " Added Flags: ";
13044   if (SCEVWrapPredicate::IncrementNUSW & getFlags())
13045     OS << "<nusw>";
13046   if (SCEVWrapPredicate::IncrementNSSW & getFlags())
13047     OS << "<nssw>";
13048   OS << "\n";
13049 }
13050 
13051 SCEVWrapPredicate::IncrementWrapFlags
13052 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR,
13053                                    ScalarEvolution &SE) {
13054   IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
13055   SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
13056 
13057   // We can safely transfer the NSW flag as NSSW.
13058   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
13059     ImpliedFlags = IncrementNSSW;
13060 
13061   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
13062     // If the increment is positive, the SCEV NUW flag will also imply the
13063     // WrapPredicate NUSW flag.
13064     if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
13065       if (Step->getValue()->getValue().isNonNegative())
13066         ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
13067   }
13068 
13069   return ImpliedFlags;
13070 }
13071 
13072 /// Union predicates don't get cached so create a dummy set ID for it.
13073 SCEVUnionPredicate::SCEVUnionPredicate()
13074     : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {}
13075 
13076 bool SCEVUnionPredicate::isAlwaysTrue() const {
13077   return all_of(Preds,
13078                 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
13079 }
13080 
13081 ArrayRef<const SCEVPredicate *>
13082 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) {
13083   auto I = SCEVToPreds.find(Expr);
13084   if (I == SCEVToPreds.end())
13085     return ArrayRef<const SCEVPredicate *>();
13086   return I->second;
13087 }
13088 
13089 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
13090   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
13091     return all_of(Set->Preds,
13092                   [this](const SCEVPredicate *I) { return this->implies(I); });
13093 
13094   auto ScevPredsIt = SCEVToPreds.find(N->getExpr());
13095   if (ScevPredsIt == SCEVToPreds.end())
13096     return false;
13097   auto &SCEVPreds = ScevPredsIt->second;
13098 
13099   return any_of(SCEVPreds,
13100                 [N](const SCEVPredicate *I) { return I->implies(N); });
13101 }
13102 
13103 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; }
13104 
13105 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
13106   for (auto Pred : Preds)
13107     Pred->print(OS, Depth);
13108 }
13109 
13110 void SCEVUnionPredicate::add(const SCEVPredicate *N) {
13111   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
13112     for (auto Pred : Set->Preds)
13113       add(Pred);
13114     return;
13115   }
13116 
13117   if (implies(N))
13118     return;
13119 
13120   const SCEV *Key = N->getExpr();
13121   assert(Key && "Only SCEVUnionPredicate doesn't have an "
13122                 " associated expression!");
13123 
13124   SCEVToPreds[Key].push_back(N);
13125   Preds.push_back(N);
13126 }
13127 
13128 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
13129                                                      Loop &L)
13130     : SE(SE), L(L) {}
13131 
13132 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
13133   const SCEV *Expr = SE.getSCEV(V);
13134   RewriteEntry &Entry = RewriteMap[Expr];
13135 
13136   // If we already have an entry and the version matches, return it.
13137   if (Entry.second && Generation == Entry.first)
13138     return Entry.second;
13139 
13140   // We found an entry but it's stale. Rewrite the stale entry
13141   // according to the current predicate.
13142   if (Entry.second)
13143     Expr = Entry.second;
13144 
13145   const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds);
13146   Entry = {Generation, NewSCEV};
13147 
13148   return NewSCEV;
13149 }
13150 
13151 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() {
13152   if (!BackedgeCount) {
13153     SCEVUnionPredicate BackedgePred;
13154     BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred);
13155     addPredicate(BackedgePred);
13156   }
13157   return BackedgeCount;
13158 }
13159 
13160 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
13161   if (Preds.implies(&Pred))
13162     return;
13163   Preds.add(&Pred);
13164   updateGeneration();
13165 }
13166 
13167 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const {
13168   return Preds;
13169 }
13170 
13171 void PredicatedScalarEvolution::updateGeneration() {
13172   // If the generation number wrapped recompute everything.
13173   if (++Generation == 0) {
13174     for (auto &II : RewriteMap) {
13175       const SCEV *Rewritten = II.second.second;
13176       II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)};
13177     }
13178   }
13179 }
13180 
13181 void PredicatedScalarEvolution::setNoOverflow(
13182     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
13183   const SCEV *Expr = getSCEV(V);
13184   const auto *AR = cast<SCEVAddRecExpr>(Expr);
13185 
13186   auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE);
13187 
13188   // Clear the statically implied flags.
13189   Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags);
13190   addPredicate(*SE.getWrapPredicate(AR, Flags));
13191 
13192   auto II = FlagsMap.insert({V, Flags});
13193   if (!II.second)
13194     II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second);
13195 }
13196 
13197 bool PredicatedScalarEvolution::hasNoOverflow(
13198     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
13199   const SCEV *Expr = getSCEV(V);
13200   const auto *AR = cast<SCEVAddRecExpr>(Expr);
13201 
13202   Flags = SCEVWrapPredicate::clearFlags(
13203       Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
13204 
13205   auto II = FlagsMap.find(V);
13206 
13207   if (II != FlagsMap.end())
13208     Flags = SCEVWrapPredicate::clearFlags(Flags, II->second);
13209 
13210   return Flags == SCEVWrapPredicate::IncrementAnyWrap;
13211 }
13212 
13213 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) {
13214   const SCEV *Expr = this->getSCEV(V);
13215   SmallPtrSet<const SCEVPredicate *, 4> NewPreds;
13216   auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
13217 
13218   if (!New)
13219     return nullptr;
13220 
13221   for (auto *P : NewPreds)
13222     Preds.add(P);
13223 
13224   updateGeneration();
13225   RewriteMap[SE.getSCEV(V)] = {Generation, New};
13226   return New;
13227 }
13228 
13229 PredicatedScalarEvolution::PredicatedScalarEvolution(
13230     const PredicatedScalarEvolution &Init)
13231     : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds),
13232       Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
13233   for (auto I : Init.FlagsMap)
13234     FlagsMap.insert(I);
13235 }
13236 
13237 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const {
13238   // For each block.
13239   for (auto *BB : L.getBlocks())
13240     for (auto &I : *BB) {
13241       if (!SE.isSCEVable(I.getType()))
13242         continue;
13243 
13244       auto *Expr = SE.getSCEV(&I);
13245       auto II = RewriteMap.find(Expr);
13246 
13247       if (II == RewriteMap.end())
13248         continue;
13249 
13250       // Don't print things that are not interesting.
13251       if (II->second.second == Expr)
13252         continue;
13253 
13254       OS.indent(Depth) << "[PSE]" << I << ":\n";
13255       OS.indent(Depth + 2) << *Expr << "\n";
13256       OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
13257     }
13258 }
13259 
13260 // Match the mathematical pattern A - (A / B) * B, where A and B can be
13261 // arbitrary expressions. Also match zext (trunc A to iB) to iY, which is used
13262 // for URem with constant power-of-2 second operands.
13263 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is
13264 // 4, A / B becomes X / 8).
13265 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS,
13266                                 const SCEV *&RHS) {
13267   // Try to match 'zext (trunc A to iB) to iY', which is used
13268   // for URem with constant power-of-2 second operands. Make sure the size of
13269   // the operand A matches the size of the whole expressions.
13270   if (const auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(Expr))
13271     if (const auto *Trunc = dyn_cast<SCEVTruncateExpr>(ZExt->getOperand(0))) {
13272       LHS = Trunc->getOperand();
13273       // Bail out if the type of the LHS is larger than the type of the
13274       // expression for now.
13275       if (getTypeSizeInBits(LHS->getType()) >
13276           getTypeSizeInBits(Expr->getType()))
13277         return false;
13278       if (LHS->getType() != Expr->getType())
13279         LHS = getZeroExtendExpr(LHS, Expr->getType());
13280       RHS = getConstant(APInt(getTypeSizeInBits(Expr->getType()), 1)
13281                         << getTypeSizeInBits(Trunc->getType()));
13282       return true;
13283     }
13284   const auto *Add = dyn_cast<SCEVAddExpr>(Expr);
13285   if (Add == nullptr || Add->getNumOperands() != 2)
13286     return false;
13287 
13288   const SCEV *A = Add->getOperand(1);
13289   const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0));
13290 
13291   if (Mul == nullptr)
13292     return false;
13293 
13294   const auto MatchURemWithDivisor = [&](const SCEV *B) {
13295     // (SomeExpr + (-(SomeExpr / B) * B)).
13296     if (Expr == getURemExpr(A, B)) {
13297       LHS = A;
13298       RHS = B;
13299       return true;
13300     }
13301     return false;
13302   };
13303 
13304   // (SomeExpr + (-1 * (SomeExpr / B) * B)).
13305   if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0)))
13306     return MatchURemWithDivisor(Mul->getOperand(1)) ||
13307            MatchURemWithDivisor(Mul->getOperand(2));
13308 
13309   // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)).
13310   if (Mul->getNumOperands() == 2)
13311     return MatchURemWithDivisor(Mul->getOperand(1)) ||
13312            MatchURemWithDivisor(Mul->getOperand(0)) ||
13313            MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) ||
13314            MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0)));
13315   return false;
13316 }
13317 
13318 const SCEV *
13319 ScalarEvolution::computeSymbolicMaxBackedgeTakenCount(const Loop *L) {
13320   SmallVector<BasicBlock*, 16> ExitingBlocks;
13321   L->getExitingBlocks(ExitingBlocks);
13322 
13323   // Form an expression for the maximum exit count possible for this loop. We
13324   // merge the max and exact information to approximate a version of
13325   // getConstantMaxBackedgeTakenCount which isn't restricted to just constants.
13326   SmallVector<const SCEV*, 4> ExitCounts;
13327   for (BasicBlock *ExitingBB : ExitingBlocks) {
13328     const SCEV *ExitCount = getExitCount(L, ExitingBB);
13329     if (isa<SCEVCouldNotCompute>(ExitCount))
13330       ExitCount = getExitCount(L, ExitingBB,
13331                                   ScalarEvolution::ConstantMaximum);
13332     if (!isa<SCEVCouldNotCompute>(ExitCount)) {
13333       assert(DT.dominates(ExitingBB, L->getLoopLatch()) &&
13334              "We should only have known counts for exiting blocks that "
13335              "dominate latch!");
13336       ExitCounts.push_back(ExitCount);
13337     }
13338   }
13339   if (ExitCounts.empty())
13340     return getCouldNotCompute();
13341   return getUMinFromMismatchedTypes(ExitCounts);
13342 }
13343 
13344 /// This rewriter is similar to SCEVParameterRewriter (it replaces SCEVUnknown
13345 /// components following the Map (Value -> SCEV)), but skips AddRecExpr because
13346 /// we cannot guarantee that the replacement is loop invariant in the loop of
13347 /// the AddRec.
13348 class SCEVLoopGuardRewriter : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> {
13349   ValueToSCEVMapTy &Map;
13350 
13351 public:
13352   SCEVLoopGuardRewriter(ScalarEvolution &SE, ValueToSCEVMapTy &M)
13353       : SCEVRewriteVisitor(SE), Map(M) {}
13354 
13355   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; }
13356 
13357   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
13358     auto I = Map.find(Expr->getValue());
13359     if (I == Map.end())
13360       return Expr;
13361     return I->second;
13362   }
13363 };
13364 
13365 const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) {
13366   auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS,
13367                               const SCEV *RHS, ValueToSCEVMapTy &RewriteMap) {
13368     // If we have LHS == 0, check if LHS is computing a property of some unknown
13369     // SCEV %v which we can rewrite %v to express explicitly.
13370     const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS);
13371     if (Predicate == CmpInst::ICMP_EQ && RHSC &&
13372         RHSC->getValue()->isNullValue()) {
13373       // If LHS is A % B, i.e. A % B == 0, rewrite A to (A /u B) * B to
13374       // explicitly express that.
13375       const SCEV *URemLHS = nullptr;
13376       const SCEV *URemRHS = nullptr;
13377       if (matchURem(LHS, URemLHS, URemRHS)) {
13378         if (const SCEVUnknown *LHSUnknown = dyn_cast<SCEVUnknown>(URemLHS)) {
13379           Value *V = LHSUnknown->getValue();
13380           auto Multiple =
13381               getMulExpr(getUDivExpr(URemLHS, URemRHS), URemRHS,
13382                          (SCEV::NoWrapFlags)(SCEV::FlagNUW | SCEV::FlagNSW));
13383           RewriteMap[V] = Multiple;
13384           return;
13385         }
13386       }
13387     }
13388 
13389     if (!isa<SCEVUnknown>(LHS)) {
13390       std::swap(LHS, RHS);
13391       Predicate = CmpInst::getSwappedPredicate(Predicate);
13392     }
13393 
13394     // For now, limit to conditions that provide information about unknown
13395     // expressions.
13396     auto *LHSUnknown = dyn_cast<SCEVUnknown>(LHS);
13397     if (!LHSUnknown)
13398       return;
13399 
13400     // TODO: use information from more predicates.
13401     switch (Predicate) {
13402     case CmpInst::ICMP_ULT: {
13403       if (!containsAddRecurrence(RHS)) {
13404         const SCEV *Base = LHS;
13405         auto I = RewriteMap.find(LHSUnknown->getValue());
13406         if (I != RewriteMap.end())
13407           Base = I->second;
13408 
13409         RewriteMap[LHSUnknown->getValue()] =
13410             getUMinExpr(Base, getMinusSCEV(RHS, getOne(RHS->getType())));
13411       }
13412       break;
13413     }
13414     case CmpInst::ICMP_ULE: {
13415       if (!containsAddRecurrence(RHS)) {
13416         const SCEV *Base = LHS;
13417         auto I = RewriteMap.find(LHSUnknown->getValue());
13418         if (I != RewriteMap.end())
13419           Base = I->second;
13420         RewriteMap[LHSUnknown->getValue()] = getUMinExpr(Base, RHS);
13421       }
13422       break;
13423     }
13424     case CmpInst::ICMP_EQ:
13425       if (isa<SCEVConstant>(RHS))
13426         RewriteMap[LHSUnknown->getValue()] = RHS;
13427       break;
13428     case CmpInst::ICMP_NE:
13429       if (isa<SCEVConstant>(RHS) &&
13430           cast<SCEVConstant>(RHS)->getValue()->isNullValue())
13431         RewriteMap[LHSUnknown->getValue()] =
13432             getUMaxExpr(LHS, getOne(RHS->getType()));
13433       break;
13434     default:
13435       break;
13436     }
13437   };
13438   // Starting at the loop predecessor, climb up the predecessor chain, as long
13439   // as there are predecessors that can be found that have unique successors
13440   // leading to the original header.
13441   // TODO: share this logic with isLoopEntryGuardedByCond.
13442   ValueToSCEVMapTy RewriteMap;
13443   for (std::pair<const BasicBlock *, const BasicBlock *> Pair(
13444            L->getLoopPredecessor(), L->getHeader());
13445        Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
13446 
13447     const BranchInst *LoopEntryPredicate =
13448         dyn_cast<BranchInst>(Pair.first->getTerminator());
13449     if (!LoopEntryPredicate || LoopEntryPredicate->isUnconditional())
13450       continue;
13451 
13452     // TODO: use information from more complex conditions, e.g. AND expressions.
13453     auto *Cmp = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
13454     if (!Cmp)
13455       continue;
13456 
13457     auto Predicate = Cmp->getPredicate();
13458     if (LoopEntryPredicate->getSuccessor(1) == Pair.second)
13459       Predicate = CmpInst::getInversePredicate(Predicate);
13460     CollectCondition(Predicate, getSCEV(Cmp->getOperand(0)),
13461                      getSCEV(Cmp->getOperand(1)), RewriteMap);
13462   }
13463 
13464   // Also collect information from assumptions dominating the loop.
13465   for (auto &AssumeVH : AC.assumptions()) {
13466     if (!AssumeVH)
13467       continue;
13468     auto *AssumeI = cast<CallInst>(AssumeVH);
13469     auto *Cmp = dyn_cast<ICmpInst>(AssumeI->getOperand(0));
13470     if (!Cmp || !DT.dominates(AssumeI, L->getHeader()))
13471       continue;
13472     CollectCondition(Cmp->getPredicate(), getSCEV(Cmp->getOperand(0)),
13473                      getSCEV(Cmp->getOperand(1)), RewriteMap);
13474   }
13475 
13476   if (RewriteMap.empty())
13477     return Expr;
13478   SCEVLoopGuardRewriter Rewriter(*this, RewriteMap);
13479   return Rewriter.visit(Expr);
13480 }
13481