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/ScalarEvolutionExpressions.h"
83 #include "llvm/Analysis/TargetLibraryInfo.h"
84 #include "llvm/Analysis/ValueTracking.h"
85 #include "llvm/Config/llvm-config.h"
86 #include "llvm/IR/Argument.h"
87 #include "llvm/IR/BasicBlock.h"
88 #include "llvm/IR/CFG.h"
89 #include "llvm/IR/CallSite.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 
139 #define DEBUG_TYPE "scalar-evolution"
140 
141 STATISTIC(NumArrayLenItCounts,
142           "Number of trip counts computed with array length");
143 STATISTIC(NumTripCountsComputed,
144           "Number of loops with predictable loop counts");
145 STATISTIC(NumTripCountsNotComputed,
146           "Number of loops without predictable loop counts");
147 STATISTIC(NumBruteForceTripCountsComputed,
148           "Number of loops with trip counts computed by force");
149 
150 static cl::opt<unsigned>
151 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
152                         cl::ZeroOrMore,
153                         cl::desc("Maximum number of iterations SCEV will "
154                                  "symbolically execute a constant "
155                                  "derived loop"),
156                         cl::init(100));
157 
158 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean.
159 static cl::opt<bool> VerifySCEV(
160     "verify-scev", cl::Hidden,
161     cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
162 static cl::opt<bool> VerifySCEVStrict(
163     "verify-scev-strict", cl::Hidden,
164     cl::desc("Enable stricter verification with -verify-scev is passed"));
165 static cl::opt<bool>
166     VerifySCEVMap("verify-scev-maps", cl::Hidden,
167                   cl::desc("Verify no dangling value in ScalarEvolution's "
168                            "ExprValueMap (slow)"));
169 
170 static cl::opt<bool> VerifyIR(
171     "scev-verify-ir", cl::Hidden,
172     cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"),
173     cl::init(false));
174 
175 static cl::opt<unsigned> MulOpsInlineThreshold(
176     "scev-mulops-inline-threshold", cl::Hidden,
177     cl::desc("Threshold for inlining multiplication operands into a SCEV"),
178     cl::init(32));
179 
180 static cl::opt<unsigned> AddOpsInlineThreshold(
181     "scev-addops-inline-threshold", cl::Hidden,
182     cl::desc("Threshold for inlining addition operands into a SCEV"),
183     cl::init(500));
184 
185 static cl::opt<unsigned> MaxSCEVCompareDepth(
186     "scalar-evolution-max-scev-compare-depth", cl::Hidden,
187     cl::desc("Maximum depth of recursive SCEV complexity comparisons"),
188     cl::init(32));
189 
190 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth(
191     "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden,
192     cl::desc("Maximum depth of recursive SCEV operations implication analysis"),
193     cl::init(2));
194 
195 static cl::opt<unsigned> MaxValueCompareDepth(
196     "scalar-evolution-max-value-compare-depth", cl::Hidden,
197     cl::desc("Maximum depth of recursive value complexity comparisons"),
198     cl::init(2));
199 
200 static cl::opt<unsigned>
201     MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden,
202                   cl::desc("Maximum depth of recursive arithmetics"),
203                   cl::init(32));
204 
205 static cl::opt<unsigned> MaxConstantEvolvingDepth(
206     "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
207     cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
208 
209 static cl::opt<unsigned>
210     MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden,
211                  cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"),
212                  cl::init(8));
213 
214 static cl::opt<unsigned>
215     MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden,
216                   cl::desc("Max coefficients in AddRec during evolving"),
217                   cl::init(8));
218 
219 static cl::opt<unsigned>
220     HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden,
221                   cl::desc("Size of the expression which is considered huge"),
222                   cl::init(4096));
223 
224 static cl::opt<bool>
225 ClassifyExpressions("scalar-evolution-classify-expressions",
226     cl::Hidden, cl::init(true),
227     cl::desc("When printing analysis, include information on every instruction"));
228 
229 
230 //===----------------------------------------------------------------------===//
231 //                           SCEV class definitions
232 //===----------------------------------------------------------------------===//
233 
234 //===----------------------------------------------------------------------===//
235 // Implementation of the SCEV class.
236 //
237 
238 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
239 LLVM_DUMP_METHOD void SCEV::dump() const {
240   print(dbgs());
241   dbgs() << '\n';
242 }
243 #endif
244 
245 void SCEV::print(raw_ostream &OS) const {
246   switch (static_cast<SCEVTypes>(getSCEVType())) {
247   case scConstant:
248     cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
249     return;
250   case scTruncate: {
251     const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
252     const SCEV *Op = Trunc->getOperand();
253     OS << "(trunc " << *Op->getType() << " " << *Op << " to "
254        << *Trunc->getType() << ")";
255     return;
256   }
257   case scZeroExtend: {
258     const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
259     const SCEV *Op = ZExt->getOperand();
260     OS << "(zext " << *Op->getType() << " " << *Op << " to "
261        << *ZExt->getType() << ")";
262     return;
263   }
264   case scSignExtend: {
265     const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
266     const SCEV *Op = SExt->getOperand();
267     OS << "(sext " << *Op->getType() << " " << *Op << " to "
268        << *SExt->getType() << ")";
269     return;
270   }
271   case scAddRecExpr: {
272     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
273     OS << "{" << *AR->getOperand(0);
274     for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
275       OS << ",+," << *AR->getOperand(i);
276     OS << "}<";
277     if (AR->hasNoUnsignedWrap())
278       OS << "nuw><";
279     if (AR->hasNoSignedWrap())
280       OS << "nsw><";
281     if (AR->hasNoSelfWrap() &&
282         !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
283       OS << "nw><";
284     AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
285     OS << ">";
286     return;
287   }
288   case scAddExpr:
289   case scMulExpr:
290   case scUMaxExpr:
291   case scSMaxExpr:
292   case scUMinExpr:
293   case scSMinExpr: {
294     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
295     const char *OpStr = nullptr;
296     switch (NAry->getSCEVType()) {
297     case scAddExpr: OpStr = " + "; break;
298     case scMulExpr: OpStr = " * "; break;
299     case scUMaxExpr: OpStr = " umax "; break;
300     case scSMaxExpr: OpStr = " smax "; break;
301     case scUMinExpr:
302       OpStr = " umin ";
303       break;
304     case scSMinExpr:
305       OpStr = " smin ";
306       break;
307     }
308     OS << "(";
309     for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
310          I != E; ++I) {
311       OS << **I;
312       if (std::next(I) != E)
313         OS << OpStr;
314     }
315     OS << ")";
316     switch (NAry->getSCEVType()) {
317     case scAddExpr:
318     case scMulExpr:
319       if (NAry->hasNoUnsignedWrap())
320         OS << "<nuw>";
321       if (NAry->hasNoSignedWrap())
322         OS << "<nsw>";
323     }
324     return;
325   }
326   case scUDivExpr: {
327     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
328     OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
329     return;
330   }
331   case scUnknown: {
332     const SCEVUnknown *U = cast<SCEVUnknown>(this);
333     Type *AllocTy;
334     if (U->isSizeOf(AllocTy)) {
335       OS << "sizeof(" << *AllocTy << ")";
336       return;
337     }
338     if (U->isAlignOf(AllocTy)) {
339       OS << "alignof(" << *AllocTy << ")";
340       return;
341     }
342 
343     Type *CTy;
344     Constant *FieldNo;
345     if (U->isOffsetOf(CTy, FieldNo)) {
346       OS << "offsetof(" << *CTy << ", ";
347       FieldNo->printAsOperand(OS, false);
348       OS << ")";
349       return;
350     }
351 
352     // Otherwise just print it normally.
353     U->getValue()->printAsOperand(OS, false);
354     return;
355   }
356   case scCouldNotCompute:
357     OS << "***COULDNOTCOMPUTE***";
358     return;
359   }
360   llvm_unreachable("Unknown SCEV kind!");
361 }
362 
363 Type *SCEV::getType() const {
364   switch (static_cast<SCEVTypes>(getSCEVType())) {
365   case scConstant:
366     return cast<SCEVConstant>(this)->getType();
367   case scTruncate:
368   case scZeroExtend:
369   case scSignExtend:
370     return cast<SCEVCastExpr>(this)->getType();
371   case scAddRecExpr:
372   case scMulExpr:
373   case scUMaxExpr:
374   case scSMaxExpr:
375   case scUMinExpr:
376   case scSMinExpr:
377     return cast<SCEVNAryExpr>(this)->getType();
378   case scAddExpr:
379     return cast<SCEVAddExpr>(this)->getType();
380   case scUDivExpr:
381     return cast<SCEVUDivExpr>(this)->getType();
382   case scUnknown:
383     return cast<SCEVUnknown>(this)->getType();
384   case scCouldNotCompute:
385     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
386   }
387   llvm_unreachable("Unknown SCEV kind!");
388 }
389 
390 bool SCEV::isZero() const {
391   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
392     return SC->getValue()->isZero();
393   return false;
394 }
395 
396 bool SCEV::isOne() const {
397   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
398     return SC->getValue()->isOne();
399   return false;
400 }
401 
402 bool SCEV::isAllOnesValue() const {
403   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
404     return SC->getValue()->isMinusOne();
405   return false;
406 }
407 
408 bool SCEV::isNonConstantNegative() const {
409   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
410   if (!Mul) return false;
411 
412   // If there is a constant factor, it will be first.
413   const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
414   if (!SC) return false;
415 
416   // Return true if the value is negative, this matches things like (-42 * V).
417   return SC->getAPInt().isNegative();
418 }
419 
420 SCEVCouldNotCompute::SCEVCouldNotCompute() :
421   SCEV(FoldingSetNodeIDRef(), scCouldNotCompute, 0) {}
422 
423 bool SCEVCouldNotCompute::classof(const SCEV *S) {
424   return S->getSCEVType() == scCouldNotCompute;
425 }
426 
427 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
428   FoldingSetNodeID ID;
429   ID.AddInteger(scConstant);
430   ID.AddPointer(V);
431   void *IP = nullptr;
432   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
433   SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
434   UniqueSCEVs.InsertNode(S, IP);
435   return S;
436 }
437 
438 const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
439   return getConstant(ConstantInt::get(getContext(), Val));
440 }
441 
442 const SCEV *
443 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
444   IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
445   return getConstant(ConstantInt::get(ITy, V, isSigned));
446 }
447 
448 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
449                            unsigned SCEVTy, const SCEV *op, Type *ty)
450   : SCEV(ID, SCEVTy, computeExpressionSize(op)), Op(op), Ty(ty) {}
451 
452 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
453                                    const SCEV *op, Type *ty)
454   : SCEVCastExpr(ID, scTruncate, op, ty) {
455   assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
456          "Cannot truncate non-integer value!");
457 }
458 
459 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
460                                        const SCEV *op, Type *ty)
461   : SCEVCastExpr(ID, scZeroExtend, op, ty) {
462   assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
463          "Cannot zero extend non-integer value!");
464 }
465 
466 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
467                                        const SCEV *op, Type *ty)
468   : SCEVCastExpr(ID, scSignExtend, op, ty) {
469   assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
470          "Cannot sign extend non-integer value!");
471 }
472 
473 void SCEVUnknown::deleted() {
474   // Clear this SCEVUnknown from various maps.
475   SE->forgetMemoizedResults(this);
476 
477   // Remove this SCEVUnknown from the uniquing map.
478   SE->UniqueSCEVs.RemoveNode(this);
479 
480   // Release the value.
481   setValPtr(nullptr);
482 }
483 
484 void SCEVUnknown::allUsesReplacedWith(Value *New) {
485   // Remove this SCEVUnknown from the uniquing map.
486   SE->UniqueSCEVs.RemoveNode(this);
487 
488   // Update this SCEVUnknown to point to the new value. This is needed
489   // because there may still be outstanding SCEVs which still point to
490   // this SCEVUnknown.
491   setValPtr(New);
492 }
493 
494 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
495   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
496     if (VCE->getOpcode() == Instruction::PtrToInt)
497       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
498         if (CE->getOpcode() == Instruction::GetElementPtr &&
499             CE->getOperand(0)->isNullValue() &&
500             CE->getNumOperands() == 2)
501           if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
502             if (CI->isOne()) {
503               AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
504                                  ->getElementType();
505               return true;
506             }
507 
508   return false;
509 }
510 
511 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
512   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
513     if (VCE->getOpcode() == Instruction::PtrToInt)
514       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
515         if (CE->getOpcode() == Instruction::GetElementPtr &&
516             CE->getOperand(0)->isNullValue()) {
517           Type *Ty =
518             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
519           if (StructType *STy = dyn_cast<StructType>(Ty))
520             if (!STy->isPacked() &&
521                 CE->getNumOperands() == 3 &&
522                 CE->getOperand(1)->isNullValue()) {
523               if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
524                 if (CI->isOne() &&
525                     STy->getNumElements() == 2 &&
526                     STy->getElementType(0)->isIntegerTy(1)) {
527                   AllocTy = STy->getElementType(1);
528                   return true;
529                 }
530             }
531         }
532 
533   return false;
534 }
535 
536 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
537   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
538     if (VCE->getOpcode() == Instruction::PtrToInt)
539       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
540         if (CE->getOpcode() == Instruction::GetElementPtr &&
541             CE->getNumOperands() == 3 &&
542             CE->getOperand(0)->isNullValue() &&
543             CE->getOperand(1)->isNullValue()) {
544           Type *Ty =
545             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
546           // Ignore vector types here so that ScalarEvolutionExpander doesn't
547           // emit getelementptrs that index into vectors.
548           if (Ty->isStructTy() || Ty->isArrayTy()) {
549             CTy = Ty;
550             FieldNo = CE->getOperand(2);
551             return true;
552           }
553         }
554 
555   return false;
556 }
557 
558 //===----------------------------------------------------------------------===//
559 //                               SCEV Utilities
560 //===----------------------------------------------------------------------===//
561 
562 /// Compare the two values \p LV and \p RV in terms of their "complexity" where
563 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order
564 /// operands in SCEV expressions.  \p EqCache is a set of pairs of values that
565 /// have been previously deemed to be "equally complex" by this routine.  It is
566 /// intended to avoid exponential time complexity in cases like:
567 ///
568 ///   %a = f(%x, %y)
569 ///   %b = f(%a, %a)
570 ///   %c = f(%b, %b)
571 ///
572 ///   %d = f(%x, %y)
573 ///   %e = f(%d, %d)
574 ///   %f = f(%e, %e)
575 ///
576 ///   CompareValueComplexity(%f, %c)
577 ///
578 /// Since we do not continue running this routine on expression trees once we
579 /// have seen unequal values, there is no need to track them in the cache.
580 static int
581 CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue,
582                        const LoopInfo *const LI, Value *LV, Value *RV,
583                        unsigned Depth) {
584   if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV))
585     return 0;
586 
587   // Order pointer values after integer values. This helps SCEVExpander form
588   // GEPs.
589   bool LIsPointer = LV->getType()->isPointerTy(),
590        RIsPointer = RV->getType()->isPointerTy();
591   if (LIsPointer != RIsPointer)
592     return (int)LIsPointer - (int)RIsPointer;
593 
594   // Compare getValueID values.
595   unsigned LID = LV->getValueID(), RID = RV->getValueID();
596   if (LID != RID)
597     return (int)LID - (int)RID;
598 
599   // Sort arguments by their position.
600   if (const auto *LA = dyn_cast<Argument>(LV)) {
601     const auto *RA = cast<Argument>(RV);
602     unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
603     return (int)LArgNo - (int)RArgNo;
604   }
605 
606   if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
607     const auto *RGV = cast<GlobalValue>(RV);
608 
609     const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
610       auto LT = GV->getLinkage();
611       return !(GlobalValue::isPrivateLinkage(LT) ||
612                GlobalValue::isInternalLinkage(LT));
613     };
614 
615     // Use the names to distinguish the two values, but only if the
616     // names are semantically important.
617     if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
618       return LGV->getName().compare(RGV->getName());
619   }
620 
621   // For instructions, compare their loop depth, and their operand count.  This
622   // is pretty loose.
623   if (const auto *LInst = dyn_cast<Instruction>(LV)) {
624     const auto *RInst = cast<Instruction>(RV);
625 
626     // Compare loop depths.
627     const BasicBlock *LParent = LInst->getParent(),
628                      *RParent = RInst->getParent();
629     if (LParent != RParent) {
630       unsigned LDepth = LI->getLoopDepth(LParent),
631                RDepth = LI->getLoopDepth(RParent);
632       if (LDepth != RDepth)
633         return (int)LDepth - (int)RDepth;
634     }
635 
636     // Compare the number of operands.
637     unsigned LNumOps = LInst->getNumOperands(),
638              RNumOps = RInst->getNumOperands();
639     if (LNumOps != RNumOps)
640       return (int)LNumOps - (int)RNumOps;
641 
642     for (unsigned Idx : seq(0u, LNumOps)) {
643       int Result =
644           CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx),
645                                  RInst->getOperand(Idx), Depth + 1);
646       if (Result != 0)
647         return Result;
648     }
649   }
650 
651   EqCacheValue.unionSets(LV, RV);
652   return 0;
653 }
654 
655 // Return negative, zero, or positive, if LHS is less than, equal to, or greater
656 // than RHS, respectively. A three-way result allows recursive comparisons to be
657 // more efficient.
658 static int CompareSCEVComplexity(
659     EquivalenceClasses<const SCEV *> &EqCacheSCEV,
660     EquivalenceClasses<const Value *> &EqCacheValue,
661     const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS,
662     DominatorTree &DT, unsigned Depth = 0) {
663   // Fast-path: SCEVs are uniqued so we can do a quick equality check.
664   if (LHS == RHS)
665     return 0;
666 
667   // Primarily, sort the SCEVs by their getSCEVType().
668   unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
669   if (LType != RType)
670     return (int)LType - (int)RType;
671 
672   if (Depth > MaxSCEVCompareDepth || EqCacheSCEV.isEquivalent(LHS, RHS))
673     return 0;
674   // Aside from the getSCEVType() ordering, the particular ordering
675   // isn't very important except that it's beneficial to be consistent,
676   // so that (a + b) and (b + a) don't end up as different expressions.
677   switch (static_cast<SCEVTypes>(LType)) {
678   case scUnknown: {
679     const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
680     const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
681 
682     int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(),
683                                    RU->getValue(), Depth + 1);
684     if (X == 0)
685       EqCacheSCEV.unionSets(LHS, RHS);
686     return X;
687   }
688 
689   case scConstant: {
690     const SCEVConstant *LC = cast<SCEVConstant>(LHS);
691     const SCEVConstant *RC = cast<SCEVConstant>(RHS);
692 
693     // Compare constant values.
694     const APInt &LA = LC->getAPInt();
695     const APInt &RA = RC->getAPInt();
696     unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
697     if (LBitWidth != RBitWidth)
698       return (int)LBitWidth - (int)RBitWidth;
699     return LA.ult(RA) ? -1 : 1;
700   }
701 
702   case scAddRecExpr: {
703     const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
704     const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
705 
706     // There is always a dominance between two recs that are used by one SCEV,
707     // so we can safely sort recs by loop header dominance. We require such
708     // order in getAddExpr.
709     const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
710     if (LLoop != RLoop) {
711       const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
712       assert(LHead != RHead && "Two loops share the same header?");
713       if (DT.dominates(LHead, RHead))
714         return 1;
715       else
716         assert(DT.dominates(RHead, LHead) &&
717                "No dominance between recurrences used by one SCEV?");
718       return -1;
719     }
720 
721     // Addrec complexity grows with operand count.
722     unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
723     if (LNumOps != RNumOps)
724       return (int)LNumOps - (int)RNumOps;
725 
726     // Lexicographically compare.
727     for (unsigned i = 0; i != LNumOps; ++i) {
728       int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
729                                     LA->getOperand(i), RA->getOperand(i), DT,
730                                     Depth + 1);
731       if (X != 0)
732         return X;
733     }
734     EqCacheSCEV.unionSets(LHS, RHS);
735     return 0;
736   }
737 
738   case scAddExpr:
739   case scMulExpr:
740   case scSMaxExpr:
741   case scUMaxExpr:
742   case scSMinExpr:
743   case scUMinExpr: {
744     const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
745     const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
746 
747     // Lexicographically compare n-ary expressions.
748     unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
749     if (LNumOps != RNumOps)
750       return (int)LNumOps - (int)RNumOps;
751 
752     for (unsigned i = 0; i != LNumOps; ++i) {
753       int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
754                                     LC->getOperand(i), RC->getOperand(i), DT,
755                                     Depth + 1);
756       if (X != 0)
757         return X;
758     }
759     EqCacheSCEV.unionSets(LHS, RHS);
760     return 0;
761   }
762 
763   case scUDivExpr: {
764     const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
765     const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
766 
767     // Lexicographically compare udiv expressions.
768     int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(),
769                                   RC->getLHS(), DT, Depth + 1);
770     if (X != 0)
771       return X;
772     X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(),
773                               RC->getRHS(), DT, Depth + 1);
774     if (X == 0)
775       EqCacheSCEV.unionSets(LHS, RHS);
776     return X;
777   }
778 
779   case scTruncate:
780   case scZeroExtend:
781   case scSignExtend: {
782     const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
783     const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
784 
785     // Compare cast expressions by operand.
786     int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
787                                   LC->getOperand(), RC->getOperand(), DT,
788                                   Depth + 1);
789     if (X == 0)
790       EqCacheSCEV.unionSets(LHS, RHS);
791     return X;
792   }
793 
794   case scCouldNotCompute:
795     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
796   }
797   llvm_unreachable("Unknown SCEV kind!");
798 }
799 
800 /// Given a list of SCEV objects, order them by their complexity, and group
801 /// objects of the same complexity together by value.  When this routine is
802 /// finished, we know that any duplicates in the vector are consecutive and that
803 /// complexity is monotonically increasing.
804 ///
805 /// Note that we go take special precautions to ensure that we get deterministic
806 /// results from this routine.  In other words, we don't want the results of
807 /// this to depend on where the addresses of various SCEV objects happened to
808 /// land in memory.
809 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
810                               LoopInfo *LI, DominatorTree &DT) {
811   if (Ops.size() < 2) return;  // Noop
812 
813   EquivalenceClasses<const SCEV *> EqCacheSCEV;
814   EquivalenceClasses<const Value *> EqCacheValue;
815   if (Ops.size() == 2) {
816     // This is the common case, which also happens to be trivially simple.
817     // Special case it.
818     const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
819     if (CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, RHS, LHS, DT) < 0)
820       std::swap(LHS, RHS);
821     return;
822   }
823 
824   // Do the rough sort by complexity.
825   llvm::stable_sort(Ops, [&](const SCEV *LHS, const SCEV *RHS) {
826     return CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LHS, RHS, DT) <
827            0;
828   });
829 
830   // Now that we are sorted by complexity, group elements of the same
831   // complexity.  Note that this is, at worst, N^2, but the vector is likely to
832   // be extremely short in practice.  Note that we take this approach because we
833   // do not want to depend on the addresses of the objects we are grouping.
834   for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
835     const SCEV *S = Ops[i];
836     unsigned Complexity = S->getSCEVType();
837 
838     // If there are any objects of the same complexity and same value as this
839     // one, group them.
840     for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
841       if (Ops[j] == S) { // Found a duplicate.
842         // Move it to immediately after i'th element.
843         std::swap(Ops[i+1], Ops[j]);
844         ++i;   // no need to rescan it.
845         if (i == e-2) return;  // Done!
846       }
847     }
848   }
849 }
850 
851 // Returns the size of the SCEV S.
852 static inline int sizeOfSCEV(const SCEV *S) {
853   struct FindSCEVSize {
854     int Size = 0;
855 
856     FindSCEVSize() = default;
857 
858     bool follow(const SCEV *S) {
859       ++Size;
860       // Keep looking at all operands of S.
861       return true;
862     }
863 
864     bool isDone() const {
865       return false;
866     }
867   };
868 
869   FindSCEVSize F;
870   SCEVTraversal<FindSCEVSize> ST(F);
871   ST.visitAll(S);
872   return F.Size;
873 }
874 
875 /// Returns true if the subtree of \p S contains at least HugeExprThreshold
876 /// nodes.
877 static bool isHugeExpression(const SCEV *S) {
878   return S->getExpressionSize() >= HugeExprThreshold;
879 }
880 
881 /// Returns true of \p Ops contains a huge SCEV (see definition above).
882 static bool hasHugeExpression(ArrayRef<const SCEV *> Ops) {
883   return any_of(Ops, isHugeExpression);
884 }
885 
886 namespace {
887 
888 struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> {
889 public:
890   // Computes the Quotient and Remainder of the division of Numerator by
891   // Denominator.
892   static void divide(ScalarEvolution &SE, const SCEV *Numerator,
893                      const SCEV *Denominator, const SCEV **Quotient,
894                      const SCEV **Remainder) {
895     assert(Numerator && Denominator && "Uninitialized SCEV");
896 
897     SCEVDivision D(SE, Numerator, Denominator);
898 
899     // Check for the trivial case here to avoid having to check for it in the
900     // rest of the code.
901     if (Numerator == Denominator) {
902       *Quotient = D.One;
903       *Remainder = D.Zero;
904       return;
905     }
906 
907     if (Numerator->isZero()) {
908       *Quotient = D.Zero;
909       *Remainder = D.Zero;
910       return;
911     }
912 
913     // A simple case when N/1. The quotient is N.
914     if (Denominator->isOne()) {
915       *Quotient = Numerator;
916       *Remainder = D.Zero;
917       return;
918     }
919 
920     // Split the Denominator when it is a product.
921     if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) {
922       const SCEV *Q, *R;
923       *Quotient = Numerator;
924       for (const SCEV *Op : T->operands()) {
925         divide(SE, *Quotient, Op, &Q, &R);
926         *Quotient = Q;
927 
928         // Bail out when the Numerator is not divisible by one of the terms of
929         // the Denominator.
930         if (!R->isZero()) {
931           *Quotient = D.Zero;
932           *Remainder = Numerator;
933           return;
934         }
935       }
936       *Remainder = D.Zero;
937       return;
938     }
939 
940     D.visit(Numerator);
941     *Quotient = D.Quotient;
942     *Remainder = D.Remainder;
943   }
944 
945   // Except in the trivial case described above, we do not know how to divide
946   // Expr by Denominator for the following functions with empty implementation.
947   void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {}
948   void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {}
949   void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {}
950   void visitUDivExpr(const SCEVUDivExpr *Numerator) {}
951   void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {}
952   void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {}
953   void visitSMinExpr(const SCEVSMinExpr *Numerator) {}
954   void visitUMinExpr(const SCEVUMinExpr *Numerator) {}
955   void visitUnknown(const SCEVUnknown *Numerator) {}
956   void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {}
957 
958   void visitConstant(const SCEVConstant *Numerator) {
959     if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) {
960       APInt NumeratorVal = Numerator->getAPInt();
961       APInt DenominatorVal = D->getAPInt();
962       uint32_t NumeratorBW = NumeratorVal.getBitWidth();
963       uint32_t DenominatorBW = DenominatorVal.getBitWidth();
964 
965       if (NumeratorBW > DenominatorBW)
966         DenominatorVal = DenominatorVal.sext(NumeratorBW);
967       else if (NumeratorBW < DenominatorBW)
968         NumeratorVal = NumeratorVal.sext(DenominatorBW);
969 
970       APInt QuotientVal(NumeratorVal.getBitWidth(), 0);
971       APInt RemainderVal(NumeratorVal.getBitWidth(), 0);
972       APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal);
973       Quotient = SE.getConstant(QuotientVal);
974       Remainder = SE.getConstant(RemainderVal);
975       return;
976     }
977   }
978 
979   void visitAddRecExpr(const SCEVAddRecExpr *Numerator) {
980     const SCEV *StartQ, *StartR, *StepQ, *StepR;
981     if (!Numerator->isAffine())
982       return cannotDivide(Numerator);
983     divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR);
984     divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR);
985     // Bail out if the types do not match.
986     Type *Ty = Denominator->getType();
987     if (Ty != StartQ->getType() || Ty != StartR->getType() ||
988         Ty != StepQ->getType() || Ty != StepR->getType())
989       return cannotDivide(Numerator);
990     Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(),
991                                 Numerator->getNoWrapFlags());
992     Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(),
993                                  Numerator->getNoWrapFlags());
994   }
995 
996   void visitAddExpr(const SCEVAddExpr *Numerator) {
997     SmallVector<const SCEV *, 2> Qs, Rs;
998     Type *Ty = Denominator->getType();
999 
1000     for (const SCEV *Op : Numerator->operands()) {
1001       const SCEV *Q, *R;
1002       divide(SE, Op, Denominator, &Q, &R);
1003 
1004       // Bail out if types do not match.
1005       if (Ty != Q->getType() || Ty != R->getType())
1006         return cannotDivide(Numerator);
1007 
1008       Qs.push_back(Q);
1009       Rs.push_back(R);
1010     }
1011 
1012     if (Qs.size() == 1) {
1013       Quotient = Qs[0];
1014       Remainder = Rs[0];
1015       return;
1016     }
1017 
1018     Quotient = SE.getAddExpr(Qs);
1019     Remainder = SE.getAddExpr(Rs);
1020   }
1021 
1022   void visitMulExpr(const SCEVMulExpr *Numerator) {
1023     SmallVector<const SCEV *, 2> Qs;
1024     Type *Ty = Denominator->getType();
1025 
1026     bool FoundDenominatorTerm = false;
1027     for (const SCEV *Op : Numerator->operands()) {
1028       // Bail out if types do not match.
1029       if (Ty != Op->getType())
1030         return cannotDivide(Numerator);
1031 
1032       if (FoundDenominatorTerm) {
1033         Qs.push_back(Op);
1034         continue;
1035       }
1036 
1037       // Check whether Denominator divides one of the product operands.
1038       const SCEV *Q, *R;
1039       divide(SE, Op, Denominator, &Q, &R);
1040       if (!R->isZero()) {
1041         Qs.push_back(Op);
1042         continue;
1043       }
1044 
1045       // Bail out if types do not match.
1046       if (Ty != Q->getType())
1047         return cannotDivide(Numerator);
1048 
1049       FoundDenominatorTerm = true;
1050       Qs.push_back(Q);
1051     }
1052 
1053     if (FoundDenominatorTerm) {
1054       Remainder = Zero;
1055       if (Qs.size() == 1)
1056         Quotient = Qs[0];
1057       else
1058         Quotient = SE.getMulExpr(Qs);
1059       return;
1060     }
1061 
1062     if (!isa<SCEVUnknown>(Denominator))
1063       return cannotDivide(Numerator);
1064 
1065     // The Remainder is obtained by replacing Denominator by 0 in Numerator.
1066     ValueToValueMap RewriteMap;
1067     RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
1068         cast<SCEVConstant>(Zero)->getValue();
1069     Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
1070 
1071     if (Remainder->isZero()) {
1072       // The Quotient is obtained by replacing Denominator by 1 in Numerator.
1073       RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
1074           cast<SCEVConstant>(One)->getValue();
1075       Quotient =
1076           SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
1077       return;
1078     }
1079 
1080     // Quotient is (Numerator - Remainder) divided by Denominator.
1081     const SCEV *Q, *R;
1082     const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder);
1083     // This SCEV does not seem to simplify: fail the division here.
1084     if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator))
1085       return cannotDivide(Numerator);
1086     divide(SE, Diff, Denominator, &Q, &R);
1087     if (R != Zero)
1088       return cannotDivide(Numerator);
1089     Quotient = Q;
1090   }
1091 
1092 private:
1093   SCEVDivision(ScalarEvolution &S, const SCEV *Numerator,
1094                const SCEV *Denominator)
1095       : SE(S), Denominator(Denominator) {
1096     Zero = SE.getZero(Denominator->getType());
1097     One = SE.getOne(Denominator->getType());
1098 
1099     // We generally do not know how to divide Expr by Denominator. We
1100     // initialize the division to a "cannot divide" state to simplify the rest
1101     // of the code.
1102     cannotDivide(Numerator);
1103   }
1104 
1105   // Convenience function for giving up on the division. We set the quotient to
1106   // be equal to zero and the remainder to be equal to the numerator.
1107   void cannotDivide(const SCEV *Numerator) {
1108     Quotient = Zero;
1109     Remainder = Numerator;
1110   }
1111 
1112   ScalarEvolution &SE;
1113   const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One;
1114 };
1115 
1116 } // end anonymous namespace
1117 
1118 //===----------------------------------------------------------------------===//
1119 //                      Simple SCEV method implementations
1120 //===----------------------------------------------------------------------===//
1121 
1122 /// Compute BC(It, K).  The result has width W.  Assume, K > 0.
1123 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
1124                                        ScalarEvolution &SE,
1125                                        Type *ResultTy) {
1126   // Handle the simplest case efficiently.
1127   if (K == 1)
1128     return SE.getTruncateOrZeroExtend(It, ResultTy);
1129 
1130   // We are using the following formula for BC(It, K):
1131   //
1132   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
1133   //
1134   // Suppose, W is the bitwidth of the return value.  We must be prepared for
1135   // overflow.  Hence, we must assure that the result of our computation is
1136   // equal to the accurate one modulo 2^W.  Unfortunately, division isn't
1137   // safe in modular arithmetic.
1138   //
1139   // However, this code doesn't use exactly that formula; the formula it uses
1140   // is something like the following, where T is the number of factors of 2 in
1141   // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
1142   // exponentiation:
1143   //
1144   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
1145   //
1146   // This formula is trivially equivalent to the previous formula.  However,
1147   // this formula can be implemented much more efficiently.  The trick is that
1148   // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
1149   // arithmetic.  To do exact division in modular arithmetic, all we have
1150   // to do is multiply by the inverse.  Therefore, this step can be done at
1151   // width W.
1152   //
1153   // The next issue is how to safely do the division by 2^T.  The way this
1154   // is done is by doing the multiplication step at a width of at least W + T
1155   // bits.  This way, the bottom W+T bits of the product are accurate. Then,
1156   // when we perform the division by 2^T (which is equivalent to a right shift
1157   // by T), the bottom W bits are accurate.  Extra bits are okay; they'll get
1158   // truncated out after the division by 2^T.
1159   //
1160   // In comparison to just directly using the first formula, this technique
1161   // is much more efficient; using the first formula requires W * K bits,
1162   // but this formula less than W + K bits. Also, the first formula requires
1163   // a division step, whereas this formula only requires multiplies and shifts.
1164   //
1165   // It doesn't matter whether the subtraction step is done in the calculation
1166   // width or the input iteration count's width; if the subtraction overflows,
1167   // the result must be zero anyway.  We prefer here to do it in the width of
1168   // the induction variable because it helps a lot for certain cases; CodeGen
1169   // isn't smart enough to ignore the overflow, which leads to much less
1170   // efficient code if the width of the subtraction is wider than the native
1171   // register width.
1172   //
1173   // (It's possible to not widen at all by pulling out factors of 2 before
1174   // the multiplication; for example, K=2 can be calculated as
1175   // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
1176   // extra arithmetic, so it's not an obvious win, and it gets
1177   // much more complicated for K > 3.)
1178 
1179   // Protection from insane SCEVs; this bound is conservative,
1180   // but it probably doesn't matter.
1181   if (K > 1000)
1182     return SE.getCouldNotCompute();
1183 
1184   unsigned W = SE.getTypeSizeInBits(ResultTy);
1185 
1186   // Calculate K! / 2^T and T; we divide out the factors of two before
1187   // multiplying for calculating K! / 2^T to avoid overflow.
1188   // Other overflow doesn't matter because we only care about the bottom
1189   // W bits of the result.
1190   APInt OddFactorial(W, 1);
1191   unsigned T = 1;
1192   for (unsigned i = 3; i <= K; ++i) {
1193     APInt Mult(W, i);
1194     unsigned TwoFactors = Mult.countTrailingZeros();
1195     T += TwoFactors;
1196     Mult.lshrInPlace(TwoFactors);
1197     OddFactorial *= Mult;
1198   }
1199 
1200   // We need at least W + T bits for the multiplication step
1201   unsigned CalculationBits = W + T;
1202 
1203   // Calculate 2^T, at width T+W.
1204   APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
1205 
1206   // Calculate the multiplicative inverse of K! / 2^T;
1207   // this multiplication factor will perform the exact division by
1208   // K! / 2^T.
1209   APInt Mod = APInt::getSignedMinValue(W+1);
1210   APInt MultiplyFactor = OddFactorial.zext(W+1);
1211   MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
1212   MultiplyFactor = MultiplyFactor.trunc(W);
1213 
1214   // Calculate the product, at width T+W
1215   IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
1216                                                       CalculationBits);
1217   const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
1218   for (unsigned i = 1; i != K; ++i) {
1219     const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
1220     Dividend = SE.getMulExpr(Dividend,
1221                              SE.getTruncateOrZeroExtend(S, CalculationTy));
1222   }
1223 
1224   // Divide by 2^T
1225   const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
1226 
1227   // Truncate the result, and divide by K! / 2^T.
1228 
1229   return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1230                        SE.getTruncateOrZeroExtend(DivResult, ResultTy));
1231 }
1232 
1233 /// Return the value of this chain of recurrences at the specified iteration
1234 /// number.  We can evaluate this recurrence by multiplying each element in the
1235 /// chain by the binomial coefficient corresponding to it.  In other words, we
1236 /// can evaluate {A,+,B,+,C,+,D} as:
1237 ///
1238 ///   A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
1239 ///
1240 /// where BC(It, k) stands for binomial coefficient.
1241 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
1242                                                 ScalarEvolution &SE) const {
1243   const SCEV *Result = getStart();
1244   for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1245     // The computation is correct in the face of overflow provided that the
1246     // multiplication is performed _after_ the evaluation of the binomial
1247     // coefficient.
1248     const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
1249     if (isa<SCEVCouldNotCompute>(Coeff))
1250       return Coeff;
1251 
1252     Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
1253   }
1254   return Result;
1255 }
1256 
1257 //===----------------------------------------------------------------------===//
1258 //                    SCEV Expression folder implementations
1259 //===----------------------------------------------------------------------===//
1260 
1261 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, Type *Ty,
1262                                              unsigned Depth) {
1263   assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1264          "This is not a truncating conversion!");
1265   assert(isSCEVable(Ty) &&
1266          "This is not a conversion to a SCEVable type!");
1267   Ty = getEffectiveSCEVType(Ty);
1268 
1269   FoldingSetNodeID ID;
1270   ID.AddInteger(scTruncate);
1271   ID.AddPointer(Op);
1272   ID.AddPointer(Ty);
1273   void *IP = nullptr;
1274   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1275 
1276   // Fold if the operand is constant.
1277   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1278     return getConstant(
1279       cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1280 
1281   // trunc(trunc(x)) --> trunc(x)
1282   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
1283     return getTruncateExpr(ST->getOperand(), Ty, Depth + 1);
1284 
1285   // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1286   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1287     return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1);
1288 
1289   // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1290   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1291     return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1);
1292 
1293   if (Depth > MaxCastDepth) {
1294     SCEV *S =
1295         new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty);
1296     UniqueSCEVs.InsertNode(S, IP);
1297     addToLoopUseLists(S);
1298     return S;
1299   }
1300 
1301   // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and
1302   // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN),
1303   // if after transforming we have at most one truncate, not counting truncates
1304   // that replace other casts.
1305   if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) {
1306     auto *CommOp = cast<SCEVCommutativeExpr>(Op);
1307     SmallVector<const SCEV *, 4> Operands;
1308     unsigned numTruncs = 0;
1309     for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2;
1310          ++i) {
1311       const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1);
1312       if (!isa<SCEVCastExpr>(CommOp->getOperand(i)) && isa<SCEVTruncateExpr>(S))
1313         numTruncs++;
1314       Operands.push_back(S);
1315     }
1316     if (numTruncs < 2) {
1317       if (isa<SCEVAddExpr>(Op))
1318         return getAddExpr(Operands);
1319       else if (isa<SCEVMulExpr>(Op))
1320         return getMulExpr(Operands);
1321       else
1322         llvm_unreachable("Unexpected SCEV type for Op.");
1323     }
1324     // Although we checked in the beginning that ID is not in the cache, it is
1325     // possible that during recursion and different modification ID was inserted
1326     // into the cache. So if we find it, just return it.
1327     if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1328       return S;
1329   }
1330 
1331   // If the input value is a chrec scev, truncate the chrec's operands.
1332   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1333     SmallVector<const SCEV *, 4> Operands;
1334     for (const SCEV *Op : AddRec->operands())
1335       Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1));
1336     return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1337   }
1338 
1339   // The cast wasn't folded; create an explicit cast node. We can reuse
1340   // the existing insert position since if we get here, we won't have
1341   // made any changes which would invalidate it.
1342   SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1343                                                  Op, Ty);
1344   UniqueSCEVs.InsertNode(S, IP);
1345   addToLoopUseLists(S);
1346   return S;
1347 }
1348 
1349 // Get the limit of a recurrence such that incrementing by Step cannot cause
1350 // signed overflow as long as the value of the recurrence within the
1351 // loop does not exceed this limit before incrementing.
1352 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1353                                                  ICmpInst::Predicate *Pred,
1354                                                  ScalarEvolution *SE) {
1355   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1356   if (SE->isKnownPositive(Step)) {
1357     *Pred = ICmpInst::ICMP_SLT;
1358     return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1359                            SE->getSignedRangeMax(Step));
1360   }
1361   if (SE->isKnownNegative(Step)) {
1362     *Pred = ICmpInst::ICMP_SGT;
1363     return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1364                            SE->getSignedRangeMin(Step));
1365   }
1366   return nullptr;
1367 }
1368 
1369 // Get the limit of a recurrence such that incrementing by Step cannot cause
1370 // unsigned overflow as long as the value of the recurrence within the loop does
1371 // not exceed this limit before incrementing.
1372 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1373                                                    ICmpInst::Predicate *Pred,
1374                                                    ScalarEvolution *SE) {
1375   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1376   *Pred = ICmpInst::ICMP_ULT;
1377 
1378   return SE->getConstant(APInt::getMinValue(BitWidth) -
1379                          SE->getUnsignedRangeMax(Step));
1380 }
1381 
1382 namespace {
1383 
1384 struct ExtendOpTraitsBase {
1385   typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *,
1386                                                           unsigned);
1387 };
1388 
1389 // Used to make code generic over signed and unsigned overflow.
1390 template <typename ExtendOp> struct ExtendOpTraits {
1391   // Members present:
1392   //
1393   // static const SCEV::NoWrapFlags WrapType;
1394   //
1395   // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1396   //
1397   // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1398   //                                           ICmpInst::Predicate *Pred,
1399   //                                           ScalarEvolution *SE);
1400 };
1401 
1402 template <>
1403 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1404   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1405 
1406   static const GetExtendExprTy GetExtendExpr;
1407 
1408   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1409                                              ICmpInst::Predicate *Pred,
1410                                              ScalarEvolution *SE) {
1411     return getSignedOverflowLimitForStep(Step, Pred, SE);
1412   }
1413 };
1414 
1415 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1416     SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr;
1417 
1418 template <>
1419 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1420   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1421 
1422   static const GetExtendExprTy GetExtendExpr;
1423 
1424   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1425                                              ICmpInst::Predicate *Pred,
1426                                              ScalarEvolution *SE) {
1427     return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1428   }
1429 };
1430 
1431 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1432     SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr;
1433 
1434 } // end anonymous namespace
1435 
1436 // The recurrence AR has been shown to have no signed/unsigned wrap or something
1437 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1438 // easily prove NSW/NUW for its preincrement or postincrement sibling. This
1439 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1440 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1441 // expression "Step + sext/zext(PreIncAR)" is congruent with
1442 // "sext/zext(PostIncAR)"
1443 template <typename ExtendOpTy>
1444 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1445                                         ScalarEvolution *SE, unsigned Depth) {
1446   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1447   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1448 
1449   const Loop *L = AR->getLoop();
1450   const SCEV *Start = AR->getStart();
1451   const SCEV *Step = AR->getStepRecurrence(*SE);
1452 
1453   // Check for a simple looking step prior to loop entry.
1454   const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1455   if (!SA)
1456     return nullptr;
1457 
1458   // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1459   // subtraction is expensive. For this purpose, perform a quick and dirty
1460   // difference, by checking for Step in the operand list.
1461   SmallVector<const SCEV *, 4> DiffOps;
1462   for (const SCEV *Op : SA->operands())
1463     if (Op != Step)
1464       DiffOps.push_back(Op);
1465 
1466   if (DiffOps.size() == SA->getNumOperands())
1467     return nullptr;
1468 
1469   // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1470   // `Step`:
1471 
1472   // 1. NSW/NUW flags on the step increment.
1473   auto PreStartFlags =
1474     ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
1475   const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1476   const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1477       SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1478 
1479   // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1480   // "S+X does not sign/unsign-overflow".
1481   //
1482 
1483   const SCEV *BECount = SE->getBackedgeTakenCount(L);
1484   if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1485       !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1486     return PreStart;
1487 
1488   // 2. Direct overflow check on the step operation's expression.
1489   unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1490   Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1491   const SCEV *OperandExtendedStart =
1492       SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
1493                      (SE->*GetExtendExpr)(Step, WideTy, Depth));
1494   if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
1495     if (PreAR && AR->getNoWrapFlags(WrapType)) {
1496       // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1497       // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1498       // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`.  Cache this fact.
1499       const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType);
1500     }
1501     return PreStart;
1502   }
1503 
1504   // 3. Loop precondition.
1505   ICmpInst::Predicate Pred;
1506   const SCEV *OverflowLimit =
1507       ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1508 
1509   if (OverflowLimit &&
1510       SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1511     return PreStart;
1512 
1513   return nullptr;
1514 }
1515 
1516 // Get the normalized zero or sign extended expression for this AddRec's Start.
1517 template <typename ExtendOpTy>
1518 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1519                                         ScalarEvolution *SE,
1520                                         unsigned Depth) {
1521   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1522 
1523   const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth);
1524   if (!PreStart)
1525     return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth);
1526 
1527   return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty,
1528                                              Depth),
1529                         (SE->*GetExtendExpr)(PreStart, Ty, Depth));
1530 }
1531 
1532 // Try to prove away overflow by looking at "nearby" add recurrences.  A
1533 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1534 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1535 //
1536 // Formally:
1537 //
1538 //     {S,+,X} == {S-T,+,X} + T
1539 //  => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1540 //
1541 // If ({S-T,+,X} + T) does not overflow  ... (1)
1542 //
1543 //  RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1544 //
1545 // If {S-T,+,X} does not overflow  ... (2)
1546 //
1547 //  RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1548 //      == {Ext(S-T)+Ext(T),+,Ext(X)}
1549 //
1550 // If (S-T)+T does not overflow  ... (3)
1551 //
1552 //  RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1553 //      == {Ext(S),+,Ext(X)} == LHS
1554 //
1555 // Thus, if (1), (2) and (3) are true for some T, then
1556 //   Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1557 //
1558 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1559 // does not overflow" restricted to the 0th iteration.  Therefore we only need
1560 // to check for (1) and (2).
1561 //
1562 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1563 // is `Delta` (defined below).
1564 template <typename ExtendOpTy>
1565 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1566                                                 const SCEV *Step,
1567                                                 const Loop *L) {
1568   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1569 
1570   // We restrict `Start` to a constant to prevent SCEV from spending too much
1571   // time here.  It is correct (but more expensive) to continue with a
1572   // non-constant `Start` and do a general SCEV subtraction to compute
1573   // `PreStart` below.
1574   const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1575   if (!StartC)
1576     return false;
1577 
1578   APInt StartAI = StartC->getAPInt();
1579 
1580   for (unsigned Delta : {-2, -1, 1, 2}) {
1581     const SCEV *PreStart = getConstant(StartAI - Delta);
1582 
1583     FoldingSetNodeID ID;
1584     ID.AddInteger(scAddRecExpr);
1585     ID.AddPointer(PreStart);
1586     ID.AddPointer(Step);
1587     ID.AddPointer(L);
1588     void *IP = nullptr;
1589     const auto *PreAR =
1590       static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1591 
1592     // Give up if we don't already have the add recurrence we need because
1593     // actually constructing an add recurrence is relatively expensive.
1594     if (PreAR && PreAR->getNoWrapFlags(WrapType)) {  // proves (2)
1595       const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1596       ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1597       const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1598           DeltaS, &Pred, this);
1599       if (Limit && isKnownPredicate(Pred, PreAR, Limit))  // proves (1)
1600         return true;
1601     }
1602   }
1603 
1604   return false;
1605 }
1606 
1607 // Finds an integer D for an expression (C + x + y + ...) such that the top
1608 // level addition in (D + (C - D + x + y + ...)) would not wrap (signed or
1609 // unsigned) and the number of trailing zeros of (C - D + x + y + ...) is
1610 // maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and
1611 // the (C + x + y + ...) expression is \p WholeAddExpr.
1612 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE,
1613                                             const SCEVConstant *ConstantTerm,
1614                                             const SCEVAddExpr *WholeAddExpr) {
1615   const APInt C = ConstantTerm->getAPInt();
1616   const unsigned BitWidth = C.getBitWidth();
1617   // Find number of trailing zeros of (x + y + ...) w/o the C first:
1618   uint32_t TZ = BitWidth;
1619   for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I)
1620     TZ = std::min(TZ, SE.GetMinTrailingZeros(WholeAddExpr->getOperand(I)));
1621   if (TZ) {
1622     // Set D to be as many least significant bits of C as possible while still
1623     // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap:
1624     return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C;
1625   }
1626   return APInt(BitWidth, 0);
1627 }
1628 
1629 // Finds an integer D for an affine AddRec expression {C,+,x} such that the top
1630 // level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the
1631 // number of trailing zeros of (C - D + x * n) is maximized, where C is the \p
1632 // ConstantStart, x is an arbitrary \p Step, and n is the loop trip count.
1633 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE,
1634                                             const APInt &ConstantStart,
1635                                             const SCEV *Step) {
1636   const unsigned BitWidth = ConstantStart.getBitWidth();
1637   const uint32_t TZ = SE.GetMinTrailingZeros(Step);
1638   if (TZ)
1639     return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth)
1640                          : ConstantStart;
1641   return APInt(BitWidth, 0);
1642 }
1643 
1644 const SCEV *
1645 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1646   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1647          "This is not an extending conversion!");
1648   assert(isSCEVable(Ty) &&
1649          "This is not a conversion to a SCEVable type!");
1650   Ty = getEffectiveSCEVType(Ty);
1651 
1652   // Fold if the operand is constant.
1653   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1654     return getConstant(
1655       cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
1656 
1657   // zext(zext(x)) --> zext(x)
1658   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1659     return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1660 
1661   // Before doing any expensive analysis, check to see if we've already
1662   // computed a SCEV for this Op and Ty.
1663   FoldingSetNodeID ID;
1664   ID.AddInteger(scZeroExtend);
1665   ID.AddPointer(Op);
1666   ID.AddPointer(Ty);
1667   void *IP = nullptr;
1668   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1669   if (Depth > MaxCastDepth) {
1670     SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1671                                                      Op, Ty);
1672     UniqueSCEVs.InsertNode(S, IP);
1673     addToLoopUseLists(S);
1674     return S;
1675   }
1676 
1677   // zext(trunc(x)) --> zext(x) or x or trunc(x)
1678   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1679     // It's possible the bits taken off by the truncate were all zero bits. If
1680     // so, we should be able to simplify this further.
1681     const SCEV *X = ST->getOperand();
1682     ConstantRange CR = getUnsignedRange(X);
1683     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1684     unsigned NewBits = getTypeSizeInBits(Ty);
1685     if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1686             CR.zextOrTrunc(NewBits)))
1687       return getTruncateOrZeroExtend(X, Ty, Depth);
1688   }
1689 
1690   // If the input value is a chrec scev, and we can prove that the value
1691   // did not overflow the old, smaller, value, we can zero extend all of the
1692   // operands (often constants).  This allows analysis of something like
1693   // this:  for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1694   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1695     if (AR->isAffine()) {
1696       const SCEV *Start = AR->getStart();
1697       const SCEV *Step = AR->getStepRecurrence(*this);
1698       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1699       const Loop *L = AR->getLoop();
1700 
1701       if (!AR->hasNoUnsignedWrap()) {
1702         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1703         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1704       }
1705 
1706       // If we have special knowledge that this addrec won't overflow,
1707       // we don't need to do any further analysis.
1708       if (AR->hasNoUnsignedWrap())
1709         return getAddRecExpr(
1710             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1711             getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1712 
1713       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1714       // Note that this serves two purposes: It filters out loops that are
1715       // simply not analyzable, and it covers the case where this code is
1716       // being called from within backedge-taken count analysis, such that
1717       // attempting to ask for the backedge-taken count would likely result
1718       // in infinite recursion. In the later case, the analysis code will
1719       // cope with a conservative value, and it will take care to purge
1720       // that value once it has finished.
1721       const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
1722       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1723         // Manually compute the final value for AR, checking for
1724         // overflow.
1725 
1726         // Check whether the backedge-taken count can be losslessly casted to
1727         // the addrec's type. The count is always unsigned.
1728         const SCEV *CastedMaxBECount =
1729             getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
1730         const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
1731             CastedMaxBECount, MaxBECount->getType(), Depth);
1732         if (MaxBECount == RecastedMaxBECount) {
1733           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1734           // Check whether Start+Step*MaxBECount has no unsigned overflow.
1735           const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step,
1736                                         SCEV::FlagAnyWrap, Depth + 1);
1737           const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul,
1738                                                           SCEV::FlagAnyWrap,
1739                                                           Depth + 1),
1740                                                WideTy, Depth + 1);
1741           const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
1742           const SCEV *WideMaxBECount =
1743             getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1744           const SCEV *OperandExtendedAdd =
1745             getAddExpr(WideStart,
1746                        getMulExpr(WideMaxBECount,
1747                                   getZeroExtendExpr(Step, WideTy, Depth + 1),
1748                                   SCEV::FlagAnyWrap, Depth + 1),
1749                        SCEV::FlagAnyWrap, Depth + 1);
1750           if (ZAdd == OperandExtendedAdd) {
1751             // Cache knowledge of AR NUW, which is propagated to this AddRec.
1752             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1753             // Return the expression with the addrec on the outside.
1754             return getAddRecExpr(
1755                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1756                                                          Depth + 1),
1757                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1758                 AR->getNoWrapFlags());
1759           }
1760           // Similar to above, only this time treat the step value as signed.
1761           // This covers loops that count down.
1762           OperandExtendedAdd =
1763             getAddExpr(WideStart,
1764                        getMulExpr(WideMaxBECount,
1765                                   getSignExtendExpr(Step, WideTy, Depth + 1),
1766                                   SCEV::FlagAnyWrap, Depth + 1),
1767                        SCEV::FlagAnyWrap, Depth + 1);
1768           if (ZAdd == OperandExtendedAdd) {
1769             // Cache knowledge of AR NW, which is propagated to this AddRec.
1770             // Negative step causes unsigned wrap, but it still can't self-wrap.
1771             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1772             // Return the expression with the addrec on the outside.
1773             return getAddRecExpr(
1774                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1775                                                          Depth + 1),
1776                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1777                 AR->getNoWrapFlags());
1778           }
1779         }
1780       }
1781 
1782       // Normally, in the cases we can prove no-overflow via a
1783       // backedge guarding condition, we can also compute a backedge
1784       // taken count for the loop.  The exceptions are assumptions and
1785       // guards present in the loop -- SCEV is not great at exploiting
1786       // these to compute max backedge taken counts, but can still use
1787       // these to prove lack of overflow.  Use this fact to avoid
1788       // doing extra work that may not pay off.
1789       if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1790           !AC.assumptions().empty()) {
1791         // If the backedge is guarded by a comparison with the pre-inc
1792         // value the addrec is safe. Also, if the entry is guarded by
1793         // a comparison with the start value and the backedge is
1794         // guarded by a comparison with the post-inc value, the addrec
1795         // is safe.
1796         if (isKnownPositive(Step)) {
1797           const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
1798                                       getUnsignedRangeMax(Step));
1799           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
1800               isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) {
1801             // Cache knowledge of AR NUW, which is propagated to this
1802             // AddRec.
1803             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1804             // Return the expression with the addrec on the outside.
1805             return getAddRecExpr(
1806                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1807                                                          Depth + 1),
1808                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1809                 AR->getNoWrapFlags());
1810           }
1811         } else if (isKnownNegative(Step)) {
1812           const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1813                                       getSignedRangeMin(Step));
1814           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1815               isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) {
1816             // Cache knowledge of AR NW, which is propagated to this
1817             // AddRec.  Negative step causes unsigned wrap, but it
1818             // still can't self-wrap.
1819             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1820             // Return the expression with the addrec on the outside.
1821             return getAddRecExpr(
1822                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1823                                                          Depth + 1),
1824                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1825                 AR->getNoWrapFlags());
1826           }
1827         }
1828       }
1829 
1830       // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw>
1831       // if D + (C - D + Step * n) could be proven to not unsigned wrap
1832       // where D maximizes the number of trailing zeros of (C - D + Step * n)
1833       if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
1834         const APInt &C = SC->getAPInt();
1835         const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
1836         if (D != 0) {
1837           const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1838           const SCEV *SResidual =
1839               getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
1840           const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1841           return getAddExpr(SZExtD, SZExtR,
1842                             (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1843                             Depth + 1);
1844         }
1845       }
1846 
1847       if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1848         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1849         return getAddRecExpr(
1850             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1851             getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1852       }
1853     }
1854 
1855   // zext(A % B) --> zext(A) % zext(B)
1856   {
1857     const SCEV *LHS;
1858     const SCEV *RHS;
1859     if (matchURem(Op, LHS, RHS))
1860       return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1),
1861                          getZeroExtendExpr(RHS, Ty, Depth + 1));
1862   }
1863 
1864   // zext(A / B) --> zext(A) / zext(B).
1865   if (auto *Div = dyn_cast<SCEVUDivExpr>(Op))
1866     return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1),
1867                        getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1));
1868 
1869   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1870     // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1871     if (SA->hasNoUnsignedWrap()) {
1872       // If the addition does not unsign overflow then we can, by definition,
1873       // commute the zero extension with the addition operation.
1874       SmallVector<const SCEV *, 4> Ops;
1875       for (const auto *Op : SA->operands())
1876         Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1877       return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1);
1878     }
1879 
1880     // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...))
1881     // if D + (C - D + x + y + ...) could be proven to not unsigned wrap
1882     // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1883     //
1884     // Often address arithmetics contain expressions like
1885     // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))).
1886     // This transformation is useful while proving that such expressions are
1887     // equal or differ by a small constant amount, see LoadStoreVectorizer pass.
1888     if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1889       const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1890       if (D != 0) {
1891         const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1892         const SCEV *SResidual =
1893             getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth);
1894         const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1895         return getAddExpr(SZExtD, SZExtR,
1896                           (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1897                           Depth + 1);
1898       }
1899     }
1900   }
1901 
1902   if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) {
1903     // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw>
1904     if (SM->hasNoUnsignedWrap()) {
1905       // If the multiply does not unsign overflow then we can, by definition,
1906       // commute the zero extension with the multiply operation.
1907       SmallVector<const SCEV *, 4> Ops;
1908       for (const auto *Op : SM->operands())
1909         Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1910       return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1);
1911     }
1912 
1913     // zext(2^K * (trunc X to iN)) to iM ->
1914     // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw>
1915     //
1916     // Proof:
1917     //
1918     //     zext(2^K * (trunc X to iN)) to iM
1919     //   = zext((trunc X to iN) << K) to iM
1920     //   = zext((trunc X to i{N-K}) << K)<nuw> to iM
1921     //     (because shl removes the top K bits)
1922     //   = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM
1923     //   = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>.
1924     //
1925     if (SM->getNumOperands() == 2)
1926       if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0)))
1927         if (MulLHS->getAPInt().isPowerOf2())
1928           if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) {
1929             int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) -
1930                                MulLHS->getAPInt().logBase2();
1931             Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits);
1932             return getMulExpr(
1933                 getZeroExtendExpr(MulLHS, Ty),
1934                 getZeroExtendExpr(
1935                     getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty),
1936                 SCEV::FlagNUW, Depth + 1);
1937           }
1938   }
1939 
1940   // The cast wasn't folded; create an explicit cast node.
1941   // Recompute the insert position, as it may have been invalidated.
1942   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1943   SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1944                                                    Op, Ty);
1945   UniqueSCEVs.InsertNode(S, IP);
1946   addToLoopUseLists(S);
1947   return S;
1948 }
1949 
1950 const SCEV *
1951 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1952   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1953          "This is not an extending conversion!");
1954   assert(isSCEVable(Ty) &&
1955          "This is not a conversion to a SCEVable type!");
1956   Ty = getEffectiveSCEVType(Ty);
1957 
1958   // Fold if the operand is constant.
1959   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1960     return getConstant(
1961       cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
1962 
1963   // sext(sext(x)) --> sext(x)
1964   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1965     return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1);
1966 
1967   // sext(zext(x)) --> zext(x)
1968   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1969     return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1970 
1971   // Before doing any expensive analysis, check to see if we've already
1972   // computed a SCEV for this Op and Ty.
1973   FoldingSetNodeID ID;
1974   ID.AddInteger(scSignExtend);
1975   ID.AddPointer(Op);
1976   ID.AddPointer(Ty);
1977   void *IP = nullptr;
1978   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1979   // Limit recursion depth.
1980   if (Depth > MaxCastDepth) {
1981     SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1982                                                      Op, Ty);
1983     UniqueSCEVs.InsertNode(S, IP);
1984     addToLoopUseLists(S);
1985     return S;
1986   }
1987 
1988   // sext(trunc(x)) --> sext(x) or x or trunc(x)
1989   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1990     // It's possible the bits taken off by the truncate were all sign bits. If
1991     // so, we should be able to simplify this further.
1992     const SCEV *X = ST->getOperand();
1993     ConstantRange CR = getSignedRange(X);
1994     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1995     unsigned NewBits = getTypeSizeInBits(Ty);
1996     if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1997             CR.sextOrTrunc(NewBits)))
1998       return getTruncateOrSignExtend(X, Ty, Depth);
1999   }
2000 
2001   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
2002     // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
2003     if (SA->hasNoSignedWrap()) {
2004       // If the addition does not sign overflow then we can, by definition,
2005       // commute the sign extension with the addition operation.
2006       SmallVector<const SCEV *, 4> Ops;
2007       for (const auto *Op : SA->operands())
2008         Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1));
2009       return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1);
2010     }
2011 
2012     // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...))
2013     // if D + (C - D + x + y + ...) could be proven to not signed wrap
2014     // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
2015     //
2016     // For instance, this will bring two seemingly different expressions:
2017     //     1 + sext(5 + 20 * %x + 24 * %y)  and
2018     //         sext(6 + 20 * %x + 24 * %y)
2019     // to the same form:
2020     //     2 + sext(4 + 20 * %x + 24 * %y)
2021     if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
2022       const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
2023       if (D != 0) {
2024         const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
2025         const SCEV *SResidual =
2026             getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth);
2027         const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
2028         return getAddExpr(SSExtD, SSExtR,
2029                           (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
2030                           Depth + 1);
2031       }
2032     }
2033   }
2034   // If the input value is a chrec scev, and we can prove that the value
2035   // did not overflow the old, smaller, value, we can sign extend all of the
2036   // operands (often constants).  This allows analysis of something like
2037   // this:  for (signed char X = 0; X < 100; ++X) { int Y = X; }
2038   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
2039     if (AR->isAffine()) {
2040       const SCEV *Start = AR->getStart();
2041       const SCEV *Step = AR->getStepRecurrence(*this);
2042       unsigned BitWidth = getTypeSizeInBits(AR->getType());
2043       const Loop *L = AR->getLoop();
2044 
2045       if (!AR->hasNoSignedWrap()) {
2046         auto NewFlags = proveNoWrapViaConstantRanges(AR);
2047         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
2048       }
2049 
2050       // If we have special knowledge that this addrec won't overflow,
2051       // we don't need to do any further analysis.
2052       if (AR->hasNoSignedWrap())
2053         return getAddRecExpr(
2054             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2055             getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW);
2056 
2057       // Check whether the backedge-taken count is SCEVCouldNotCompute.
2058       // Note that this serves two purposes: It filters out loops that are
2059       // simply not analyzable, and it covers the case where this code is
2060       // being called from within backedge-taken count analysis, such that
2061       // attempting to ask for the backedge-taken count would likely result
2062       // in infinite recursion. In the later case, the analysis code will
2063       // cope with a conservative value, and it will take care to purge
2064       // that value once it has finished.
2065       const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
2066       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
2067         // Manually compute the final value for AR, checking for
2068         // overflow.
2069 
2070         // Check whether the backedge-taken count can be losslessly casted to
2071         // the addrec's type. The count is always unsigned.
2072         const SCEV *CastedMaxBECount =
2073             getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
2074         const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
2075             CastedMaxBECount, MaxBECount->getType(), Depth);
2076         if (MaxBECount == RecastedMaxBECount) {
2077           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
2078           // Check whether Start+Step*MaxBECount has no signed overflow.
2079           const SCEV *SMul = getMulExpr(CastedMaxBECount, Step,
2080                                         SCEV::FlagAnyWrap, Depth + 1);
2081           const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul,
2082                                                           SCEV::FlagAnyWrap,
2083                                                           Depth + 1),
2084                                                WideTy, Depth + 1);
2085           const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
2086           const SCEV *WideMaxBECount =
2087             getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
2088           const SCEV *OperandExtendedAdd =
2089             getAddExpr(WideStart,
2090                        getMulExpr(WideMaxBECount,
2091                                   getSignExtendExpr(Step, WideTy, Depth + 1),
2092                                   SCEV::FlagAnyWrap, Depth + 1),
2093                        SCEV::FlagAnyWrap, Depth + 1);
2094           if (SAdd == OperandExtendedAdd) {
2095             // Cache knowledge of AR NSW, which is propagated to this AddRec.
2096             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
2097             // Return the expression with the addrec on the outside.
2098             return getAddRecExpr(
2099                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
2100                                                          Depth + 1),
2101                 getSignExtendExpr(Step, Ty, Depth + 1), L,
2102                 AR->getNoWrapFlags());
2103           }
2104           // Similar to above, only this time treat the step value as unsigned.
2105           // This covers loops that count up with an unsigned step.
2106           OperandExtendedAdd =
2107             getAddExpr(WideStart,
2108                        getMulExpr(WideMaxBECount,
2109                                   getZeroExtendExpr(Step, WideTy, Depth + 1),
2110                                   SCEV::FlagAnyWrap, Depth + 1),
2111                        SCEV::FlagAnyWrap, Depth + 1);
2112           if (SAdd == OperandExtendedAdd) {
2113             // If AR wraps around then
2114             //
2115             //    abs(Step) * MaxBECount > unsigned-max(AR->getType())
2116             // => SAdd != OperandExtendedAdd
2117             //
2118             // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
2119             // (SAdd == OperandExtendedAdd => AR is NW)
2120 
2121             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
2122 
2123             // Return the expression with the addrec on the outside.
2124             return getAddRecExpr(
2125                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
2126                                                          Depth + 1),
2127                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
2128                 AR->getNoWrapFlags());
2129           }
2130         }
2131       }
2132 
2133       // Normally, in the cases we can prove no-overflow via a
2134       // backedge guarding condition, we can also compute a backedge
2135       // taken count for the loop.  The exceptions are assumptions and
2136       // guards present in the loop -- SCEV is not great at exploiting
2137       // these to compute max backedge taken counts, but can still use
2138       // these to prove lack of overflow.  Use this fact to avoid
2139       // doing extra work that may not pay off.
2140 
2141       if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
2142           !AC.assumptions().empty()) {
2143         // If the backedge is guarded by a comparison with the pre-inc
2144         // value the addrec is safe. Also, if the entry is guarded by
2145         // a comparison with the start value and the backedge is
2146         // guarded by a comparison with the post-inc value, the addrec
2147         // is safe.
2148         ICmpInst::Predicate Pred;
2149         const SCEV *OverflowLimit =
2150             getSignedOverflowLimitForStep(Step, &Pred, this);
2151         if (OverflowLimit &&
2152             (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
2153              isKnownOnEveryIteration(Pred, AR, OverflowLimit))) {
2154           // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec.
2155           const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
2156           return getAddRecExpr(
2157               getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2158               getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2159         }
2160       }
2161 
2162       // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw>
2163       // if D + (C - D + Step * n) could be proven to not signed wrap
2164       // where D maximizes the number of trailing zeros of (C - D + Step * n)
2165       if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
2166         const APInt &C = SC->getAPInt();
2167         const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
2168         if (D != 0) {
2169           const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
2170           const SCEV *SResidual =
2171               getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
2172           const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
2173           return getAddExpr(SSExtD, SSExtR,
2174                             (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
2175                             Depth + 1);
2176         }
2177       }
2178 
2179       if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
2180         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
2181         return getAddRecExpr(
2182             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2183             getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2184       }
2185     }
2186 
2187   // If the input value is provably positive and we could not simplify
2188   // away the sext build a zext instead.
2189   if (isKnownNonNegative(Op))
2190     return getZeroExtendExpr(Op, Ty, Depth + 1);
2191 
2192   // The cast wasn't folded; create an explicit cast node.
2193   // Recompute the insert position, as it may have been invalidated.
2194   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2195   SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
2196                                                    Op, Ty);
2197   UniqueSCEVs.InsertNode(S, IP);
2198   addToLoopUseLists(S);
2199   return S;
2200 }
2201 
2202 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
2203 /// unspecified bits out to the given type.
2204 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
2205                                               Type *Ty) {
2206   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
2207          "This is not an extending conversion!");
2208   assert(isSCEVable(Ty) &&
2209          "This is not a conversion to a SCEVable type!");
2210   Ty = getEffectiveSCEVType(Ty);
2211 
2212   // Sign-extend negative constants.
2213   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
2214     if (SC->getAPInt().isNegative())
2215       return getSignExtendExpr(Op, Ty);
2216 
2217   // Peel off a truncate cast.
2218   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
2219     const SCEV *NewOp = T->getOperand();
2220     if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
2221       return getAnyExtendExpr(NewOp, Ty);
2222     return getTruncateOrNoop(NewOp, Ty);
2223   }
2224 
2225   // Next try a zext cast. If the cast is folded, use it.
2226   const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2227   if (!isa<SCEVZeroExtendExpr>(ZExt))
2228     return ZExt;
2229 
2230   // Next try a sext cast. If the cast is folded, use it.
2231   const SCEV *SExt = getSignExtendExpr(Op, Ty);
2232   if (!isa<SCEVSignExtendExpr>(SExt))
2233     return SExt;
2234 
2235   // Force the cast to be folded into the operands of an addrec.
2236   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2237     SmallVector<const SCEV *, 4> Ops;
2238     for (const SCEV *Op : AR->operands())
2239       Ops.push_back(getAnyExtendExpr(Op, Ty));
2240     return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2241   }
2242 
2243   // If the expression is obviously signed, use the sext cast value.
2244   if (isa<SCEVSMaxExpr>(Op))
2245     return SExt;
2246 
2247   // Absent any other information, use the zext cast value.
2248   return ZExt;
2249 }
2250 
2251 /// Process the given Ops list, which is a list of operands to be added under
2252 /// the given scale, update the given map. This is a helper function for
2253 /// getAddRecExpr. As an example of what it does, given a sequence of operands
2254 /// that would form an add expression like this:
2255 ///
2256 ///    m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2257 ///
2258 /// where A and B are constants, update the map with these values:
2259 ///
2260 ///    (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2261 ///
2262 /// and add 13 + A*B*29 to AccumulatedConstant.
2263 /// This will allow getAddRecExpr to produce this:
2264 ///
2265 ///    13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2266 ///
2267 /// This form often exposes folding opportunities that are hidden in
2268 /// the original operand list.
2269 ///
2270 /// Return true iff it appears that any interesting folding opportunities
2271 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
2272 /// the common case where no interesting opportunities are present, and
2273 /// is also used as a check to avoid infinite recursion.
2274 static bool
2275 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
2276                              SmallVectorImpl<const SCEV *> &NewOps,
2277                              APInt &AccumulatedConstant,
2278                              const SCEV *const *Ops, size_t NumOperands,
2279                              const APInt &Scale,
2280                              ScalarEvolution &SE) {
2281   bool Interesting = false;
2282 
2283   // Iterate over the add operands. They are sorted, with constants first.
2284   unsigned i = 0;
2285   while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2286     ++i;
2287     // Pull a buried constant out to the outside.
2288     if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2289       Interesting = true;
2290     AccumulatedConstant += Scale * C->getAPInt();
2291   }
2292 
2293   // Next comes everything else. We're especially interested in multiplies
2294   // here, but they're in the middle, so just visit the rest with one loop.
2295   for (; i != NumOperands; ++i) {
2296     const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
2297     if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2298       APInt NewScale =
2299           Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2300       if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2301         // A multiplication of a constant with another add; recurse.
2302         const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2303         Interesting |=
2304           CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2305                                        Add->op_begin(), Add->getNumOperands(),
2306                                        NewScale, SE);
2307       } else {
2308         // A multiplication of a constant with some other value. Update
2309         // the map.
2310         SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
2311         const SCEV *Key = SE.getMulExpr(MulOps);
2312         auto Pair = M.insert({Key, NewScale});
2313         if (Pair.second) {
2314           NewOps.push_back(Pair.first->first);
2315         } else {
2316           Pair.first->second += NewScale;
2317           // The map already had an entry for this value, which may indicate
2318           // a folding opportunity.
2319           Interesting = true;
2320         }
2321       }
2322     } else {
2323       // An ordinary operand. Update the map.
2324       std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
2325           M.insert({Ops[i], Scale});
2326       if (Pair.second) {
2327         NewOps.push_back(Pair.first->first);
2328       } else {
2329         Pair.first->second += Scale;
2330         // The map already had an entry for this value, which may indicate
2331         // a folding opportunity.
2332         Interesting = true;
2333       }
2334     }
2335   }
2336 
2337   return Interesting;
2338 }
2339 
2340 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2341 // `OldFlags' as can't-wrap behavior.  Infer a more aggressive set of
2342 // can't-overflow flags for the operation if possible.
2343 static SCEV::NoWrapFlags
2344 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
2345                       const ArrayRef<const SCEV *> Ops,
2346                       SCEV::NoWrapFlags Flags) {
2347   using namespace std::placeholders;
2348 
2349   using OBO = OverflowingBinaryOperator;
2350 
2351   bool CanAnalyze =
2352       Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
2353   (void)CanAnalyze;
2354   assert(CanAnalyze && "don't call from other places!");
2355 
2356   int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2357   SCEV::NoWrapFlags SignOrUnsignWrap =
2358       ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2359 
2360   // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2361   auto IsKnownNonNegative = [&](const SCEV *S) {
2362     return SE->isKnownNonNegative(S);
2363   };
2364 
2365   if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2366     Flags =
2367         ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
2368 
2369   SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2370 
2371   if (SignOrUnsignWrap != SignOrUnsignMask &&
2372       (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 &&
2373       isa<SCEVConstant>(Ops[0])) {
2374 
2375     auto Opcode = [&] {
2376       switch (Type) {
2377       case scAddExpr:
2378         return Instruction::Add;
2379       case scMulExpr:
2380         return Instruction::Mul;
2381       default:
2382         llvm_unreachable("Unexpected SCEV op.");
2383       }
2384     }();
2385 
2386     const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2387 
2388     // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow.
2389     if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2390       auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2391           Opcode, C, OBO::NoSignedWrap);
2392       if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2393         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2394     }
2395 
2396     // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow.
2397     if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2398       auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2399           Opcode, C, OBO::NoUnsignedWrap);
2400       if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2401         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2402     }
2403   }
2404 
2405   return Flags;
2406 }
2407 
2408 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) {
2409   return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader());
2410 }
2411 
2412 /// Get a canonical add expression, or something simpler if possible.
2413 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2414                                         SCEV::NoWrapFlags Flags,
2415                                         unsigned Depth) {
2416   assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2417          "only nuw or nsw allowed");
2418   assert(!Ops.empty() && "Cannot get empty add!");
2419   if (Ops.size() == 1) return Ops[0];
2420 #ifndef NDEBUG
2421   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2422   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2423     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2424            "SCEVAddExpr operand types don't match!");
2425 #endif
2426 
2427   // Sort by complexity, this groups all similar expression types together.
2428   GroupByComplexity(Ops, &LI, DT);
2429 
2430   Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags);
2431 
2432   // If there are any constants, fold them together.
2433   unsigned Idx = 0;
2434   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2435     ++Idx;
2436     assert(Idx < Ops.size());
2437     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2438       // We found two constants, fold them together!
2439       Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
2440       if (Ops.size() == 2) return Ops[0];
2441       Ops.erase(Ops.begin()+1);  // Erase the folded element
2442       LHSC = cast<SCEVConstant>(Ops[0]);
2443     }
2444 
2445     // If we are left with a constant zero being added, strip it off.
2446     if (LHSC->getValue()->isZero()) {
2447       Ops.erase(Ops.begin());
2448       --Idx;
2449     }
2450 
2451     if (Ops.size() == 1) return Ops[0];
2452   }
2453 
2454   // Limit recursion calls depth.
2455   if (Depth > MaxArithDepth || hasHugeExpression(Ops))
2456     return getOrCreateAddExpr(Ops, Flags);
2457 
2458   // Okay, check to see if the same value occurs in the operand list more than
2459   // once.  If so, merge them together into an multiply expression.  Since we
2460   // sorted the list, these values are required to be adjacent.
2461   Type *Ty = Ops[0]->getType();
2462   bool FoundMatch = false;
2463   for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2464     if (Ops[i] == Ops[i+1]) {      //  X + Y + Y  -->  X + Y*2
2465       // Scan ahead to count how many equal operands there are.
2466       unsigned Count = 2;
2467       while (i+Count != e && Ops[i+Count] == Ops[i])
2468         ++Count;
2469       // Merge the values into a multiply.
2470       const SCEV *Scale = getConstant(Ty, Count);
2471       const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1);
2472       if (Ops.size() == Count)
2473         return Mul;
2474       Ops[i] = Mul;
2475       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2476       --i; e -= Count - 1;
2477       FoundMatch = true;
2478     }
2479   if (FoundMatch)
2480     return getAddExpr(Ops, Flags, Depth + 1);
2481 
2482   // Check for truncates. If all the operands are truncated from the same
2483   // type, see if factoring out the truncate would permit the result to be
2484   // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
2485   // if the contents of the resulting outer trunc fold to something simple.
2486   auto FindTruncSrcType = [&]() -> Type * {
2487     // We're ultimately looking to fold an addrec of truncs and muls of only
2488     // constants and truncs, so if we find any other types of SCEV
2489     // as operands of the addrec then we bail and return nullptr here.
2490     // Otherwise, we return the type of the operand of a trunc that we find.
2491     if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx]))
2492       return T->getOperand()->getType();
2493     if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2494       const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1);
2495       if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp))
2496         return T->getOperand()->getType();
2497     }
2498     return nullptr;
2499   };
2500   if (auto *SrcType = FindTruncSrcType()) {
2501     SmallVector<const SCEV *, 8> LargeOps;
2502     bool Ok = true;
2503     // Check all the operands to see if they can be represented in the
2504     // source type of the truncate.
2505     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2506       if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2507         if (T->getOperand()->getType() != SrcType) {
2508           Ok = false;
2509           break;
2510         }
2511         LargeOps.push_back(T->getOperand());
2512       } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2513         LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2514       } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
2515         SmallVector<const SCEV *, 8> LargeMulOps;
2516         for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2517           if (const SCEVTruncateExpr *T =
2518                 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2519             if (T->getOperand()->getType() != SrcType) {
2520               Ok = false;
2521               break;
2522             }
2523             LargeMulOps.push_back(T->getOperand());
2524           } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2525             LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2526           } else {
2527             Ok = false;
2528             break;
2529           }
2530         }
2531         if (Ok)
2532           LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1));
2533       } else {
2534         Ok = false;
2535         break;
2536       }
2537     }
2538     if (Ok) {
2539       // Evaluate the expression in the larger type.
2540       const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1);
2541       // If it folds to something simple, use it. Otherwise, don't.
2542       if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2543         return getTruncateExpr(Fold, Ty);
2544     }
2545   }
2546 
2547   // Skip past any other cast SCEVs.
2548   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2549     ++Idx;
2550 
2551   // If there are add operands they would be next.
2552   if (Idx < Ops.size()) {
2553     bool DeletedAdd = false;
2554     while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2555       if (Ops.size() > AddOpsInlineThreshold ||
2556           Add->getNumOperands() > AddOpsInlineThreshold)
2557         break;
2558       // If we have an add, expand the add operands onto the end of the operands
2559       // list.
2560       Ops.erase(Ops.begin()+Idx);
2561       Ops.append(Add->op_begin(), Add->op_end());
2562       DeletedAdd = true;
2563     }
2564 
2565     // If we deleted at least one add, we added operands to the end of the list,
2566     // and they are not necessarily sorted.  Recurse to resort and resimplify
2567     // any operands we just acquired.
2568     if (DeletedAdd)
2569       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2570   }
2571 
2572   // Skip over the add expression until we get to a multiply.
2573   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2574     ++Idx;
2575 
2576   // Check to see if there are any folding opportunities present with
2577   // operands multiplied by constant values.
2578   if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2579     uint64_t BitWidth = getTypeSizeInBits(Ty);
2580     DenseMap<const SCEV *, APInt> M;
2581     SmallVector<const SCEV *, 8> NewOps;
2582     APInt AccumulatedConstant(BitWidth, 0);
2583     if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2584                                      Ops.data(), Ops.size(),
2585                                      APInt(BitWidth, 1), *this)) {
2586       struct APIntCompare {
2587         bool operator()(const APInt &LHS, const APInt &RHS) const {
2588           return LHS.ult(RHS);
2589         }
2590       };
2591 
2592       // Some interesting folding opportunity is present, so its worthwhile to
2593       // re-generate the operands list. Group the operands by constant scale,
2594       // to avoid multiplying by the same constant scale multiple times.
2595       std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
2596       for (const SCEV *NewOp : NewOps)
2597         MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2598       // Re-generate the operands list.
2599       Ops.clear();
2600       if (AccumulatedConstant != 0)
2601         Ops.push_back(getConstant(AccumulatedConstant));
2602       for (auto &MulOp : MulOpLists)
2603         if (MulOp.first != 0)
2604           Ops.push_back(getMulExpr(
2605               getConstant(MulOp.first),
2606               getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1),
2607               SCEV::FlagAnyWrap, Depth + 1));
2608       if (Ops.empty())
2609         return getZero(Ty);
2610       if (Ops.size() == 1)
2611         return Ops[0];
2612       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2613     }
2614   }
2615 
2616   // If we are adding something to a multiply expression, make sure the
2617   // something is not already an operand of the multiply.  If so, merge it into
2618   // the multiply.
2619   for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2620     const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2621     for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2622       const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2623       if (isa<SCEVConstant>(MulOpSCEV))
2624         continue;
2625       for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
2626         if (MulOpSCEV == Ops[AddOp]) {
2627           // Fold W + X + (X * Y * Z)  -->  W + (X * ((Y*Z)+1))
2628           const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
2629           if (Mul->getNumOperands() != 2) {
2630             // If the multiply has more than two operands, we must get the
2631             // Y*Z term.
2632             SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2633                                                 Mul->op_begin()+MulOp);
2634             MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2635             InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2636           }
2637           SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul};
2638           const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2639           const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV,
2640                                             SCEV::FlagAnyWrap, Depth + 1);
2641           if (Ops.size() == 2) return OuterMul;
2642           if (AddOp < Idx) {
2643             Ops.erase(Ops.begin()+AddOp);
2644             Ops.erase(Ops.begin()+Idx-1);
2645           } else {
2646             Ops.erase(Ops.begin()+Idx);
2647             Ops.erase(Ops.begin()+AddOp-1);
2648           }
2649           Ops.push_back(OuterMul);
2650           return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2651         }
2652 
2653       // Check this multiply against other multiplies being added together.
2654       for (unsigned OtherMulIdx = Idx+1;
2655            OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2656            ++OtherMulIdx) {
2657         const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
2658         // If MulOp occurs in OtherMul, we can fold the two multiplies
2659         // together.
2660         for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2661              OMulOp != e; ++OMulOp)
2662           if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2663             // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
2664             const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
2665             if (Mul->getNumOperands() != 2) {
2666               SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2667                                                   Mul->op_begin()+MulOp);
2668               MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2669               InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2670             }
2671             const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
2672             if (OtherMul->getNumOperands() != 2) {
2673               SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
2674                                                   OtherMul->op_begin()+OMulOp);
2675               MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
2676               InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2677             }
2678             SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2};
2679             const SCEV *InnerMulSum =
2680                 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2681             const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum,
2682                                               SCEV::FlagAnyWrap, Depth + 1);
2683             if (Ops.size() == 2) return OuterMul;
2684             Ops.erase(Ops.begin()+Idx);
2685             Ops.erase(Ops.begin()+OtherMulIdx-1);
2686             Ops.push_back(OuterMul);
2687             return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2688           }
2689       }
2690     }
2691   }
2692 
2693   // If there are any add recurrences in the operands list, see if any other
2694   // added values are loop invariant.  If so, we can fold them into the
2695   // recurrence.
2696   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2697     ++Idx;
2698 
2699   // Scan over all recurrences, trying to fold loop invariants into them.
2700   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2701     // Scan all of the other operands to this add and add them to the vector if
2702     // they are loop invariant w.r.t. the recurrence.
2703     SmallVector<const SCEV *, 8> LIOps;
2704     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2705     const Loop *AddRecLoop = AddRec->getLoop();
2706     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2707       if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2708         LIOps.push_back(Ops[i]);
2709         Ops.erase(Ops.begin()+i);
2710         --i; --e;
2711       }
2712 
2713     // If we found some loop invariants, fold them into the recurrence.
2714     if (!LIOps.empty()) {
2715       //  NLI + LI + {Start,+,Step}  -->  NLI + {LI+Start,+,Step}
2716       LIOps.push_back(AddRec->getStart());
2717 
2718       SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2719                                              AddRec->op_end());
2720       // This follows from the fact that the no-wrap flags on the outer add
2721       // expression are applicable on the 0th iteration, when the add recurrence
2722       // will be equal to its start value.
2723       AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1);
2724 
2725       // Build the new addrec. Propagate the NUW and NSW flags if both the
2726       // outer add and the inner addrec are guaranteed to have no overflow.
2727       // Always propagate NW.
2728       Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2729       const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2730 
2731       // If all of the other operands were loop invariant, we are done.
2732       if (Ops.size() == 1) return NewRec;
2733 
2734       // Otherwise, add the folded AddRec by the non-invariant parts.
2735       for (unsigned i = 0;; ++i)
2736         if (Ops[i] == AddRec) {
2737           Ops[i] = NewRec;
2738           break;
2739         }
2740       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2741     }
2742 
2743     // Okay, if there weren't any loop invariants to be folded, check to see if
2744     // there are multiple AddRec's with the same loop induction variable being
2745     // added together.  If so, we can fold them.
2746     for (unsigned OtherIdx = Idx+1;
2747          OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2748          ++OtherIdx) {
2749       // We expect the AddRecExpr's to be sorted in reverse dominance order,
2750       // so that the 1st found AddRecExpr is dominated by all others.
2751       assert(DT.dominates(
2752            cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
2753            AddRec->getLoop()->getHeader()) &&
2754         "AddRecExprs are not sorted in reverse dominance order?");
2755       if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2756         // Other + {A,+,B}<L> + {C,+,D}<L>  -->  Other + {A+C,+,B+D}<L>
2757         SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2758                                                AddRec->op_end());
2759         for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2760              ++OtherIdx) {
2761           const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2762           if (OtherAddRec->getLoop() == AddRecLoop) {
2763             for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2764                  i != e; ++i) {
2765               if (i >= AddRecOps.size()) {
2766                 AddRecOps.append(OtherAddRec->op_begin()+i,
2767                                  OtherAddRec->op_end());
2768                 break;
2769               }
2770               SmallVector<const SCEV *, 2> TwoOps = {
2771                   AddRecOps[i], OtherAddRec->getOperand(i)};
2772               AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2773             }
2774             Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2775           }
2776         }
2777         // Step size has changed, so we cannot guarantee no self-wraparound.
2778         Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2779         return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2780       }
2781     }
2782 
2783     // Otherwise couldn't fold anything into this recurrence.  Move onto the
2784     // next one.
2785   }
2786 
2787   // Okay, it looks like we really DO need an add expr.  Check to see if we
2788   // already have one, otherwise create a new one.
2789   return getOrCreateAddExpr(Ops, Flags);
2790 }
2791 
2792 const SCEV *
2793 ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops,
2794                                     SCEV::NoWrapFlags Flags) {
2795   FoldingSetNodeID ID;
2796   ID.AddInteger(scAddExpr);
2797   for (const SCEV *Op : Ops)
2798     ID.AddPointer(Op);
2799   void *IP = nullptr;
2800   SCEVAddExpr *S =
2801       static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2802   if (!S) {
2803     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2804     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2805     S = new (SCEVAllocator)
2806         SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
2807     UniqueSCEVs.InsertNode(S, IP);
2808     addToLoopUseLists(S);
2809   }
2810   S->setNoWrapFlags(Flags);
2811   return S;
2812 }
2813 
2814 const SCEV *
2815 ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops,
2816                                        const Loop *L, SCEV::NoWrapFlags Flags) {
2817   FoldingSetNodeID ID;
2818   ID.AddInteger(scAddRecExpr);
2819   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2820     ID.AddPointer(Ops[i]);
2821   ID.AddPointer(L);
2822   void *IP = nullptr;
2823   SCEVAddRecExpr *S =
2824       static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2825   if (!S) {
2826     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2827     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2828     S = new (SCEVAllocator)
2829         SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L);
2830     UniqueSCEVs.InsertNode(S, IP);
2831     addToLoopUseLists(S);
2832   }
2833   S->setNoWrapFlags(Flags);
2834   return S;
2835 }
2836 
2837 const SCEV *
2838 ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops,
2839                                     SCEV::NoWrapFlags Flags) {
2840   FoldingSetNodeID ID;
2841   ID.AddInteger(scMulExpr);
2842   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2843     ID.AddPointer(Ops[i]);
2844   void *IP = nullptr;
2845   SCEVMulExpr *S =
2846     static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2847   if (!S) {
2848     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2849     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2850     S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2851                                         O, Ops.size());
2852     UniqueSCEVs.InsertNode(S, IP);
2853     addToLoopUseLists(S);
2854   }
2855   S->setNoWrapFlags(Flags);
2856   return S;
2857 }
2858 
2859 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2860   uint64_t k = i*j;
2861   if (j > 1 && k / j != i) Overflow = true;
2862   return k;
2863 }
2864 
2865 /// Compute the result of "n choose k", the binomial coefficient.  If an
2866 /// intermediate computation overflows, Overflow will be set and the return will
2867 /// be garbage. Overflow is not cleared on absence of overflow.
2868 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2869   // We use the multiplicative formula:
2870   //     n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2871   // At each iteration, we take the n-th term of the numeral and divide by the
2872   // (k-n)th term of the denominator.  This division will always produce an
2873   // integral result, and helps reduce the chance of overflow in the
2874   // intermediate computations. However, we can still overflow even when the
2875   // final result would fit.
2876 
2877   if (n == 0 || n == k) return 1;
2878   if (k > n) return 0;
2879 
2880   if (k > n/2)
2881     k = n-k;
2882 
2883   uint64_t r = 1;
2884   for (uint64_t i = 1; i <= k; ++i) {
2885     r = umul_ov(r, n-(i-1), Overflow);
2886     r /= i;
2887   }
2888   return r;
2889 }
2890 
2891 /// Determine if any of the operands in this SCEV are a constant or if
2892 /// any of the add or multiply expressions in this SCEV contain a constant.
2893 static bool containsConstantInAddMulChain(const SCEV *StartExpr) {
2894   struct FindConstantInAddMulChain {
2895     bool FoundConstant = false;
2896 
2897     bool follow(const SCEV *S) {
2898       FoundConstant |= isa<SCEVConstant>(S);
2899       return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
2900     }
2901 
2902     bool isDone() const {
2903       return FoundConstant;
2904     }
2905   };
2906 
2907   FindConstantInAddMulChain F;
2908   SCEVTraversal<FindConstantInAddMulChain> ST(F);
2909   ST.visitAll(StartExpr);
2910   return F.FoundConstant;
2911 }
2912 
2913 /// Get a canonical multiply expression, or something simpler if possible.
2914 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
2915                                         SCEV::NoWrapFlags Flags,
2916                                         unsigned Depth) {
2917   assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&
2918          "only nuw or nsw allowed");
2919   assert(!Ops.empty() && "Cannot get empty mul!");
2920   if (Ops.size() == 1) return Ops[0];
2921 #ifndef NDEBUG
2922   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2923   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2924     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2925            "SCEVMulExpr operand types don't match!");
2926 #endif
2927 
2928   // Sort by complexity, this groups all similar expression types together.
2929   GroupByComplexity(Ops, &LI, DT);
2930 
2931   Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags);
2932 
2933   // Limit recursion calls depth.
2934   if (Depth > MaxArithDepth || hasHugeExpression(Ops))
2935     return getOrCreateMulExpr(Ops, Flags);
2936 
2937   // If there are any constants, fold them together.
2938   unsigned Idx = 0;
2939   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2940 
2941     if (Ops.size() == 2)
2942       // C1*(C2+V) -> C1*C2 + C1*V
2943       if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
2944         // If any of Add's ops are Adds or Muls with a constant, apply this
2945         // transformation as well.
2946         //
2947         // TODO: There are some cases where this transformation is not
2948         // profitable; for example, Add = (C0 + X) * Y + Z.  Maybe the scope of
2949         // this transformation should be narrowed down.
2950         if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add))
2951           return getAddExpr(getMulExpr(LHSC, Add->getOperand(0),
2952                                        SCEV::FlagAnyWrap, Depth + 1),
2953                             getMulExpr(LHSC, Add->getOperand(1),
2954                                        SCEV::FlagAnyWrap, Depth + 1),
2955                             SCEV::FlagAnyWrap, Depth + 1);
2956 
2957     ++Idx;
2958     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2959       // We found two constants, fold them together!
2960       ConstantInt *Fold =
2961           ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt());
2962       Ops[0] = getConstant(Fold);
2963       Ops.erase(Ops.begin()+1);  // Erase the folded element
2964       if (Ops.size() == 1) return Ops[0];
2965       LHSC = cast<SCEVConstant>(Ops[0]);
2966     }
2967 
2968     // If we are left with a constant one being multiplied, strip it off.
2969     if (cast<SCEVConstant>(Ops[0])->getValue()->isOne()) {
2970       Ops.erase(Ops.begin());
2971       --Idx;
2972     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
2973       // If we have a multiply of zero, it will always be zero.
2974       return Ops[0];
2975     } else if (Ops[0]->isAllOnesValue()) {
2976       // If we have a mul by -1 of an add, try distributing the -1 among the
2977       // add operands.
2978       if (Ops.size() == 2) {
2979         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
2980           SmallVector<const SCEV *, 4> NewOps;
2981           bool AnyFolded = false;
2982           for (const SCEV *AddOp : Add->operands()) {
2983             const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap,
2984                                          Depth + 1);
2985             if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
2986             NewOps.push_back(Mul);
2987           }
2988           if (AnyFolded)
2989             return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1);
2990         } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
2991           // Negation preserves a recurrence's no self-wrap property.
2992           SmallVector<const SCEV *, 4> Operands;
2993           for (const SCEV *AddRecOp : AddRec->operands())
2994             Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap,
2995                                           Depth + 1));
2996 
2997           return getAddRecExpr(Operands, AddRec->getLoop(),
2998                                AddRec->getNoWrapFlags(SCEV::FlagNW));
2999         }
3000       }
3001     }
3002 
3003     if (Ops.size() == 1)
3004       return Ops[0];
3005   }
3006 
3007   // Skip over the add expression until we get to a multiply.
3008   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
3009     ++Idx;
3010 
3011   // If there are mul operands inline them all into this expression.
3012   if (Idx < Ops.size()) {
3013     bool DeletedMul = false;
3014     while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
3015       if (Ops.size() > MulOpsInlineThreshold)
3016         break;
3017       // If we have an mul, expand the mul operands onto the end of the
3018       // operands list.
3019       Ops.erase(Ops.begin()+Idx);
3020       Ops.append(Mul->op_begin(), Mul->op_end());
3021       DeletedMul = true;
3022     }
3023 
3024     // If we deleted at least one mul, we added operands to the end of the
3025     // list, and they are not necessarily sorted.  Recurse to resort and
3026     // resimplify any operands we just acquired.
3027     if (DeletedMul)
3028       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3029   }
3030 
3031   // If there are any add recurrences in the operands list, see if any other
3032   // added values are loop invariant.  If so, we can fold them into the
3033   // recurrence.
3034   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
3035     ++Idx;
3036 
3037   // Scan over all recurrences, trying to fold loop invariants into them.
3038   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
3039     // Scan all of the other operands to this mul and add them to the vector
3040     // if they are loop invariant w.r.t. the recurrence.
3041     SmallVector<const SCEV *, 8> LIOps;
3042     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
3043     const Loop *AddRecLoop = AddRec->getLoop();
3044     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3045       if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
3046         LIOps.push_back(Ops[i]);
3047         Ops.erase(Ops.begin()+i);
3048         --i; --e;
3049       }
3050 
3051     // If we found some loop invariants, fold them into the recurrence.
3052     if (!LIOps.empty()) {
3053       //  NLI * LI * {Start,+,Step}  -->  NLI * {LI*Start,+,LI*Step}
3054       SmallVector<const SCEV *, 4> NewOps;
3055       NewOps.reserve(AddRec->getNumOperands());
3056       const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1);
3057       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
3058         NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
3059                                     SCEV::FlagAnyWrap, Depth + 1));
3060 
3061       // Build the new addrec. Propagate the NUW and NSW flags if both the
3062       // outer mul and the inner addrec are guaranteed to have no overflow.
3063       //
3064       // No self-wrap cannot be guaranteed after changing the step size, but
3065       // will be inferred if either NUW or NSW is true.
3066       Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW));
3067       const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
3068 
3069       // If all of the other operands were loop invariant, we are done.
3070       if (Ops.size() == 1) return NewRec;
3071 
3072       // Otherwise, multiply the folded AddRec by the non-invariant parts.
3073       for (unsigned i = 0;; ++i)
3074         if (Ops[i] == AddRec) {
3075           Ops[i] = NewRec;
3076           break;
3077         }
3078       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3079     }
3080 
3081     // Okay, if there weren't any loop invariants to be folded, check to see
3082     // if there are multiple AddRec's with the same loop induction variable
3083     // being multiplied together.  If so, we can fold them.
3084 
3085     // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
3086     // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
3087     //       choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
3088     //   ]]],+,...up to x=2n}.
3089     // Note that the arguments to choose() are always integers with values
3090     // known at compile time, never SCEV objects.
3091     //
3092     // The implementation avoids pointless extra computations when the two
3093     // addrec's are of different length (mathematically, it's equivalent to
3094     // an infinite stream of zeros on the right).
3095     bool OpsModified = false;
3096     for (unsigned OtherIdx = Idx+1;
3097          OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
3098          ++OtherIdx) {
3099       const SCEVAddRecExpr *OtherAddRec =
3100         dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
3101       if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
3102         continue;
3103 
3104       // Limit max number of arguments to avoid creation of unreasonably big
3105       // SCEVAddRecs with very complex operands.
3106       if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
3107           MaxAddRecSize || isHugeExpression(AddRec) ||
3108           isHugeExpression(OtherAddRec))
3109         continue;
3110 
3111       bool Overflow = false;
3112       Type *Ty = AddRec->getType();
3113       bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
3114       SmallVector<const SCEV*, 7> AddRecOps;
3115       for (int x = 0, xe = AddRec->getNumOperands() +
3116              OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
3117         SmallVector <const SCEV *, 7> SumOps;
3118         for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
3119           uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
3120           for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
3121                  ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
3122                z < ze && !Overflow; ++z) {
3123             uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
3124             uint64_t Coeff;
3125             if (LargerThan64Bits)
3126               Coeff = umul_ov(Coeff1, Coeff2, Overflow);
3127             else
3128               Coeff = Coeff1*Coeff2;
3129             const SCEV *CoeffTerm = getConstant(Ty, Coeff);
3130             const SCEV *Term1 = AddRec->getOperand(y-z);
3131             const SCEV *Term2 = OtherAddRec->getOperand(z);
3132             SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2,
3133                                         SCEV::FlagAnyWrap, Depth + 1));
3134           }
3135         }
3136         if (SumOps.empty())
3137           SumOps.push_back(getZero(Ty));
3138         AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1));
3139       }
3140       if (!Overflow) {
3141         const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRecLoop,
3142                                               SCEV::FlagAnyWrap);
3143         if (Ops.size() == 2) return NewAddRec;
3144         Ops[Idx] = NewAddRec;
3145         Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
3146         OpsModified = true;
3147         AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
3148         if (!AddRec)
3149           break;
3150       }
3151     }
3152     if (OpsModified)
3153       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3154 
3155     // Otherwise couldn't fold anything into this recurrence.  Move onto the
3156     // next one.
3157   }
3158 
3159   // Okay, it looks like we really DO need an mul expr.  Check to see if we
3160   // already have one, otherwise create a new one.
3161   return getOrCreateMulExpr(Ops, Flags);
3162 }
3163 
3164 /// Represents an unsigned remainder expression based on unsigned division.
3165 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS,
3166                                          const SCEV *RHS) {
3167   assert(getEffectiveSCEVType(LHS->getType()) ==
3168          getEffectiveSCEVType(RHS->getType()) &&
3169          "SCEVURemExpr operand types don't match!");
3170 
3171   // Short-circuit easy cases
3172   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3173     // If constant is one, the result is trivial
3174     if (RHSC->getValue()->isOne())
3175       return getZero(LHS->getType()); // X urem 1 --> 0
3176 
3177     // If constant is a power of two, fold into a zext(trunc(LHS)).
3178     if (RHSC->getAPInt().isPowerOf2()) {
3179       Type *FullTy = LHS->getType();
3180       Type *TruncTy =
3181           IntegerType::get(getContext(), RHSC->getAPInt().logBase2());
3182       return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy);
3183     }
3184   }
3185 
3186   // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
3187   const SCEV *UDiv = getUDivExpr(LHS, RHS);
3188   const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW);
3189   return getMinusSCEV(LHS, Mult, SCEV::FlagNUW);
3190 }
3191 
3192 /// Get a canonical unsigned division expression, or something simpler if
3193 /// possible.
3194 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
3195                                          const SCEV *RHS) {
3196   assert(getEffectiveSCEVType(LHS->getType()) ==
3197          getEffectiveSCEVType(RHS->getType()) &&
3198          "SCEVUDivExpr operand types don't match!");
3199 
3200   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3201     if (RHSC->getValue()->isOne())
3202       return LHS;                               // X udiv 1 --> x
3203     // If the denominator is zero, the result of the udiv is undefined. Don't
3204     // try to analyze it, because the resolution chosen here may differ from
3205     // the resolution chosen in other parts of the compiler.
3206     if (!RHSC->getValue()->isZero()) {
3207       // Determine if the division can be folded into the operands of
3208       // its operands.
3209       // TODO: Generalize this to non-constants by using known-bits information.
3210       Type *Ty = LHS->getType();
3211       unsigned LZ = RHSC->getAPInt().countLeadingZeros();
3212       unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
3213       // For non-power-of-two values, effectively round the value up to the
3214       // nearest power of two.
3215       if (!RHSC->getAPInt().isPowerOf2())
3216         ++MaxShiftAmt;
3217       IntegerType *ExtTy =
3218         IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
3219       if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
3220         if (const SCEVConstant *Step =
3221             dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
3222           // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
3223           const APInt &StepInt = Step->getAPInt();
3224           const APInt &DivInt = RHSC->getAPInt();
3225           if (!StepInt.urem(DivInt) &&
3226               getZeroExtendExpr(AR, ExtTy) ==
3227               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3228                             getZeroExtendExpr(Step, ExtTy),
3229                             AR->getLoop(), SCEV::FlagAnyWrap)) {
3230             SmallVector<const SCEV *, 4> Operands;
3231             for (const SCEV *Op : AR->operands())
3232               Operands.push_back(getUDivExpr(Op, RHS));
3233             return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
3234           }
3235           /// Get a canonical UDivExpr for a recurrence.
3236           /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
3237           // We can currently only fold X%N if X is constant.
3238           const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
3239           if (StartC && !DivInt.urem(StepInt) &&
3240               getZeroExtendExpr(AR, ExtTy) ==
3241               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3242                             getZeroExtendExpr(Step, ExtTy),
3243                             AR->getLoop(), SCEV::FlagAnyWrap)) {
3244             const APInt &StartInt = StartC->getAPInt();
3245             const APInt &StartRem = StartInt.urem(StepInt);
3246             if (StartRem != 0)
3247               LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step,
3248                                   AR->getLoop(), SCEV::FlagNW);
3249           }
3250         }
3251       // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
3252       if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
3253         SmallVector<const SCEV *, 4> Operands;
3254         for (const SCEV *Op : M->operands())
3255           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3256         if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
3257           // Find an operand that's safely divisible.
3258           for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3259             const SCEV *Op = M->getOperand(i);
3260             const SCEV *Div = getUDivExpr(Op, RHSC);
3261             if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
3262               Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
3263                                                       M->op_end());
3264               Operands[i] = Div;
3265               return getMulExpr(Operands);
3266             }
3267           }
3268       }
3269 
3270       // (A/B)/C --> A/(B*C) if safe and B*C can be folded.
3271       if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) {
3272         if (auto *DivisorConstant =
3273                 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) {
3274           bool Overflow = false;
3275           APInt NewRHS =
3276               DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow);
3277           if (Overflow) {
3278             return getConstant(RHSC->getType(), 0, false);
3279           }
3280           return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS));
3281         }
3282       }
3283 
3284       // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
3285       if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
3286         SmallVector<const SCEV *, 4> Operands;
3287         for (const SCEV *Op : A->operands())
3288           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3289         if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
3290           Operands.clear();
3291           for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
3292             const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
3293             if (isa<SCEVUDivExpr>(Op) ||
3294                 getMulExpr(Op, RHS) != A->getOperand(i))
3295               break;
3296             Operands.push_back(Op);
3297           }
3298           if (Operands.size() == A->getNumOperands())
3299             return getAddExpr(Operands);
3300         }
3301       }
3302 
3303       // Fold if both operands are constant.
3304       if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
3305         Constant *LHSCV = LHSC->getValue();
3306         Constant *RHSCV = RHSC->getValue();
3307         return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
3308                                                                    RHSCV)));
3309       }
3310     }
3311   }
3312 
3313   FoldingSetNodeID ID;
3314   ID.AddInteger(scUDivExpr);
3315   ID.AddPointer(LHS);
3316   ID.AddPointer(RHS);
3317   void *IP = nullptr;
3318   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3319   SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
3320                                              LHS, RHS);
3321   UniqueSCEVs.InsertNode(S, IP);
3322   addToLoopUseLists(S);
3323   return S;
3324 }
3325 
3326 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
3327   APInt A = C1->getAPInt().abs();
3328   APInt B = C2->getAPInt().abs();
3329   uint32_t ABW = A.getBitWidth();
3330   uint32_t BBW = B.getBitWidth();
3331 
3332   if (ABW > BBW)
3333     B = B.zext(ABW);
3334   else if (ABW < BBW)
3335     A = A.zext(BBW);
3336 
3337   return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B));
3338 }
3339 
3340 /// Get a canonical unsigned division expression, or something simpler if
3341 /// possible. There is no representation for an exact udiv in SCEV IR, but we
3342 /// can attempt to remove factors from the LHS and RHS.  We can't do this when
3343 /// it's not exact because the udiv may be clearing bits.
3344 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
3345                                               const SCEV *RHS) {
3346   // TODO: we could try to find factors in all sorts of things, but for now we
3347   // just deal with u/exact (multiply, constant). See SCEVDivision towards the
3348   // end of this file for inspiration.
3349 
3350   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
3351   if (!Mul || !Mul->hasNoUnsignedWrap())
3352     return getUDivExpr(LHS, RHS);
3353 
3354   if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
3355     // If the mulexpr multiplies by a constant, then that constant must be the
3356     // first element of the mulexpr.
3357     if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
3358       if (LHSCst == RHSCst) {
3359         SmallVector<const SCEV *, 2> Operands;
3360         Operands.append(Mul->op_begin() + 1, Mul->op_end());
3361         return getMulExpr(Operands);
3362       }
3363 
3364       // We can't just assume that LHSCst divides RHSCst cleanly, it could be
3365       // that there's a factor provided by one of the other terms. We need to
3366       // check.
3367       APInt Factor = gcd(LHSCst, RHSCst);
3368       if (!Factor.isIntN(1)) {
3369         LHSCst =
3370             cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
3371         RHSCst =
3372             cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
3373         SmallVector<const SCEV *, 2> Operands;
3374         Operands.push_back(LHSCst);
3375         Operands.append(Mul->op_begin() + 1, Mul->op_end());
3376         LHS = getMulExpr(Operands);
3377         RHS = RHSCst;
3378         Mul = dyn_cast<SCEVMulExpr>(LHS);
3379         if (!Mul)
3380           return getUDivExactExpr(LHS, RHS);
3381       }
3382     }
3383   }
3384 
3385   for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3386     if (Mul->getOperand(i) == RHS) {
3387       SmallVector<const SCEV *, 2> Operands;
3388       Operands.append(Mul->op_begin(), Mul->op_begin() + i);
3389       Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
3390       return getMulExpr(Operands);
3391     }
3392   }
3393 
3394   return getUDivExpr(LHS, RHS);
3395 }
3396 
3397 /// Get an add recurrence expression for the specified loop.  Simplify the
3398 /// expression as much as possible.
3399 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
3400                                            const Loop *L,
3401                                            SCEV::NoWrapFlags Flags) {
3402   SmallVector<const SCEV *, 4> Operands;
3403   Operands.push_back(Start);
3404   if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3405     if (StepChrec->getLoop() == L) {
3406       Operands.append(StepChrec->op_begin(), StepChrec->op_end());
3407       return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
3408     }
3409 
3410   Operands.push_back(Step);
3411   return getAddRecExpr(Operands, L, Flags);
3412 }
3413 
3414 /// Get an add recurrence expression for the specified loop.  Simplify the
3415 /// expression as much as possible.
3416 const SCEV *
3417 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
3418                                const Loop *L, SCEV::NoWrapFlags Flags) {
3419   if (Operands.size() == 1) return Operands[0];
3420 #ifndef NDEBUG
3421   Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
3422   for (unsigned i = 1, e = Operands.size(); i != e; ++i)
3423     assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
3424            "SCEVAddRecExpr operand types don't match!");
3425   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3426     assert(isLoopInvariant(Operands[i], L) &&
3427            "SCEVAddRecExpr operand is not loop-invariant!");
3428 #endif
3429 
3430   if (Operands.back()->isZero()) {
3431     Operands.pop_back();
3432     return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0}  -->  X
3433   }
3434 
3435   // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and
3436   // use that information to infer NUW and NSW flags. However, computing a
3437   // BE count requires calling getAddRecExpr, so we may not yet have a
3438   // meaningful BE count at this point (and if we don't, we'd be stuck
3439   // with a SCEVCouldNotCompute as the cached BE count).
3440 
3441   Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
3442 
3443   // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3444   if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3445     const Loop *NestedLoop = NestedAR->getLoop();
3446     if (L->contains(NestedLoop)
3447             ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3448             : (!NestedLoop->contains(L) &&
3449                DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3450       SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
3451                                                   NestedAR->op_end());
3452       Operands[0] = NestedAR->getStart();
3453       // AddRecs require their operands be loop-invariant with respect to their
3454       // loops. Don't perform this transformation if it would break this
3455       // requirement.
3456       bool AllInvariant = all_of(
3457           Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3458 
3459       if (AllInvariant) {
3460         // Create a recurrence for the outer loop with the same step size.
3461         //
3462         // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3463         // inner recurrence has the same property.
3464         SCEV::NoWrapFlags OuterFlags =
3465           maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3466 
3467         NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3468         AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3469           return isLoopInvariant(Op, NestedLoop);
3470         });
3471 
3472         if (AllInvariant) {
3473           // Ok, both add recurrences are valid after the transformation.
3474           //
3475           // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3476           // the outer recurrence has the same property.
3477           SCEV::NoWrapFlags InnerFlags =
3478             maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
3479           return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3480         }
3481       }
3482       // Reset Operands to its original state.
3483       Operands[0] = NestedAR;
3484     }
3485   }
3486 
3487   // Okay, it looks like we really DO need an addrec expr.  Check to see if we
3488   // already have one, otherwise create a new one.
3489   return getOrCreateAddRecExpr(Operands, L, Flags);
3490 }
3491 
3492 const SCEV *
3493 ScalarEvolution::getGEPExpr(GEPOperator *GEP,
3494                             const SmallVectorImpl<const SCEV *> &IndexExprs) {
3495   const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3496   // getSCEV(Base)->getType() has the same address space as Base->getType()
3497   // because SCEV::getType() preserves the address space.
3498   Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType());
3499   // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP
3500   // instruction to its SCEV, because the Instruction may be guarded by control
3501   // flow and the no-overflow bits may not be valid for the expression in any
3502   // context. This can be fixed similarly to how these flags are handled for
3503   // adds.
3504   SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW
3505                                              : SCEV::FlagAnyWrap;
3506 
3507   const SCEV *TotalOffset = getZero(IntIdxTy);
3508   // The array size is unimportant. The first thing we do on CurTy is getting
3509   // its element type.
3510   Type *CurTy = ArrayType::get(GEP->getSourceElementType(), 0);
3511   for (const SCEV *IndexExpr : IndexExprs) {
3512     // Compute the (potentially symbolic) offset in bytes for this index.
3513     if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3514       // For a struct, add the member offset.
3515       ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3516       unsigned FieldNo = Index->getZExtValue();
3517       const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo);
3518 
3519       // Add the field offset to the running total offset.
3520       TotalOffset = getAddExpr(TotalOffset, FieldOffset);
3521 
3522       // Update CurTy to the type of the field at Index.
3523       CurTy = STy->getTypeAtIndex(Index);
3524     } else {
3525       // Update CurTy to its element type.
3526       CurTy = cast<SequentialType>(CurTy)->getElementType();
3527       // For an array, add the element offset, explicitly scaled.
3528       const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy);
3529       // Getelementptr indices are signed.
3530       IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy);
3531 
3532       // Multiply the index by the element size to compute the element offset.
3533       const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap);
3534 
3535       // Add the element offset to the running total offset.
3536       TotalOffset = getAddExpr(TotalOffset, LocalOffset);
3537     }
3538   }
3539 
3540   // Add the total offset from all the GEP indices to the base.
3541   return getAddExpr(BaseExpr, TotalOffset, Wrap);
3542 }
3543 
3544 std::tuple<const SCEV *, FoldingSetNodeID, void *>
3545 ScalarEvolution::findExistingSCEVInCache(int SCEVType,
3546                                          ArrayRef<const SCEV *> Ops) {
3547   FoldingSetNodeID ID;
3548   void *IP = nullptr;
3549   ID.AddInteger(SCEVType);
3550   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3551     ID.AddPointer(Ops[i]);
3552   return std::tuple<const SCEV *, FoldingSetNodeID, void *>(
3553       UniqueSCEVs.FindNodeOrInsertPos(ID, IP), std::move(ID), IP);
3554 }
3555 
3556 const SCEV *ScalarEvolution::getMinMaxExpr(unsigned Kind,
3557                                            SmallVectorImpl<const SCEV *> &Ops) {
3558   assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
3559   if (Ops.size() == 1) return Ops[0];
3560 #ifndef NDEBUG
3561   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3562   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3563     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3564            "Operand types don't match!");
3565 #endif
3566 
3567   bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr;
3568   bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr;
3569 
3570   // Sort by complexity, this groups all similar expression types together.
3571   GroupByComplexity(Ops, &LI, DT);
3572 
3573   // Check if we have created the same expression before.
3574   if (const SCEV *S = std::get<0>(findExistingSCEVInCache(Kind, Ops))) {
3575     return S;
3576   }
3577 
3578   // If there are any constants, fold them together.
3579   unsigned Idx = 0;
3580   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3581     ++Idx;
3582     assert(Idx < Ops.size());
3583     auto FoldOp = [&](const APInt &LHS, const APInt &RHS) {
3584       if (Kind == scSMaxExpr)
3585         return APIntOps::smax(LHS, RHS);
3586       else if (Kind == scSMinExpr)
3587         return APIntOps::smin(LHS, RHS);
3588       else if (Kind == scUMaxExpr)
3589         return APIntOps::umax(LHS, RHS);
3590       else if (Kind == scUMinExpr)
3591         return APIntOps::umin(LHS, RHS);
3592       llvm_unreachable("Unknown SCEV min/max opcode");
3593     };
3594 
3595     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3596       // We found two constants, fold them together!
3597       ConstantInt *Fold = ConstantInt::get(
3598           getContext(), FoldOp(LHSC->getAPInt(), RHSC->getAPInt()));
3599       Ops[0] = getConstant(Fold);
3600       Ops.erase(Ops.begin()+1);  // Erase the folded element
3601       if (Ops.size() == 1) return Ops[0];
3602       LHSC = cast<SCEVConstant>(Ops[0]);
3603     }
3604 
3605     bool IsMinV = LHSC->getValue()->isMinValue(IsSigned);
3606     bool IsMaxV = LHSC->getValue()->isMaxValue(IsSigned);
3607 
3608     if (IsMax ? IsMinV : IsMaxV) {
3609       // If we are left with a constant minimum(/maximum)-int, strip it off.
3610       Ops.erase(Ops.begin());
3611       --Idx;
3612     } else if (IsMax ? IsMaxV : IsMinV) {
3613       // If we have a max(/min) with a constant maximum(/minimum)-int,
3614       // it will always be the extremum.
3615       return LHSC;
3616     }
3617 
3618     if (Ops.size() == 1) return Ops[0];
3619   }
3620 
3621   // Find the first operation of the same kind
3622   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind)
3623     ++Idx;
3624 
3625   // Check to see if one of the operands is of the same kind. If so, expand its
3626   // operands onto our operand list, and recurse to simplify.
3627   if (Idx < Ops.size()) {
3628     bool DeletedAny = false;
3629     while (Ops[Idx]->getSCEVType() == Kind) {
3630       const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]);
3631       Ops.erase(Ops.begin()+Idx);
3632       Ops.append(SMME->op_begin(), SMME->op_end());
3633       DeletedAny = true;
3634     }
3635 
3636     if (DeletedAny)
3637       return getMinMaxExpr(Kind, Ops);
3638   }
3639 
3640   // Okay, check to see if the same value occurs in the operand list twice.  If
3641   // so, delete one.  Since we sorted the list, these values are required to
3642   // be adjacent.
3643   llvm::CmpInst::Predicate GEPred =
3644       IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
3645   llvm::CmpInst::Predicate LEPred =
3646       IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
3647   llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred;
3648   llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred;
3649   for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) {
3650     if (Ops[i] == Ops[i + 1] ||
3651         isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) {
3652       //  X op Y op Y  -->  X op Y
3653       //  X op Y       -->  X, if we know X, Y are ordered appropriately
3654       Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2);
3655       --i;
3656       --e;
3657     } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i],
3658                                                Ops[i + 1])) {
3659       //  X op Y       -->  Y, if we know X, Y are ordered appropriately
3660       Ops.erase(Ops.begin() + i, Ops.begin() + i + 1);
3661       --i;
3662       --e;
3663     }
3664   }
3665 
3666   if (Ops.size() == 1) return Ops[0];
3667 
3668   assert(!Ops.empty() && "Reduced smax down to nothing!");
3669 
3670   // Okay, it looks like we really DO need an expr.  Check to see if we
3671   // already have one, otherwise create a new one.
3672   const SCEV *ExistingSCEV;
3673   FoldingSetNodeID ID;
3674   void *IP;
3675   std::tie(ExistingSCEV, ID, IP) = findExistingSCEVInCache(Kind, Ops);
3676   if (ExistingSCEV)
3677     return ExistingSCEV;
3678   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3679   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3680   SCEV *S = new (SCEVAllocator) SCEVMinMaxExpr(
3681       ID.Intern(SCEVAllocator), static_cast<SCEVTypes>(Kind), O, Ops.size());
3682 
3683   UniqueSCEVs.InsertNode(S, IP);
3684   addToLoopUseLists(S);
3685   return S;
3686 }
3687 
3688 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) {
3689   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3690   return getSMaxExpr(Ops);
3691 }
3692 
3693 const SCEV *ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3694   return getMinMaxExpr(scSMaxExpr, Ops);
3695 }
3696 
3697 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) {
3698   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3699   return getUMaxExpr(Ops);
3700 }
3701 
3702 const SCEV *ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3703   return getMinMaxExpr(scUMaxExpr, Ops);
3704 }
3705 
3706 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
3707                                          const SCEV *RHS) {
3708   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
3709   return getSMinExpr(Ops);
3710 }
3711 
3712 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) {
3713   return getMinMaxExpr(scSMinExpr, Ops);
3714 }
3715 
3716 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
3717                                          const SCEV *RHS) {
3718   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
3719   return getUMinExpr(Ops);
3720 }
3721 
3722 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops) {
3723   return getMinMaxExpr(scUMinExpr, Ops);
3724 }
3725 
3726 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
3727   // We can bypass creating a target-independent
3728   // constant expression and then folding it back into a ConstantInt.
3729   // This is just a compile-time optimization.
3730   return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
3731 }
3732 
3733 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
3734                                              StructType *STy,
3735                                              unsigned FieldNo) {
3736   // We can bypass creating a target-independent
3737   // constant expression and then folding it back into a ConstantInt.
3738   // This is just a compile-time optimization.
3739   return getConstant(
3740       IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
3741 }
3742 
3743 const SCEV *ScalarEvolution::getUnknown(Value *V) {
3744   // Don't attempt to do anything other than create a SCEVUnknown object
3745   // here.  createSCEV only calls getUnknown after checking for all other
3746   // interesting possibilities, and any other code that calls getUnknown
3747   // is doing so in order to hide a value from SCEV canonicalization.
3748 
3749   FoldingSetNodeID ID;
3750   ID.AddInteger(scUnknown);
3751   ID.AddPointer(V);
3752   void *IP = nullptr;
3753   if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3754     assert(cast<SCEVUnknown>(S)->getValue() == V &&
3755            "Stale SCEVUnknown in uniquing map!");
3756     return S;
3757   }
3758   SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3759                                             FirstUnknown);
3760   FirstUnknown = cast<SCEVUnknown>(S);
3761   UniqueSCEVs.InsertNode(S, IP);
3762   return S;
3763 }
3764 
3765 //===----------------------------------------------------------------------===//
3766 //            Basic SCEV Analysis and PHI Idiom Recognition Code
3767 //
3768 
3769 /// Test if values of the given type are analyzable within the SCEV
3770 /// framework. This primarily includes integer types, and it can optionally
3771 /// include pointer types if the ScalarEvolution class has access to
3772 /// target-specific information.
3773 bool ScalarEvolution::isSCEVable(Type *Ty) const {
3774   // Integers and pointers are always SCEVable.
3775   return Ty->isIntOrPtrTy();
3776 }
3777 
3778 /// Return the size in bits of the specified type, for which isSCEVable must
3779 /// return true.
3780 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
3781   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3782   if (Ty->isPointerTy())
3783     return getDataLayout().getIndexTypeSizeInBits(Ty);
3784   return getDataLayout().getTypeSizeInBits(Ty);
3785 }
3786 
3787 /// Return a type with the same bitwidth as the given type and which represents
3788 /// how SCEV will treat the given type, for which isSCEVable must return
3789 /// true. For pointer types, this is the pointer index sized integer type.
3790 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
3791   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3792 
3793   if (Ty->isIntegerTy())
3794     return Ty;
3795 
3796   // The only other support type is pointer.
3797   assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
3798   return getDataLayout().getIndexType(Ty);
3799 }
3800 
3801 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const {
3802   return  getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
3803 }
3804 
3805 const SCEV *ScalarEvolution::getCouldNotCompute() {
3806   return CouldNotCompute.get();
3807 }
3808 
3809 bool ScalarEvolution::checkValidity(const SCEV *S) const {
3810   bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
3811     auto *SU = dyn_cast<SCEVUnknown>(S);
3812     return SU && SU->getValue() == nullptr;
3813   });
3814 
3815   return !ContainsNulls;
3816 }
3817 
3818 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
3819   HasRecMapType::iterator I = HasRecMap.find(S);
3820   if (I != HasRecMap.end())
3821     return I->second;
3822 
3823   bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>);
3824   HasRecMap.insert({S, FoundAddRec});
3825   return FoundAddRec;
3826 }
3827 
3828 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}.
3829 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an
3830 /// offset I, then return {S', I}, else return {\p S, nullptr}.
3831 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) {
3832   const auto *Add = dyn_cast<SCEVAddExpr>(S);
3833   if (!Add)
3834     return {S, nullptr};
3835 
3836   if (Add->getNumOperands() != 2)
3837     return {S, nullptr};
3838 
3839   auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0));
3840   if (!ConstOp)
3841     return {S, nullptr};
3842 
3843   return {Add->getOperand(1), ConstOp->getValue()};
3844 }
3845 
3846 /// Return the ValueOffsetPair set for \p S. \p S can be represented
3847 /// by the value and offset from any ValueOffsetPair in the set.
3848 SetVector<ScalarEvolution::ValueOffsetPair> *
3849 ScalarEvolution::getSCEVValues(const SCEV *S) {
3850   ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
3851   if (SI == ExprValueMap.end())
3852     return nullptr;
3853 #ifndef NDEBUG
3854   if (VerifySCEVMap) {
3855     // Check there is no dangling Value in the set returned.
3856     for (const auto &VE : SI->second)
3857       assert(ValueExprMap.count(VE.first));
3858   }
3859 #endif
3860   return &SI->second;
3861 }
3862 
3863 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
3864 /// cannot be used separately. eraseValueFromMap should be used to remove
3865 /// V from ValueExprMap and ExprValueMap at the same time.
3866 void ScalarEvolution::eraseValueFromMap(Value *V) {
3867   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3868   if (I != ValueExprMap.end()) {
3869     const SCEV *S = I->second;
3870     // Remove {V, 0} from the set of ExprValueMap[S]
3871     if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S))
3872       SV->remove({V, nullptr});
3873 
3874     // Remove {V, Offset} from the set of ExprValueMap[Stripped]
3875     const SCEV *Stripped;
3876     ConstantInt *Offset;
3877     std::tie(Stripped, Offset) = splitAddExpr(S);
3878     if (Offset != nullptr) {
3879       if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped))
3880         SV->remove({V, Offset});
3881     }
3882     ValueExprMap.erase(V);
3883   }
3884 }
3885 
3886 /// Check whether value has nuw/nsw/exact set but SCEV does not.
3887 /// TODO: In reality it is better to check the poison recursively
3888 /// but this is better than nothing.
3889 static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) {
3890   if (auto *I = dyn_cast<Instruction>(V)) {
3891     if (isa<OverflowingBinaryOperator>(I)) {
3892       if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) {
3893         if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap())
3894           return true;
3895         if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap())
3896           return true;
3897       }
3898     } else if (isa<PossiblyExactOperator>(I) && I->isExact())
3899       return true;
3900   }
3901   return false;
3902 }
3903 
3904 /// Return an existing SCEV if it exists, otherwise analyze the expression and
3905 /// create a new one.
3906 const SCEV *ScalarEvolution::getSCEV(Value *V) {
3907   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3908 
3909   const SCEV *S = getExistingSCEV(V);
3910   if (S == nullptr) {
3911     S = createSCEV(V);
3912     // During PHI resolution, it is possible to create two SCEVs for the same
3913     // V, so it is needed to double check whether V->S is inserted into
3914     // ValueExprMap before insert S->{V, 0} into ExprValueMap.
3915     std::pair<ValueExprMapType::iterator, bool> Pair =
3916         ValueExprMap.insert({SCEVCallbackVH(V, this), S});
3917     if (Pair.second && !SCEVLostPoisonFlags(S, V)) {
3918       ExprValueMap[S].insert({V, nullptr});
3919 
3920       // If S == Stripped + Offset, add Stripped -> {V, Offset} into
3921       // ExprValueMap.
3922       const SCEV *Stripped = S;
3923       ConstantInt *Offset = nullptr;
3924       std::tie(Stripped, Offset) = splitAddExpr(S);
3925       // If stripped is SCEVUnknown, don't bother to save
3926       // Stripped -> {V, offset}. It doesn't simplify and sometimes even
3927       // increase the complexity of the expansion code.
3928       // If V is GetElementPtrInst, don't save Stripped -> {V, offset}
3929       // because it may generate add/sub instead of GEP in SCEV expansion.
3930       if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) &&
3931           !isa<GetElementPtrInst>(V))
3932         ExprValueMap[Stripped].insert({V, Offset});
3933     }
3934   }
3935   return S;
3936 }
3937 
3938 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
3939   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3940 
3941   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3942   if (I != ValueExprMap.end()) {
3943     const SCEV *S = I->second;
3944     if (checkValidity(S))
3945       return S;
3946     eraseValueFromMap(V);
3947     forgetMemoizedResults(S);
3948   }
3949   return nullptr;
3950 }
3951 
3952 /// Return a SCEV corresponding to -V = -1*V
3953 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
3954                                              SCEV::NoWrapFlags Flags) {
3955   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3956     return getConstant(
3957                cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
3958 
3959   Type *Ty = V->getType();
3960   Ty = getEffectiveSCEVType(Ty);
3961   return getMulExpr(
3962       V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags);
3963 }
3964 
3965 /// If Expr computes ~A, return A else return nullptr
3966 static const SCEV *MatchNotExpr(const SCEV *Expr) {
3967   const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
3968   if (!Add || Add->getNumOperands() != 2 ||
3969       !Add->getOperand(0)->isAllOnesValue())
3970     return nullptr;
3971 
3972   const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
3973   if (!AddRHS || AddRHS->getNumOperands() != 2 ||
3974       !AddRHS->getOperand(0)->isAllOnesValue())
3975     return nullptr;
3976 
3977   return AddRHS->getOperand(1);
3978 }
3979 
3980 /// Return a SCEV corresponding to ~V = -1-V
3981 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
3982   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3983     return getConstant(
3984                 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
3985 
3986   // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y)
3987   if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) {
3988     auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) {
3989       SmallVector<const SCEV *, 2> MatchedOperands;
3990       for (const SCEV *Operand : MME->operands()) {
3991         const SCEV *Matched = MatchNotExpr(Operand);
3992         if (!Matched)
3993           return (const SCEV *)nullptr;
3994         MatchedOperands.push_back(Matched);
3995       }
3996       return getMinMaxExpr(
3997           SCEVMinMaxExpr::negate(static_cast<SCEVTypes>(MME->getSCEVType())),
3998           MatchedOperands);
3999     };
4000     if (const SCEV *Replaced = MatchMinMaxNegation(MME))
4001       return Replaced;
4002   }
4003 
4004   Type *Ty = V->getType();
4005   Ty = getEffectiveSCEVType(Ty);
4006   const SCEV *AllOnes =
4007                    getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
4008   return getMinusSCEV(AllOnes, V);
4009 }
4010 
4011 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
4012                                           SCEV::NoWrapFlags Flags,
4013                                           unsigned Depth) {
4014   // Fast path: X - X --> 0.
4015   if (LHS == RHS)
4016     return getZero(LHS->getType());
4017 
4018   // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
4019   // makes it so that we cannot make much use of NUW.
4020   auto AddFlags = SCEV::FlagAnyWrap;
4021   const bool RHSIsNotMinSigned =
4022       !getSignedRangeMin(RHS).isMinSignedValue();
4023   if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) {
4024     // Let M be the minimum representable signed value. Then (-1)*RHS
4025     // signed-wraps if and only if RHS is M. That can happen even for
4026     // a NSW subtraction because e.g. (-1)*M signed-wraps even though
4027     // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
4028     // (-1)*RHS, we need to prove that RHS != M.
4029     //
4030     // If LHS is non-negative and we know that LHS - RHS does not
4031     // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
4032     // either by proving that RHS > M or that LHS >= 0.
4033     if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
4034       AddFlags = SCEV::FlagNSW;
4035     }
4036   }
4037 
4038   // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
4039   // RHS is NSW and LHS >= 0.
4040   //
4041   // The difficulty here is that the NSW flag may have been proven
4042   // relative to a loop that is to be found in a recurrence in LHS and
4043   // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
4044   // larger scope than intended.
4045   auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
4046 
4047   return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
4048 }
4049 
4050 const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty,
4051                                                      unsigned Depth) {
4052   Type *SrcTy = V->getType();
4053   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4054          "Cannot truncate or zero extend with non-integer arguments!");
4055   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4056     return V;  // No conversion
4057   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4058     return getTruncateExpr(V, Ty, Depth);
4059   return getZeroExtendExpr(V, Ty, Depth);
4060 }
4061 
4062 const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty,
4063                                                      unsigned Depth) {
4064   Type *SrcTy = V->getType();
4065   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4066          "Cannot truncate or zero extend with non-integer arguments!");
4067   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4068     return V;  // No conversion
4069   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4070     return getTruncateExpr(V, Ty, Depth);
4071   return getSignExtendExpr(V, Ty, Depth);
4072 }
4073 
4074 const SCEV *
4075 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
4076   Type *SrcTy = V->getType();
4077   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4078          "Cannot noop or zero extend with non-integer arguments!");
4079   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4080          "getNoopOrZeroExtend cannot truncate!");
4081   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4082     return V;  // No conversion
4083   return getZeroExtendExpr(V, Ty);
4084 }
4085 
4086 const SCEV *
4087 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
4088   Type *SrcTy = V->getType();
4089   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4090          "Cannot noop or sign extend with non-integer arguments!");
4091   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4092          "getNoopOrSignExtend cannot truncate!");
4093   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4094     return V;  // No conversion
4095   return getSignExtendExpr(V, Ty);
4096 }
4097 
4098 const SCEV *
4099 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
4100   Type *SrcTy = V->getType();
4101   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4102          "Cannot noop or any extend with non-integer arguments!");
4103   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4104          "getNoopOrAnyExtend cannot truncate!");
4105   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4106     return V;  // No conversion
4107   return getAnyExtendExpr(V, Ty);
4108 }
4109 
4110 const SCEV *
4111 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
4112   Type *SrcTy = V->getType();
4113   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4114          "Cannot truncate or noop with non-integer arguments!");
4115   assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
4116          "getTruncateOrNoop cannot extend!");
4117   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4118     return V;  // No conversion
4119   return getTruncateExpr(V, Ty);
4120 }
4121 
4122 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
4123                                                         const SCEV *RHS) {
4124   const SCEV *PromotedLHS = LHS;
4125   const SCEV *PromotedRHS = RHS;
4126 
4127   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
4128     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
4129   else
4130     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
4131 
4132   return getUMaxExpr(PromotedLHS, PromotedRHS);
4133 }
4134 
4135 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
4136                                                         const SCEV *RHS) {
4137   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
4138   return getUMinFromMismatchedTypes(Ops);
4139 }
4140 
4141 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(
4142     SmallVectorImpl<const SCEV *> &Ops) {
4143   assert(!Ops.empty() && "At least one operand must be!");
4144   // Trivial case.
4145   if (Ops.size() == 1)
4146     return Ops[0];
4147 
4148   // Find the max type first.
4149   Type *MaxType = nullptr;
4150   for (auto *S : Ops)
4151     if (MaxType)
4152       MaxType = getWiderType(MaxType, S->getType());
4153     else
4154       MaxType = S->getType();
4155 
4156   // Extend all ops to max type.
4157   SmallVector<const SCEV *, 2> PromotedOps;
4158   for (auto *S : Ops)
4159     PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType));
4160 
4161   // Generate umin.
4162   return getUMinExpr(PromotedOps);
4163 }
4164 
4165 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
4166   // A pointer operand may evaluate to a nonpointer expression, such as null.
4167   if (!V->getType()->isPointerTy())
4168     return V;
4169 
4170   if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
4171     return getPointerBase(Cast->getOperand());
4172   } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
4173     const SCEV *PtrOp = nullptr;
4174     for (const SCEV *NAryOp : NAry->operands()) {
4175       if (NAryOp->getType()->isPointerTy()) {
4176         // Cannot find the base of an expression with multiple pointer operands.
4177         if (PtrOp)
4178           return V;
4179         PtrOp = NAryOp;
4180       }
4181     }
4182     if (!PtrOp)
4183       return V;
4184     return getPointerBase(PtrOp);
4185   }
4186   return V;
4187 }
4188 
4189 /// Push users of the given Instruction onto the given Worklist.
4190 static void
4191 PushDefUseChildren(Instruction *I,
4192                    SmallVectorImpl<Instruction *> &Worklist) {
4193   // Push the def-use children onto the Worklist stack.
4194   for (User *U : I->users())
4195     Worklist.push_back(cast<Instruction>(U));
4196 }
4197 
4198 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) {
4199   SmallVector<Instruction *, 16> Worklist;
4200   PushDefUseChildren(PN, Worklist);
4201 
4202   SmallPtrSet<Instruction *, 8> Visited;
4203   Visited.insert(PN);
4204   while (!Worklist.empty()) {
4205     Instruction *I = Worklist.pop_back_val();
4206     if (!Visited.insert(I).second)
4207       continue;
4208 
4209     auto It = ValueExprMap.find_as(static_cast<Value *>(I));
4210     if (It != ValueExprMap.end()) {
4211       const SCEV *Old = It->second;
4212 
4213       // Short-circuit the def-use traversal if the symbolic name
4214       // ceases to appear in expressions.
4215       if (Old != SymName && !hasOperand(Old, SymName))
4216         continue;
4217 
4218       // SCEVUnknown for a PHI either means that it has an unrecognized
4219       // structure, it's a PHI that's in the progress of being computed
4220       // by createNodeForPHI, or it's a single-value PHI. In the first case,
4221       // additional loop trip count information isn't going to change anything.
4222       // In the second case, createNodeForPHI will perform the necessary
4223       // updates on its own when it gets to that point. In the third, we do
4224       // want to forget the SCEVUnknown.
4225       if (!isa<PHINode>(I) ||
4226           !isa<SCEVUnknown>(Old) ||
4227           (I != PN && Old == SymName)) {
4228         eraseValueFromMap(It->first);
4229         forgetMemoizedResults(Old);
4230       }
4231     }
4232 
4233     PushDefUseChildren(I, Worklist);
4234   }
4235 }
4236 
4237 namespace {
4238 
4239 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start
4240 /// expression in case its Loop is L. If it is not L then
4241 /// if IgnoreOtherLoops is true then use AddRec itself
4242 /// otherwise rewrite cannot be done.
4243 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4244 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
4245 public:
4246   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
4247                              bool IgnoreOtherLoops = true) {
4248     SCEVInitRewriter Rewriter(L, SE);
4249     const SCEV *Result = Rewriter.visit(S);
4250     if (Rewriter.hasSeenLoopVariantSCEVUnknown())
4251       return SE.getCouldNotCompute();
4252     return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops
4253                ? SE.getCouldNotCompute()
4254                : Result;
4255   }
4256 
4257   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4258     if (!SE.isLoopInvariant(Expr, L))
4259       SeenLoopVariantSCEVUnknown = true;
4260     return Expr;
4261   }
4262 
4263   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4264     // Only re-write AddRecExprs for this loop.
4265     if (Expr->getLoop() == L)
4266       return Expr->getStart();
4267     SeenOtherLoops = true;
4268     return Expr;
4269   }
4270 
4271   bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4272 
4273   bool hasSeenOtherLoops() { return SeenOtherLoops; }
4274 
4275 private:
4276   explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
4277       : SCEVRewriteVisitor(SE), L(L) {}
4278 
4279   const Loop *L;
4280   bool SeenLoopVariantSCEVUnknown = false;
4281   bool SeenOtherLoops = false;
4282 };
4283 
4284 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post
4285 /// increment expression in case its Loop is L. If it is not L then
4286 /// use AddRec itself.
4287 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4288 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> {
4289 public:
4290   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) {
4291     SCEVPostIncRewriter Rewriter(L, SE);
4292     const SCEV *Result = Rewriter.visit(S);
4293     return Rewriter.hasSeenLoopVariantSCEVUnknown()
4294         ? SE.getCouldNotCompute()
4295         : Result;
4296   }
4297 
4298   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4299     if (!SE.isLoopInvariant(Expr, L))
4300       SeenLoopVariantSCEVUnknown = true;
4301     return Expr;
4302   }
4303 
4304   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4305     // Only re-write AddRecExprs for this loop.
4306     if (Expr->getLoop() == L)
4307       return Expr->getPostIncExpr(SE);
4308     SeenOtherLoops = true;
4309     return Expr;
4310   }
4311 
4312   bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4313 
4314   bool hasSeenOtherLoops() { return SeenOtherLoops; }
4315 
4316 private:
4317   explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE)
4318       : SCEVRewriteVisitor(SE), L(L) {}
4319 
4320   const Loop *L;
4321   bool SeenLoopVariantSCEVUnknown = false;
4322   bool SeenOtherLoops = false;
4323 };
4324 
4325 /// This class evaluates the compare condition by matching it against the
4326 /// condition of loop latch. If there is a match we assume a true value
4327 /// for the condition while building SCEV nodes.
4328 class SCEVBackedgeConditionFolder
4329     : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> {
4330 public:
4331   static const SCEV *rewrite(const SCEV *S, const Loop *L,
4332                              ScalarEvolution &SE) {
4333     bool IsPosBECond = false;
4334     Value *BECond = nullptr;
4335     if (BasicBlock *Latch = L->getLoopLatch()) {
4336       BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator());
4337       if (BI && BI->isConditional()) {
4338         assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
4339                "Both outgoing branches should not target same header!");
4340         BECond = BI->getCondition();
4341         IsPosBECond = BI->getSuccessor(0) == L->getHeader();
4342       } else {
4343         return S;
4344       }
4345     }
4346     SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE);
4347     return Rewriter.visit(S);
4348   }
4349 
4350   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4351     const SCEV *Result = Expr;
4352     bool InvariantF = SE.isLoopInvariant(Expr, L);
4353 
4354     if (!InvariantF) {
4355       Instruction *I = cast<Instruction>(Expr->getValue());
4356       switch (I->getOpcode()) {
4357       case Instruction::Select: {
4358         SelectInst *SI = cast<SelectInst>(I);
4359         Optional<const SCEV *> Res =
4360             compareWithBackedgeCondition(SI->getCondition());
4361         if (Res.hasValue()) {
4362           bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne();
4363           Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue());
4364         }
4365         break;
4366       }
4367       default: {
4368         Optional<const SCEV *> Res = compareWithBackedgeCondition(I);
4369         if (Res.hasValue())
4370           Result = Res.getValue();
4371         break;
4372       }
4373       }
4374     }
4375     return Result;
4376   }
4377 
4378 private:
4379   explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond,
4380                                        bool IsPosBECond, ScalarEvolution &SE)
4381       : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond),
4382         IsPositiveBECond(IsPosBECond) {}
4383 
4384   Optional<const SCEV *> compareWithBackedgeCondition(Value *IC);
4385 
4386   const Loop *L;
4387   /// Loop back condition.
4388   Value *BackedgeCond = nullptr;
4389   /// Set to true if loop back is on positive branch condition.
4390   bool IsPositiveBECond;
4391 };
4392 
4393 Optional<const SCEV *>
4394 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) {
4395 
4396   // If value matches the backedge condition for loop latch,
4397   // then return a constant evolution node based on loopback
4398   // branch taken.
4399   if (BackedgeCond == IC)
4400     return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext()))
4401                             : SE.getZero(Type::getInt1Ty(SE.getContext()));
4402   return None;
4403 }
4404 
4405 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
4406 public:
4407   static const SCEV *rewrite(const SCEV *S, const Loop *L,
4408                              ScalarEvolution &SE) {
4409     SCEVShiftRewriter Rewriter(L, SE);
4410     const SCEV *Result = Rewriter.visit(S);
4411     return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
4412   }
4413 
4414   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4415     // Only allow AddRecExprs for this loop.
4416     if (!SE.isLoopInvariant(Expr, L))
4417       Valid = false;
4418     return Expr;
4419   }
4420 
4421   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4422     if (Expr->getLoop() == L && Expr->isAffine())
4423       return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
4424     Valid = false;
4425     return Expr;
4426   }
4427 
4428   bool isValid() { return Valid; }
4429 
4430 private:
4431   explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
4432       : SCEVRewriteVisitor(SE), L(L) {}
4433 
4434   const Loop *L;
4435   bool Valid = true;
4436 };
4437 
4438 } // end anonymous namespace
4439 
4440 SCEV::NoWrapFlags
4441 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
4442   if (!AR->isAffine())
4443     return SCEV::FlagAnyWrap;
4444 
4445   using OBO = OverflowingBinaryOperator;
4446 
4447   SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
4448 
4449   if (!AR->hasNoSignedWrap()) {
4450     ConstantRange AddRecRange = getSignedRange(AR);
4451     ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
4452 
4453     auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4454         Instruction::Add, IncRange, OBO::NoSignedWrap);
4455     if (NSWRegion.contains(AddRecRange))
4456       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
4457   }
4458 
4459   if (!AR->hasNoUnsignedWrap()) {
4460     ConstantRange AddRecRange = getUnsignedRange(AR);
4461     ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
4462 
4463     auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4464         Instruction::Add, IncRange, OBO::NoUnsignedWrap);
4465     if (NUWRegion.contains(AddRecRange))
4466       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
4467   }
4468 
4469   return Result;
4470 }
4471 
4472 namespace {
4473 
4474 /// Represents an abstract binary operation.  This may exist as a
4475 /// normal instruction or constant expression, or may have been
4476 /// derived from an expression tree.
4477 struct BinaryOp {
4478   unsigned Opcode;
4479   Value *LHS;
4480   Value *RHS;
4481   bool IsNSW = false;
4482   bool IsNUW = false;
4483 
4484   /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
4485   /// constant expression.
4486   Operator *Op = nullptr;
4487 
4488   explicit BinaryOp(Operator *Op)
4489       : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
4490         Op(Op) {
4491     if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
4492       IsNSW = OBO->hasNoSignedWrap();
4493       IsNUW = OBO->hasNoUnsignedWrap();
4494     }
4495   }
4496 
4497   explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
4498                     bool IsNUW = false)
4499       : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {}
4500 };
4501 
4502 } // end anonymous namespace
4503 
4504 /// Try to map \p V into a BinaryOp, and return \c None on failure.
4505 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) {
4506   auto *Op = dyn_cast<Operator>(V);
4507   if (!Op)
4508     return None;
4509 
4510   // Recognise intrinsic loop.decrement.reg, and as this has exactly the same
4511   // semantics as a Sub, return a binary sub expression.
4512   if (auto *II = dyn_cast<IntrinsicInst>(V)) {
4513     switch (II->getIntrinsicID()) {
4514     case Intrinsic::loop_decrement_reg:
4515       return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1));
4516     default:
4517       return None;
4518     }
4519   }
4520 
4521   // Implementation detail: all the cleverness here should happen without
4522   // creating new SCEV expressions -- our caller knowns tricks to avoid creating
4523   // SCEV expressions when possible, and we should not break that.
4524 
4525   switch (Op->getOpcode()) {
4526   case Instruction::Add:
4527   case Instruction::Sub:
4528   case Instruction::Mul:
4529   case Instruction::UDiv:
4530   case Instruction::URem:
4531   case Instruction::And:
4532   case Instruction::Or:
4533   case Instruction::AShr:
4534   case Instruction::Shl:
4535     return BinaryOp(Op);
4536 
4537   case Instruction::Xor:
4538     if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
4539       // If the RHS of the xor is a signmask, then this is just an add.
4540       // Instcombine turns add of signmask into xor as a strength reduction step.
4541       if (RHSC->getValue().isSignMask())
4542         return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
4543     return BinaryOp(Op);
4544 
4545   case Instruction::LShr:
4546     // Turn logical shift right of a constant into a unsigned divide.
4547     if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
4548       uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
4549 
4550       // If the shift count is not less than the bitwidth, the result of
4551       // the shift is undefined. Don't try to analyze it, because the
4552       // resolution chosen here may differ from the resolution chosen in
4553       // other parts of the compiler.
4554       if (SA->getValue().ult(BitWidth)) {
4555         Constant *X =
4556             ConstantInt::get(SA->getContext(),
4557                              APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
4558         return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
4559       }
4560     }
4561     return BinaryOp(Op);
4562 
4563   case Instruction::ExtractValue: {
4564     auto *EVI = cast<ExtractValueInst>(Op);
4565     if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
4566       break;
4567 
4568     auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand());
4569     if (!WO)
4570       break;
4571 
4572     Instruction::BinaryOps BinOp = WO->getBinaryOp();
4573     bool Signed = WO->isSigned();
4574     // TODO: Should add nuw/nsw flags for mul as well.
4575     if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT))
4576       return BinaryOp(BinOp, WO->getLHS(), WO->getRHS());
4577 
4578     // Now that we know that all uses of the arithmetic-result component of
4579     // CI are guarded by the overflow check, we can go ahead and pretend
4580     // that the arithmetic is non-overflowing.
4581     return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(),
4582                     /* IsNSW = */ Signed, /* IsNUW = */ !Signed);
4583   }
4584 
4585   default:
4586     break;
4587   }
4588 
4589   return None;
4590 }
4591 
4592 /// Helper function to createAddRecFromPHIWithCasts. We have a phi
4593 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
4594 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
4595 /// way. This function checks if \p Op, an operand of this SCEVAddExpr,
4596 /// follows one of the following patterns:
4597 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4598 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4599 /// If the SCEV expression of \p Op conforms with one of the expected patterns
4600 /// we return the type of the truncation operation, and indicate whether the
4601 /// truncated type should be treated as signed/unsigned by setting
4602 /// \p Signed to true/false, respectively.
4603 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
4604                                bool &Signed, ScalarEvolution &SE) {
4605   // The case where Op == SymbolicPHI (that is, with no type conversions on
4606   // the way) is handled by the regular add recurrence creating logic and
4607   // would have already been triggered in createAddRecForPHI. Reaching it here
4608   // means that createAddRecFromPHI had failed for this PHI before (e.g.,
4609   // because one of the other operands of the SCEVAddExpr updating this PHI is
4610   // not invariant).
4611   //
4612   // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
4613   // this case predicates that allow us to prove that Op == SymbolicPHI will
4614   // be added.
4615   if (Op == SymbolicPHI)
4616     return nullptr;
4617 
4618   unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
4619   unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
4620   if (SourceBits != NewBits)
4621     return nullptr;
4622 
4623   const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op);
4624   const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op);
4625   if (!SExt && !ZExt)
4626     return nullptr;
4627   const SCEVTruncateExpr *Trunc =
4628       SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand())
4629            : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand());
4630   if (!Trunc)
4631     return nullptr;
4632   const SCEV *X = Trunc->getOperand();
4633   if (X != SymbolicPHI)
4634     return nullptr;
4635   Signed = SExt != nullptr;
4636   return Trunc->getType();
4637 }
4638 
4639 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
4640   if (!PN->getType()->isIntegerTy())
4641     return nullptr;
4642   const Loop *L = LI.getLoopFor(PN->getParent());
4643   if (!L || L->getHeader() != PN->getParent())
4644     return nullptr;
4645   return L;
4646 }
4647 
4648 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
4649 // computation that updates the phi follows the following pattern:
4650 //   (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
4651 // which correspond to a phi->trunc->sext/zext->add->phi update chain.
4652 // If so, try to see if it can be rewritten as an AddRecExpr under some
4653 // Predicates. If successful, return them as a pair. Also cache the results
4654 // of the analysis.
4655 //
4656 // Example usage scenario:
4657 //    Say the Rewriter is called for the following SCEV:
4658 //         8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4659 //    where:
4660 //         %X = phi i64 (%Start, %BEValue)
4661 //    It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
4662 //    and call this function with %SymbolicPHI = %X.
4663 //
4664 //    The analysis will find that the value coming around the backedge has
4665 //    the following SCEV:
4666 //         BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4667 //    Upon concluding that this matches the desired pattern, the function
4668 //    will return the pair {NewAddRec, SmallPredsVec} where:
4669 //         NewAddRec = {%Start,+,%Step}
4670 //         SmallPredsVec = {P1, P2, P3} as follows:
4671 //           P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
4672 //           P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
4673 //           P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
4674 //    The returned pair means that SymbolicPHI can be rewritten into NewAddRec
4675 //    under the predicates {P1,P2,P3}.
4676 //    This predicated rewrite will be cached in PredicatedSCEVRewrites:
4677 //         PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
4678 //
4679 // TODO's:
4680 //
4681 // 1) Extend the Induction descriptor to also support inductions that involve
4682 //    casts: When needed (namely, when we are called in the context of the
4683 //    vectorizer induction analysis), a Set of cast instructions will be
4684 //    populated by this method, and provided back to isInductionPHI. This is
4685 //    needed to allow the vectorizer to properly record them to be ignored by
4686 //    the cost model and to avoid vectorizing them (otherwise these casts,
4687 //    which are redundant under the runtime overflow checks, will be
4688 //    vectorized, which can be costly).
4689 //
4690 // 2) Support additional induction/PHISCEV patterns: We also want to support
4691 //    inductions where the sext-trunc / zext-trunc operations (partly) occur
4692 //    after the induction update operation (the induction increment):
4693 //
4694 //      (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
4695 //    which correspond to a phi->add->trunc->sext/zext->phi update chain.
4696 //
4697 //      (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
4698 //    which correspond to a phi->trunc->add->sext/zext->phi update chain.
4699 //
4700 // 3) Outline common code with createAddRecFromPHI to avoid duplication.
4701 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4702 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
4703   SmallVector<const SCEVPredicate *, 3> Predicates;
4704 
4705   // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
4706   // return an AddRec expression under some predicate.
4707 
4708   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
4709   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
4710   assert(L && "Expecting an integer loop header phi");
4711 
4712   // The loop may have multiple entrances or multiple exits; we can analyze
4713   // this phi as an addrec if it has a unique entry value and a unique
4714   // backedge value.
4715   Value *BEValueV = nullptr, *StartValueV = nullptr;
4716   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4717     Value *V = PN->getIncomingValue(i);
4718     if (L->contains(PN->getIncomingBlock(i))) {
4719       if (!BEValueV) {
4720         BEValueV = V;
4721       } else if (BEValueV != V) {
4722         BEValueV = nullptr;
4723         break;
4724       }
4725     } else if (!StartValueV) {
4726       StartValueV = V;
4727     } else if (StartValueV != V) {
4728       StartValueV = nullptr;
4729       break;
4730     }
4731   }
4732   if (!BEValueV || !StartValueV)
4733     return None;
4734 
4735   const SCEV *BEValue = getSCEV(BEValueV);
4736 
4737   // If the value coming around the backedge is an add with the symbolic
4738   // value we just inserted, possibly with casts that we can ignore under
4739   // an appropriate runtime guard, then we found a simple induction variable!
4740   const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
4741   if (!Add)
4742     return None;
4743 
4744   // If there is a single occurrence of the symbolic value, possibly
4745   // casted, replace it with a recurrence.
4746   unsigned FoundIndex = Add->getNumOperands();
4747   Type *TruncTy = nullptr;
4748   bool Signed;
4749   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4750     if ((TruncTy =
4751              isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
4752       if (FoundIndex == e) {
4753         FoundIndex = i;
4754         break;
4755       }
4756 
4757   if (FoundIndex == Add->getNumOperands())
4758     return None;
4759 
4760   // Create an add with everything but the specified operand.
4761   SmallVector<const SCEV *, 8> Ops;
4762   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4763     if (i != FoundIndex)
4764       Ops.push_back(Add->getOperand(i));
4765   const SCEV *Accum = getAddExpr(Ops);
4766 
4767   // The runtime checks will not be valid if the step amount is
4768   // varying inside the loop.
4769   if (!isLoopInvariant(Accum, L))
4770     return None;
4771 
4772   // *** Part2: Create the predicates
4773 
4774   // Analysis was successful: we have a phi-with-cast pattern for which we
4775   // can return an AddRec expression under the following predicates:
4776   //
4777   // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
4778   //     fits within the truncated type (does not overflow) for i = 0 to n-1.
4779   // P2: An Equal predicate that guarantees that
4780   //     Start = (Ext ix (Trunc iy (Start) to ix) to iy)
4781   // P3: An Equal predicate that guarantees that
4782   //     Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
4783   //
4784   // As we next prove, the above predicates guarantee that:
4785   //     Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
4786   //
4787   //
4788   // More formally, we want to prove that:
4789   //     Expr(i+1) = Start + (i+1) * Accum
4790   //               = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4791   //
4792   // Given that:
4793   // 1) Expr(0) = Start
4794   // 2) Expr(1) = Start + Accum
4795   //            = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
4796   // 3) Induction hypothesis (step i):
4797   //    Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
4798   //
4799   // Proof:
4800   //  Expr(i+1) =
4801   //   = Start + (i+1)*Accum
4802   //   = (Start + i*Accum) + Accum
4803   //   = Expr(i) + Accum
4804   //   = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
4805   //                                                             :: from step i
4806   //
4807   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
4808   //
4809   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
4810   //     + (Ext ix (Trunc iy (Accum) to ix) to iy)
4811   //     + Accum                                                     :: from P3
4812   //
4813   //   = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
4814   //     + Accum                            :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
4815   //
4816   //   = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
4817   //   = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4818   //
4819   // By induction, the same applies to all iterations 1<=i<n:
4820   //
4821 
4822   // Create a truncated addrec for which we will add a no overflow check (P1).
4823   const SCEV *StartVal = getSCEV(StartValueV);
4824   const SCEV *PHISCEV =
4825       getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
4826                     getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap);
4827 
4828   // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
4829   // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
4830   // will be constant.
4831   //
4832   //  If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
4833   // add P1.
4834   if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
4835     SCEVWrapPredicate::IncrementWrapFlags AddedFlags =
4836         Signed ? SCEVWrapPredicate::IncrementNSSW
4837                : SCEVWrapPredicate::IncrementNUSW;
4838     const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
4839     Predicates.push_back(AddRecPred);
4840   }
4841 
4842   // Create the Equal Predicates P2,P3:
4843 
4844   // It is possible that the predicates P2 and/or P3 are computable at
4845   // compile time due to StartVal and/or Accum being constants.
4846   // If either one is, then we can check that now and escape if either P2
4847   // or P3 is false.
4848 
4849   // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
4850   // for each of StartVal and Accum
4851   auto getExtendedExpr = [&](const SCEV *Expr,
4852                              bool CreateSignExtend) -> const SCEV * {
4853     assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant");
4854     const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
4855     const SCEV *ExtendedExpr =
4856         CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType())
4857                          : getZeroExtendExpr(TruncatedExpr, Expr->getType());
4858     return ExtendedExpr;
4859   };
4860 
4861   // Given:
4862   //  ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
4863   //               = getExtendedExpr(Expr)
4864   // Determine whether the predicate P: Expr == ExtendedExpr
4865   // is known to be false at compile time
4866   auto PredIsKnownFalse = [&](const SCEV *Expr,
4867                               const SCEV *ExtendedExpr) -> bool {
4868     return Expr != ExtendedExpr &&
4869            isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr);
4870   };
4871 
4872   const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
4873   if (PredIsKnownFalse(StartVal, StartExtended)) {
4874     LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";);
4875     return None;
4876   }
4877 
4878   // The Step is always Signed (because the overflow checks are either
4879   // NSSW or NUSW)
4880   const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true);
4881   if (PredIsKnownFalse(Accum, AccumExtended)) {
4882     LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";);
4883     return None;
4884   }
4885 
4886   auto AppendPredicate = [&](const SCEV *Expr,
4887                              const SCEV *ExtendedExpr) -> void {
4888     if (Expr != ExtendedExpr &&
4889         !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
4890       const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
4891       LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred);
4892       Predicates.push_back(Pred);
4893     }
4894   };
4895 
4896   AppendPredicate(StartVal, StartExtended);
4897   AppendPredicate(Accum, AccumExtended);
4898 
4899   // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
4900   // which the casts had been folded away. The caller can rewrite SymbolicPHI
4901   // into NewAR if it will also add the runtime overflow checks specified in
4902   // Predicates.
4903   auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap);
4904 
4905   std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
4906       std::make_pair(NewAR, Predicates);
4907   // Remember the result of the analysis for this SCEV at this locayyytion.
4908   PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
4909   return PredRewrite;
4910 }
4911 
4912 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4913 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) {
4914   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
4915   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
4916   if (!L)
4917     return None;
4918 
4919   // Check to see if we already analyzed this PHI.
4920   auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
4921   if (I != PredicatedSCEVRewrites.end()) {
4922     std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
4923         I->second;
4924     // Analysis was done before and failed to create an AddRec:
4925     if (Rewrite.first == SymbolicPHI)
4926       return None;
4927     // Analysis was done before and succeeded to create an AddRec under
4928     // a predicate:
4929     assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec");
4930     assert(!(Rewrite.second).empty() && "Expected to find Predicates");
4931     return Rewrite;
4932   }
4933 
4934   Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4935     Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
4936 
4937   // Record in the cache that the analysis failed
4938   if (!Rewrite) {
4939     SmallVector<const SCEVPredicate *, 3> Predicates;
4940     PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
4941     return None;
4942   }
4943 
4944   return Rewrite;
4945 }
4946 
4947 // FIXME: This utility is currently required because the Rewriter currently
4948 // does not rewrite this expression:
4949 // {0, +, (sext ix (trunc iy to ix) to iy)}
4950 // into {0, +, %step},
4951 // even when the following Equal predicate exists:
4952 // "%step == (sext ix (trunc iy to ix) to iy)".
4953 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds(
4954     const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const {
4955   if (AR1 == AR2)
4956     return true;
4957 
4958   auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool {
4959     if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) &&
4960         !Preds.implies(SE.getEqualPredicate(Expr2, Expr1)))
4961       return false;
4962     return true;
4963   };
4964 
4965   if (!areExprsEqual(AR1->getStart(), AR2->getStart()) ||
4966       !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE)))
4967     return false;
4968   return true;
4969 }
4970 
4971 /// A helper function for createAddRecFromPHI to handle simple cases.
4972 ///
4973 /// This function tries to find an AddRec expression for the simplest (yet most
4974 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
4975 /// If it fails, createAddRecFromPHI will use a more general, but slow,
4976 /// technique for finding the AddRec expression.
4977 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
4978                                                       Value *BEValueV,
4979                                                       Value *StartValueV) {
4980   const Loop *L = LI.getLoopFor(PN->getParent());
4981   assert(L && L->getHeader() == PN->getParent());
4982   assert(BEValueV && StartValueV);
4983 
4984   auto BO = MatchBinaryOp(BEValueV, DT);
4985   if (!BO)
4986     return nullptr;
4987 
4988   if (BO->Opcode != Instruction::Add)
4989     return nullptr;
4990 
4991   const SCEV *Accum = nullptr;
4992   if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
4993     Accum = getSCEV(BO->RHS);
4994   else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
4995     Accum = getSCEV(BO->LHS);
4996 
4997   if (!Accum)
4998     return nullptr;
4999 
5000   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5001   if (BO->IsNUW)
5002     Flags = setFlags(Flags, SCEV::FlagNUW);
5003   if (BO->IsNSW)
5004     Flags = setFlags(Flags, SCEV::FlagNSW);
5005 
5006   const SCEV *StartVal = getSCEV(StartValueV);
5007   const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5008 
5009   ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
5010 
5011   // We can add Flags to the post-inc expression only if we
5012   // know that it is *undefined behavior* for BEValueV to
5013   // overflow.
5014   if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5015     if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5016       (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5017 
5018   return PHISCEV;
5019 }
5020 
5021 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
5022   const Loop *L = LI.getLoopFor(PN->getParent());
5023   if (!L || L->getHeader() != PN->getParent())
5024     return nullptr;
5025 
5026   // The loop may have multiple entrances or multiple exits; we can analyze
5027   // this phi as an addrec if it has a unique entry value and a unique
5028   // backedge value.
5029   Value *BEValueV = nullptr, *StartValueV = nullptr;
5030   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5031     Value *V = PN->getIncomingValue(i);
5032     if (L->contains(PN->getIncomingBlock(i))) {
5033       if (!BEValueV) {
5034         BEValueV = V;
5035       } else if (BEValueV != V) {
5036         BEValueV = nullptr;
5037         break;
5038       }
5039     } else if (!StartValueV) {
5040       StartValueV = V;
5041     } else if (StartValueV != V) {
5042       StartValueV = nullptr;
5043       break;
5044     }
5045   }
5046   if (!BEValueV || !StartValueV)
5047     return nullptr;
5048 
5049   assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
5050          "PHI node already processed?");
5051 
5052   // First, try to find AddRec expression without creating a fictituos symbolic
5053   // value for PN.
5054   if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
5055     return S;
5056 
5057   // Handle PHI node value symbolically.
5058   const SCEV *SymbolicName = getUnknown(PN);
5059   ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName});
5060 
5061   // Using this symbolic name for the PHI, analyze the value coming around
5062   // the back-edge.
5063   const SCEV *BEValue = getSCEV(BEValueV);
5064 
5065   // NOTE: If BEValue is loop invariant, we know that the PHI node just
5066   // has a special value for the first iteration of the loop.
5067 
5068   // If the value coming around the backedge is an add with the symbolic
5069   // value we just inserted, then we found a simple induction variable!
5070   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
5071     // If there is a single occurrence of the symbolic value, replace it
5072     // with a recurrence.
5073     unsigned FoundIndex = Add->getNumOperands();
5074     for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5075       if (Add->getOperand(i) == SymbolicName)
5076         if (FoundIndex == e) {
5077           FoundIndex = i;
5078           break;
5079         }
5080 
5081     if (FoundIndex != Add->getNumOperands()) {
5082       // Create an add with everything but the specified operand.
5083       SmallVector<const SCEV *, 8> Ops;
5084       for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5085         if (i != FoundIndex)
5086           Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i),
5087                                                              L, *this));
5088       const SCEV *Accum = getAddExpr(Ops);
5089 
5090       // This is not a valid addrec if the step amount is varying each
5091       // loop iteration, but is not itself an addrec in this loop.
5092       if (isLoopInvariant(Accum, L) ||
5093           (isa<SCEVAddRecExpr>(Accum) &&
5094            cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
5095         SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5096 
5097         if (auto BO = MatchBinaryOp(BEValueV, DT)) {
5098           if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
5099             if (BO->IsNUW)
5100               Flags = setFlags(Flags, SCEV::FlagNUW);
5101             if (BO->IsNSW)
5102               Flags = setFlags(Flags, SCEV::FlagNSW);
5103           }
5104         } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
5105           // If the increment is an inbounds GEP, then we know the address
5106           // space cannot be wrapped around. We cannot make any guarantee
5107           // about signed or unsigned overflow because pointers are
5108           // unsigned but we may have a negative index from the base
5109           // pointer. We can guarantee that no unsigned wrap occurs if the
5110           // indices form a positive value.
5111           if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
5112             Flags = setFlags(Flags, SCEV::FlagNW);
5113 
5114             const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
5115             if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
5116               Flags = setFlags(Flags, SCEV::FlagNUW);
5117           }
5118 
5119           // We cannot transfer nuw and nsw flags from subtraction
5120           // operations -- sub nuw X, Y is not the same as add nuw X, -Y
5121           // for instance.
5122         }
5123 
5124         const SCEV *StartVal = getSCEV(StartValueV);
5125         const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5126 
5127         // Okay, for the entire analysis of this edge we assumed the PHI
5128         // to be symbolic.  We now need to go back and purge all of the
5129         // entries for the scalars that use the symbolic expression.
5130         forgetSymbolicName(PN, SymbolicName);
5131         ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
5132 
5133         // We can add Flags to the post-inc expression only if we
5134         // know that it is *undefined behavior* for BEValueV to
5135         // overflow.
5136         if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5137           if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5138             (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5139 
5140         return PHISCEV;
5141       }
5142     }
5143   } else {
5144     // Otherwise, this could be a loop like this:
5145     //     i = 0;  for (j = 1; ..; ++j) { ....  i = j; }
5146     // In this case, j = {1,+,1}  and BEValue is j.
5147     // Because the other in-value of i (0) fits the evolution of BEValue
5148     // i really is an addrec evolution.
5149     //
5150     // We can generalize this saying that i is the shifted value of BEValue
5151     // by one iteration:
5152     //   PHI(f(0), f({1,+,1})) --> f({0,+,1})
5153     const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
5154     const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false);
5155     if (Shifted != getCouldNotCompute() &&
5156         Start != getCouldNotCompute()) {
5157       const SCEV *StartVal = getSCEV(StartValueV);
5158       if (Start == StartVal) {
5159         // Okay, for the entire analysis of this edge we assumed the PHI
5160         // to be symbolic.  We now need to go back and purge all of the
5161         // entries for the scalars that use the symbolic expression.
5162         forgetSymbolicName(PN, SymbolicName);
5163         ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted;
5164         return Shifted;
5165       }
5166     }
5167   }
5168 
5169   // Remove the temporary PHI node SCEV that has been inserted while intending
5170   // to create an AddRecExpr for this PHI node. We can not keep this temporary
5171   // as it will prevent later (possibly simpler) SCEV expressions to be added
5172   // to the ValueExprMap.
5173   eraseValueFromMap(PN);
5174 
5175   return nullptr;
5176 }
5177 
5178 // Checks if the SCEV S is available at BB.  S is considered available at BB
5179 // if S can be materialized at BB without introducing a fault.
5180 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
5181                                BasicBlock *BB) {
5182   struct CheckAvailable {
5183     bool TraversalDone = false;
5184     bool Available = true;
5185 
5186     const Loop *L = nullptr;  // The loop BB is in (can be nullptr)
5187     BasicBlock *BB = nullptr;
5188     DominatorTree &DT;
5189 
5190     CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
5191       : L(L), BB(BB), DT(DT) {}
5192 
5193     bool setUnavailable() {
5194       TraversalDone = true;
5195       Available = false;
5196       return false;
5197     }
5198 
5199     bool follow(const SCEV *S) {
5200       switch (S->getSCEVType()) {
5201       case scConstant: case scTruncate: case scZeroExtend: case scSignExtend:
5202       case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr:
5203       case scUMinExpr:
5204       case scSMinExpr:
5205         // These expressions are available if their operand(s) is/are.
5206         return true;
5207 
5208       case scAddRecExpr: {
5209         // We allow add recurrences that are on the loop BB is in, or some
5210         // outer loop.  This guarantees availability because the value of the
5211         // add recurrence at BB is simply the "current" value of the induction
5212         // variable.  We can relax this in the future; for instance an add
5213         // recurrence on a sibling dominating loop is also available at BB.
5214         const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
5215         if (L && (ARLoop == L || ARLoop->contains(L)))
5216           return true;
5217 
5218         return setUnavailable();
5219       }
5220 
5221       case scUnknown: {
5222         // For SCEVUnknown, we check for simple dominance.
5223         const auto *SU = cast<SCEVUnknown>(S);
5224         Value *V = SU->getValue();
5225 
5226         if (isa<Argument>(V))
5227           return false;
5228 
5229         if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
5230           return false;
5231 
5232         return setUnavailable();
5233       }
5234 
5235       case scUDivExpr:
5236       case scCouldNotCompute:
5237         // We do not try to smart about these at all.
5238         return setUnavailable();
5239       }
5240       llvm_unreachable("switch should be fully covered!");
5241     }
5242 
5243     bool isDone() { return TraversalDone; }
5244   };
5245 
5246   CheckAvailable CA(L, BB, DT);
5247   SCEVTraversal<CheckAvailable> ST(CA);
5248 
5249   ST.visitAll(S);
5250   return CA.Available;
5251 }
5252 
5253 // Try to match a control flow sequence that branches out at BI and merges back
5254 // at Merge into a "C ? LHS : RHS" select pattern.  Return true on a successful
5255 // match.
5256 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
5257                           Value *&C, Value *&LHS, Value *&RHS) {
5258   C = BI->getCondition();
5259 
5260   BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
5261   BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
5262 
5263   if (!LeftEdge.isSingleEdge())
5264     return false;
5265 
5266   assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
5267 
5268   Use &LeftUse = Merge->getOperandUse(0);
5269   Use &RightUse = Merge->getOperandUse(1);
5270 
5271   if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
5272     LHS = LeftUse;
5273     RHS = RightUse;
5274     return true;
5275   }
5276 
5277   if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
5278     LHS = RightUse;
5279     RHS = LeftUse;
5280     return true;
5281   }
5282 
5283   return false;
5284 }
5285 
5286 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
5287   auto IsReachable =
5288       [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
5289   if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
5290     const Loop *L = LI.getLoopFor(PN->getParent());
5291 
5292     // We don't want to break LCSSA, even in a SCEV expression tree.
5293     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
5294       if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
5295         return nullptr;
5296 
5297     // Try to match
5298     //
5299     //  br %cond, label %left, label %right
5300     // left:
5301     //  br label %merge
5302     // right:
5303     //  br label %merge
5304     // merge:
5305     //  V = phi [ %x, %left ], [ %y, %right ]
5306     //
5307     // as "select %cond, %x, %y"
5308 
5309     BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
5310     assert(IDom && "At least the entry block should dominate PN");
5311 
5312     auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
5313     Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
5314 
5315     if (BI && BI->isConditional() &&
5316         BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
5317         IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
5318         IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
5319       return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
5320   }
5321 
5322   return nullptr;
5323 }
5324 
5325 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
5326   if (const SCEV *S = createAddRecFromPHI(PN))
5327     return S;
5328 
5329   if (const SCEV *S = createNodeFromSelectLikePHI(PN))
5330     return S;
5331 
5332   // If the PHI has a single incoming value, follow that value, unless the
5333   // PHI's incoming blocks are in a different loop, in which case doing so
5334   // risks breaking LCSSA form. Instcombine would normally zap these, but
5335   // it doesn't have DominatorTree information, so it may miss cases.
5336   if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC}))
5337     if (LI.replacementPreservesLCSSAForm(PN, V))
5338       return getSCEV(V);
5339 
5340   // If it's not a loop phi, we can't handle it yet.
5341   return getUnknown(PN);
5342 }
5343 
5344 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I,
5345                                                       Value *Cond,
5346                                                       Value *TrueVal,
5347                                                       Value *FalseVal) {
5348   // Handle "constant" branch or select. This can occur for instance when a
5349   // loop pass transforms an inner loop and moves on to process the outer loop.
5350   if (auto *CI = dyn_cast<ConstantInt>(Cond))
5351     return getSCEV(CI->isOne() ? TrueVal : FalseVal);
5352 
5353   // Try to match some simple smax or umax patterns.
5354   auto *ICI = dyn_cast<ICmpInst>(Cond);
5355   if (!ICI)
5356     return getUnknown(I);
5357 
5358   Value *LHS = ICI->getOperand(0);
5359   Value *RHS = ICI->getOperand(1);
5360 
5361   switch (ICI->getPredicate()) {
5362   case ICmpInst::ICMP_SLT:
5363   case ICmpInst::ICMP_SLE:
5364     std::swap(LHS, RHS);
5365     LLVM_FALLTHROUGH;
5366   case ICmpInst::ICMP_SGT:
5367   case ICmpInst::ICMP_SGE:
5368     // a >s b ? a+x : b+x  ->  smax(a, b)+x
5369     // a >s b ? b+x : a+x  ->  smin(a, b)+x
5370     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5371       const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType());
5372       const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType());
5373       const SCEV *LA = getSCEV(TrueVal);
5374       const SCEV *RA = getSCEV(FalseVal);
5375       const SCEV *LDiff = getMinusSCEV(LA, LS);
5376       const SCEV *RDiff = getMinusSCEV(RA, RS);
5377       if (LDiff == RDiff)
5378         return getAddExpr(getSMaxExpr(LS, RS), LDiff);
5379       LDiff = getMinusSCEV(LA, RS);
5380       RDiff = getMinusSCEV(RA, LS);
5381       if (LDiff == RDiff)
5382         return getAddExpr(getSMinExpr(LS, RS), LDiff);
5383     }
5384     break;
5385   case ICmpInst::ICMP_ULT:
5386   case ICmpInst::ICMP_ULE:
5387     std::swap(LHS, RHS);
5388     LLVM_FALLTHROUGH;
5389   case ICmpInst::ICMP_UGT:
5390   case ICmpInst::ICMP_UGE:
5391     // a >u b ? a+x : b+x  ->  umax(a, b)+x
5392     // a >u b ? b+x : a+x  ->  umin(a, b)+x
5393     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5394       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5395       const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType());
5396       const SCEV *LA = getSCEV(TrueVal);
5397       const SCEV *RA = getSCEV(FalseVal);
5398       const SCEV *LDiff = getMinusSCEV(LA, LS);
5399       const SCEV *RDiff = getMinusSCEV(RA, RS);
5400       if (LDiff == RDiff)
5401         return getAddExpr(getUMaxExpr(LS, RS), LDiff);
5402       LDiff = getMinusSCEV(LA, RS);
5403       RDiff = getMinusSCEV(RA, LS);
5404       if (LDiff == RDiff)
5405         return getAddExpr(getUMinExpr(LS, RS), LDiff);
5406     }
5407     break;
5408   case ICmpInst::ICMP_NE:
5409     // n != 0 ? n+x : 1+x  ->  umax(n, 1)+x
5410     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5411         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5412       const SCEV *One = getOne(I->getType());
5413       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5414       const SCEV *LA = getSCEV(TrueVal);
5415       const SCEV *RA = getSCEV(FalseVal);
5416       const SCEV *LDiff = getMinusSCEV(LA, LS);
5417       const SCEV *RDiff = getMinusSCEV(RA, One);
5418       if (LDiff == RDiff)
5419         return getAddExpr(getUMaxExpr(One, LS), LDiff);
5420     }
5421     break;
5422   case ICmpInst::ICMP_EQ:
5423     // n == 0 ? 1+x : n+x  ->  umax(n, 1)+x
5424     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5425         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5426       const SCEV *One = getOne(I->getType());
5427       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5428       const SCEV *LA = getSCEV(TrueVal);
5429       const SCEV *RA = getSCEV(FalseVal);
5430       const SCEV *LDiff = getMinusSCEV(LA, One);
5431       const SCEV *RDiff = getMinusSCEV(RA, LS);
5432       if (LDiff == RDiff)
5433         return getAddExpr(getUMaxExpr(One, LS), LDiff);
5434     }
5435     break;
5436   default:
5437     break;
5438   }
5439 
5440   return getUnknown(I);
5441 }
5442 
5443 /// Expand GEP instructions into add and multiply operations. This allows them
5444 /// to be analyzed by regular SCEV code.
5445 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
5446   // Don't attempt to analyze GEPs over unsized objects.
5447   if (!GEP->getSourceElementType()->isSized())
5448     return getUnknown(GEP);
5449 
5450   SmallVector<const SCEV *, 4> IndexExprs;
5451   for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
5452     IndexExprs.push_back(getSCEV(*Index));
5453   return getGEPExpr(GEP, IndexExprs);
5454 }
5455 
5456 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) {
5457   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5458     return C->getAPInt().countTrailingZeros();
5459 
5460   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
5461     return std::min(GetMinTrailingZeros(T->getOperand()),
5462                     (uint32_t)getTypeSizeInBits(T->getType()));
5463 
5464   if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
5465     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5466     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5467                ? getTypeSizeInBits(E->getType())
5468                : OpRes;
5469   }
5470 
5471   if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
5472     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5473     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5474                ? getTypeSizeInBits(E->getType())
5475                : OpRes;
5476   }
5477 
5478   if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
5479     // The result is the min of all operands results.
5480     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5481     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5482       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5483     return MinOpRes;
5484   }
5485 
5486   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
5487     // The result is the sum of all operands results.
5488     uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
5489     uint32_t BitWidth = getTypeSizeInBits(M->getType());
5490     for (unsigned i = 1, e = M->getNumOperands();
5491          SumOpRes != BitWidth && i != e; ++i)
5492       SumOpRes =
5493           std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth);
5494     return SumOpRes;
5495   }
5496 
5497   if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
5498     // The result is the min of all operands results.
5499     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5500     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5501       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5502     return MinOpRes;
5503   }
5504 
5505   if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
5506     // The result is the min of all operands results.
5507     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5508     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5509       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5510     return MinOpRes;
5511   }
5512 
5513   if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
5514     // The result is the min of all operands results.
5515     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5516     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5517       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5518     return MinOpRes;
5519   }
5520 
5521   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5522     // For a SCEVUnknown, ask ValueTracking.
5523     KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT);
5524     return Known.countMinTrailingZeros();
5525   }
5526 
5527   // SCEVUDivExpr
5528   return 0;
5529 }
5530 
5531 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
5532   auto I = MinTrailingZerosCache.find(S);
5533   if (I != MinTrailingZerosCache.end())
5534     return I->second;
5535 
5536   uint32_t Result = GetMinTrailingZerosImpl(S);
5537   auto InsertPair = MinTrailingZerosCache.insert({S, Result});
5538   assert(InsertPair.second && "Should insert a new key");
5539   return InsertPair.first->second;
5540 }
5541 
5542 /// Helper method to assign a range to V from metadata present in the IR.
5543 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
5544   if (Instruction *I = dyn_cast<Instruction>(V))
5545     if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
5546       return getConstantRangeFromMetadata(*MD);
5547 
5548   return None;
5549 }
5550 
5551 /// Determine the range for a particular SCEV.  If SignHint is
5552 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
5553 /// with a "cleaner" unsigned (resp. signed) representation.
5554 const ConstantRange &
5555 ScalarEvolution::getRangeRef(const SCEV *S,
5556                              ScalarEvolution::RangeSignHint SignHint) {
5557   DenseMap<const SCEV *, ConstantRange> &Cache =
5558       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
5559                                                        : SignedRanges;
5560   ConstantRange::PreferredRangeType RangeType =
5561       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED
5562           ? ConstantRange::Unsigned : ConstantRange::Signed;
5563 
5564   // See if we've computed this range already.
5565   DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
5566   if (I != Cache.end())
5567     return I->second;
5568 
5569   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5570     return setRange(C, SignHint, ConstantRange(C->getAPInt()));
5571 
5572   unsigned BitWidth = getTypeSizeInBits(S->getType());
5573   ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
5574   using OBO = OverflowingBinaryOperator;
5575 
5576   // If the value has known zeros, the maximum value will have those known zeros
5577   // as well.
5578   uint32_t TZ = GetMinTrailingZeros(S);
5579   if (TZ != 0) {
5580     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
5581       ConservativeResult =
5582           ConstantRange(APInt::getMinValue(BitWidth),
5583                         APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
5584     else
5585       ConservativeResult = ConstantRange(
5586           APInt::getSignedMinValue(BitWidth),
5587           APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
5588   }
5589 
5590   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
5591     ConstantRange X = getRangeRef(Add->getOperand(0), SignHint);
5592     unsigned WrapType = OBO::AnyWrap;
5593     if (Add->hasNoSignedWrap())
5594       WrapType |= OBO::NoSignedWrap;
5595     if (Add->hasNoUnsignedWrap())
5596       WrapType |= OBO::NoUnsignedWrap;
5597     for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
5598       X = X.addWithNoWrap(getRangeRef(Add->getOperand(i), SignHint),
5599                           WrapType, RangeType);
5600     return setRange(Add, SignHint,
5601                     ConservativeResult.intersectWith(X, RangeType));
5602   }
5603 
5604   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
5605     ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint);
5606     for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
5607       X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint));
5608     return setRange(Mul, SignHint,
5609                     ConservativeResult.intersectWith(X, RangeType));
5610   }
5611 
5612   if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
5613     ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint);
5614     for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
5615       X = X.smax(getRangeRef(SMax->getOperand(i), SignHint));
5616     return setRange(SMax, SignHint,
5617                     ConservativeResult.intersectWith(X, RangeType));
5618   }
5619 
5620   if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
5621     ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint);
5622     for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
5623       X = X.umax(getRangeRef(UMax->getOperand(i), SignHint));
5624     return setRange(UMax, SignHint,
5625                     ConservativeResult.intersectWith(X, RangeType));
5626   }
5627 
5628   if (const SCEVSMinExpr *SMin = dyn_cast<SCEVSMinExpr>(S)) {
5629     ConstantRange X = getRangeRef(SMin->getOperand(0), SignHint);
5630     for (unsigned i = 1, e = SMin->getNumOperands(); i != e; ++i)
5631       X = X.smin(getRangeRef(SMin->getOperand(i), SignHint));
5632     return setRange(SMin, SignHint,
5633                     ConservativeResult.intersectWith(X, RangeType));
5634   }
5635 
5636   if (const SCEVUMinExpr *UMin = dyn_cast<SCEVUMinExpr>(S)) {
5637     ConstantRange X = getRangeRef(UMin->getOperand(0), SignHint);
5638     for (unsigned i = 1, e = UMin->getNumOperands(); i != e; ++i)
5639       X = X.umin(getRangeRef(UMin->getOperand(i), SignHint));
5640     return setRange(UMin, SignHint,
5641                     ConservativeResult.intersectWith(X, RangeType));
5642   }
5643 
5644   if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
5645     ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint);
5646     ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint);
5647     return setRange(UDiv, SignHint,
5648                     ConservativeResult.intersectWith(X.udiv(Y), RangeType));
5649   }
5650 
5651   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
5652     ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint);
5653     return setRange(ZExt, SignHint,
5654                     ConservativeResult.intersectWith(X.zeroExtend(BitWidth),
5655                                                      RangeType));
5656   }
5657 
5658   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
5659     ConstantRange X = getRangeRef(SExt->getOperand(), SignHint);
5660     return setRange(SExt, SignHint,
5661                     ConservativeResult.intersectWith(X.signExtend(BitWidth),
5662                                                      RangeType));
5663   }
5664 
5665   if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
5666     ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint);
5667     return setRange(Trunc, SignHint,
5668                     ConservativeResult.intersectWith(X.truncate(BitWidth),
5669                                                      RangeType));
5670   }
5671 
5672   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
5673     // If there's no unsigned wrap, the value will never be less than its
5674     // initial value.
5675     if (AddRec->hasNoUnsignedWrap())
5676       if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
5677         if (!C->getValue()->isZero())
5678           ConservativeResult = ConservativeResult.intersectWith(
5679               ConstantRange(C->getAPInt(), APInt(BitWidth, 0)), RangeType);
5680 
5681     // If there's no signed wrap, and all the operands have the same sign or
5682     // zero, the value won't ever change sign.
5683     if (AddRec->hasNoSignedWrap()) {
5684       bool AllNonNeg = true;
5685       bool AllNonPos = true;
5686       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
5687         if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
5688         if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
5689       }
5690       if (AllNonNeg)
5691         ConservativeResult = ConservativeResult.intersectWith(
5692           ConstantRange(APInt(BitWidth, 0),
5693                         APInt::getSignedMinValue(BitWidth)), RangeType);
5694       else if (AllNonPos)
5695         ConservativeResult = ConservativeResult.intersectWith(
5696           ConstantRange(APInt::getSignedMinValue(BitWidth),
5697                         APInt(BitWidth, 1)), RangeType);
5698     }
5699 
5700     // TODO: non-affine addrec
5701     if (AddRec->isAffine()) {
5702       const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(AddRec->getLoop());
5703       if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
5704           getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
5705         auto RangeFromAffine = getRangeForAffineAR(
5706             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
5707             BitWidth);
5708         if (!RangeFromAffine.isFullSet())
5709           ConservativeResult =
5710               ConservativeResult.intersectWith(RangeFromAffine, RangeType);
5711 
5712         auto RangeFromFactoring = getRangeViaFactoring(
5713             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
5714             BitWidth);
5715         if (!RangeFromFactoring.isFullSet())
5716           ConservativeResult =
5717               ConservativeResult.intersectWith(RangeFromFactoring, RangeType);
5718       }
5719     }
5720 
5721     return setRange(AddRec, SignHint, std::move(ConservativeResult));
5722   }
5723 
5724   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5725     // Check if the IR explicitly contains !range metadata.
5726     Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
5727     if (MDRange.hasValue())
5728       ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue(),
5729                                                             RangeType);
5730 
5731     // Split here to avoid paying the compile-time cost of calling both
5732     // computeKnownBits and ComputeNumSignBits.  This restriction can be lifted
5733     // if needed.
5734     const DataLayout &DL = getDataLayout();
5735     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
5736       // For a SCEVUnknown, ask ValueTracking.
5737       KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
5738       if (Known.getBitWidth() != BitWidth)
5739         Known = Known.zextOrTrunc(BitWidth, true);
5740       // If Known does not result in full-set, intersect with it.
5741       if (Known.getMinValue() != Known.getMaxValue() + 1)
5742         ConservativeResult = ConservativeResult.intersectWith(
5743             ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1),
5744             RangeType);
5745     } else {
5746       assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED &&
5747              "generalize as needed!");
5748       unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
5749       // If the pointer size is larger than the index size type, this can cause
5750       // NS to be larger than BitWidth. So compensate for this.
5751       if (U->getType()->isPointerTy()) {
5752         unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType());
5753         int ptrIdxDiff = ptrSize - BitWidth;
5754         if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff)
5755           NS -= ptrIdxDiff;
5756       }
5757 
5758       if (NS > 1)
5759         ConservativeResult = ConservativeResult.intersectWith(
5760             ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
5761                           APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1),
5762             RangeType);
5763     }
5764 
5765     // A range of Phi is a subset of union of all ranges of its input.
5766     if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) {
5767       // Make sure that we do not run over cycled Phis.
5768       if (PendingPhiRanges.insert(Phi).second) {
5769         ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false);
5770         for (auto &Op : Phi->operands()) {
5771           auto OpRange = getRangeRef(getSCEV(Op), SignHint);
5772           RangeFromOps = RangeFromOps.unionWith(OpRange);
5773           // No point to continue if we already have a full set.
5774           if (RangeFromOps.isFullSet())
5775             break;
5776         }
5777         ConservativeResult =
5778             ConservativeResult.intersectWith(RangeFromOps, RangeType);
5779         bool Erased = PendingPhiRanges.erase(Phi);
5780         assert(Erased && "Failed to erase Phi properly?");
5781         (void) Erased;
5782       }
5783     }
5784 
5785     return setRange(U, SignHint, std::move(ConservativeResult));
5786   }
5787 
5788   return setRange(S, SignHint, std::move(ConservativeResult));
5789 }
5790 
5791 // Given a StartRange, Step and MaxBECount for an expression compute a range of
5792 // values that the expression can take. Initially, the expression has a value
5793 // from StartRange and then is changed by Step up to MaxBECount times. Signed
5794 // argument defines if we treat Step as signed or unsigned.
5795 static ConstantRange getRangeForAffineARHelper(APInt Step,
5796                                                const ConstantRange &StartRange,
5797                                                const APInt &MaxBECount,
5798                                                unsigned BitWidth, bool Signed) {
5799   // If either Step or MaxBECount is 0, then the expression won't change, and we
5800   // just need to return the initial range.
5801   if (Step == 0 || MaxBECount == 0)
5802     return StartRange;
5803 
5804   // If we don't know anything about the initial value (i.e. StartRange is
5805   // FullRange), then we don't know anything about the final range either.
5806   // Return FullRange.
5807   if (StartRange.isFullSet())
5808     return ConstantRange::getFull(BitWidth);
5809 
5810   // If Step is signed and negative, then we use its absolute value, but we also
5811   // note that we're moving in the opposite direction.
5812   bool Descending = Signed && Step.isNegative();
5813 
5814   if (Signed)
5815     // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
5816     // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
5817     // This equations hold true due to the well-defined wrap-around behavior of
5818     // APInt.
5819     Step = Step.abs();
5820 
5821   // Check if Offset is more than full span of BitWidth. If it is, the
5822   // expression is guaranteed to overflow.
5823   if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
5824     return ConstantRange::getFull(BitWidth);
5825 
5826   // Offset is by how much the expression can change. Checks above guarantee no
5827   // overflow here.
5828   APInt Offset = Step * MaxBECount;
5829 
5830   // Minimum value of the final range will match the minimal value of StartRange
5831   // if the expression is increasing and will be decreased by Offset otherwise.
5832   // Maximum value of the final range will match the maximal value of StartRange
5833   // if the expression is decreasing and will be increased by Offset otherwise.
5834   APInt StartLower = StartRange.getLower();
5835   APInt StartUpper = StartRange.getUpper() - 1;
5836   APInt MovedBoundary = Descending ? (StartLower - std::move(Offset))
5837                                    : (StartUpper + std::move(Offset));
5838 
5839   // It's possible that the new minimum/maximum value will fall into the initial
5840   // range (due to wrap around). This means that the expression can take any
5841   // value in this bitwidth, and we have to return full range.
5842   if (StartRange.contains(MovedBoundary))
5843     return ConstantRange::getFull(BitWidth);
5844 
5845   APInt NewLower =
5846       Descending ? std::move(MovedBoundary) : std::move(StartLower);
5847   APInt NewUpper =
5848       Descending ? std::move(StartUpper) : std::move(MovedBoundary);
5849   NewUpper += 1;
5850 
5851   // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
5852   return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper));
5853 }
5854 
5855 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
5856                                                    const SCEV *Step,
5857                                                    const SCEV *MaxBECount,
5858                                                    unsigned BitWidth) {
5859   assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&
5860          getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
5861          "Precondition!");
5862 
5863   MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType());
5864   APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount);
5865 
5866   // First, consider step signed.
5867   ConstantRange StartSRange = getSignedRange(Start);
5868   ConstantRange StepSRange = getSignedRange(Step);
5869 
5870   // If Step can be both positive and negative, we need to find ranges for the
5871   // maximum absolute step values in both directions and union them.
5872   ConstantRange SR =
5873       getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange,
5874                                 MaxBECountValue, BitWidth, /* Signed = */ true);
5875   SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(),
5876                                               StartSRange, MaxBECountValue,
5877                                               BitWidth, /* Signed = */ true));
5878 
5879   // Next, consider step unsigned.
5880   ConstantRange UR = getRangeForAffineARHelper(
5881       getUnsignedRangeMax(Step), getUnsignedRange(Start),
5882       MaxBECountValue, BitWidth, /* Signed = */ false);
5883 
5884   // Finally, intersect signed and unsigned ranges.
5885   return SR.intersectWith(UR, ConstantRange::Smallest);
5886 }
5887 
5888 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
5889                                                     const SCEV *Step,
5890                                                     const SCEV *MaxBECount,
5891                                                     unsigned BitWidth) {
5892   //    RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
5893   // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
5894 
5895   struct SelectPattern {
5896     Value *Condition = nullptr;
5897     APInt TrueValue;
5898     APInt FalseValue;
5899 
5900     explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
5901                            const SCEV *S) {
5902       Optional<unsigned> CastOp;
5903       APInt Offset(BitWidth, 0);
5904 
5905       assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&
5906              "Should be!");
5907 
5908       // Peel off a constant offset:
5909       if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
5910         // In the future we could consider being smarter here and handle
5911         // {Start+Step,+,Step} too.
5912         if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
5913           return;
5914 
5915         Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
5916         S = SA->getOperand(1);
5917       }
5918 
5919       // Peel off a cast operation
5920       if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) {
5921         CastOp = SCast->getSCEVType();
5922         S = SCast->getOperand();
5923       }
5924 
5925       using namespace llvm::PatternMatch;
5926 
5927       auto *SU = dyn_cast<SCEVUnknown>(S);
5928       const APInt *TrueVal, *FalseVal;
5929       if (!SU ||
5930           !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
5931                                           m_APInt(FalseVal)))) {
5932         Condition = nullptr;
5933         return;
5934       }
5935 
5936       TrueValue = *TrueVal;
5937       FalseValue = *FalseVal;
5938 
5939       // Re-apply the cast we peeled off earlier
5940       if (CastOp.hasValue())
5941         switch (*CastOp) {
5942         default:
5943           llvm_unreachable("Unknown SCEV cast type!");
5944 
5945         case scTruncate:
5946           TrueValue = TrueValue.trunc(BitWidth);
5947           FalseValue = FalseValue.trunc(BitWidth);
5948           break;
5949         case scZeroExtend:
5950           TrueValue = TrueValue.zext(BitWidth);
5951           FalseValue = FalseValue.zext(BitWidth);
5952           break;
5953         case scSignExtend:
5954           TrueValue = TrueValue.sext(BitWidth);
5955           FalseValue = FalseValue.sext(BitWidth);
5956           break;
5957         }
5958 
5959       // Re-apply the constant offset we peeled off earlier
5960       TrueValue += Offset;
5961       FalseValue += Offset;
5962     }
5963 
5964     bool isRecognized() { return Condition != nullptr; }
5965   };
5966 
5967   SelectPattern StartPattern(*this, BitWidth, Start);
5968   if (!StartPattern.isRecognized())
5969     return ConstantRange::getFull(BitWidth);
5970 
5971   SelectPattern StepPattern(*this, BitWidth, Step);
5972   if (!StepPattern.isRecognized())
5973     return ConstantRange::getFull(BitWidth);
5974 
5975   if (StartPattern.Condition != StepPattern.Condition) {
5976     // We don't handle this case today; but we could, by considering four
5977     // possibilities below instead of two. I'm not sure if there are cases where
5978     // that will help over what getRange already does, though.
5979     return ConstantRange::getFull(BitWidth);
5980   }
5981 
5982   // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
5983   // construct arbitrary general SCEV expressions here.  This function is called
5984   // from deep in the call stack, and calling getSCEV (on a sext instruction,
5985   // say) can end up caching a suboptimal value.
5986 
5987   // FIXME: without the explicit `this` receiver below, MSVC errors out with
5988   // C2352 and C2512 (otherwise it isn't needed).
5989 
5990   const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
5991   const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
5992   const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
5993   const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
5994 
5995   ConstantRange TrueRange =
5996       this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
5997   ConstantRange FalseRange =
5998       this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
5999 
6000   return TrueRange.unionWith(FalseRange);
6001 }
6002 
6003 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
6004   if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
6005   const BinaryOperator *BinOp = cast<BinaryOperator>(V);
6006 
6007   // Return early if there are no flags to propagate to the SCEV.
6008   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
6009   if (BinOp->hasNoUnsignedWrap())
6010     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
6011   if (BinOp->hasNoSignedWrap())
6012     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
6013   if (Flags == SCEV::FlagAnyWrap)
6014     return SCEV::FlagAnyWrap;
6015 
6016   return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
6017 }
6018 
6019 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
6020   // Here we check that I is in the header of the innermost loop containing I,
6021   // since we only deal with instructions in the loop header. The actual loop we
6022   // need to check later will come from an add recurrence, but getting that
6023   // requires computing the SCEV of the operands, which can be expensive. This
6024   // check we can do cheaply to rule out some cases early.
6025   Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent());
6026   if (InnermostContainingLoop == nullptr ||
6027       InnermostContainingLoop->getHeader() != I->getParent())
6028     return false;
6029 
6030   // Only proceed if we can prove that I does not yield poison.
6031   if (!programUndefinedIfFullPoison(I))
6032     return false;
6033 
6034   // At this point we know that if I is executed, then it does not wrap
6035   // according to at least one of NSW or NUW. If I is not executed, then we do
6036   // not know if the calculation that I represents would wrap. Multiple
6037   // instructions can map to the same SCEV. If we apply NSW or NUW from I to
6038   // the SCEV, we must guarantee no wrapping for that SCEV also when it is
6039   // derived from other instructions that map to the same SCEV. We cannot make
6040   // that guarantee for cases where I is not executed. So we need to find the
6041   // loop that I is considered in relation to and prove that I is executed for
6042   // every iteration of that loop. That implies that the value that I
6043   // calculates does not wrap anywhere in the loop, so then we can apply the
6044   // flags to the SCEV.
6045   //
6046   // We check isLoopInvariant to disambiguate in case we are adding recurrences
6047   // from different loops, so that we know which loop to prove that I is
6048   // executed in.
6049   for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) {
6050     // I could be an extractvalue from a call to an overflow intrinsic.
6051     // TODO: We can do better here in some cases.
6052     if (!isSCEVable(I->getOperand(OpIndex)->getType()))
6053       return false;
6054     const SCEV *Op = getSCEV(I->getOperand(OpIndex));
6055     if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
6056       bool AllOtherOpsLoopInvariant = true;
6057       for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands();
6058            ++OtherOpIndex) {
6059         if (OtherOpIndex != OpIndex) {
6060           const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex));
6061           if (!isLoopInvariant(OtherOp, AddRec->getLoop())) {
6062             AllOtherOpsLoopInvariant = false;
6063             break;
6064           }
6065         }
6066       }
6067       if (AllOtherOpsLoopInvariant &&
6068           isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop()))
6069         return true;
6070     }
6071   }
6072   return false;
6073 }
6074 
6075 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
6076   // If we know that \c I can never be poison period, then that's enough.
6077   if (isSCEVExprNeverPoison(I))
6078     return true;
6079 
6080   // For an add recurrence specifically, we assume that infinite loops without
6081   // side effects are undefined behavior, and then reason as follows:
6082   //
6083   // If the add recurrence is poison in any iteration, it is poison on all
6084   // future iterations (since incrementing poison yields poison). If the result
6085   // of the add recurrence is fed into the loop latch condition and the loop
6086   // does not contain any throws or exiting blocks other than the latch, we now
6087   // have the ability to "choose" whether the backedge is taken or not (by
6088   // choosing a sufficiently evil value for the poison feeding into the branch)
6089   // for every iteration including and after the one in which \p I first became
6090   // poison.  There are two possibilities (let's call the iteration in which \p
6091   // I first became poison as K):
6092   //
6093   //  1. In the set of iterations including and after K, the loop body executes
6094   //     no side effects.  In this case executing the backege an infinte number
6095   //     of times will yield undefined behavior.
6096   //
6097   //  2. In the set of iterations including and after K, the loop body executes
6098   //     at least one side effect.  In this case, that specific instance of side
6099   //     effect is control dependent on poison, which also yields undefined
6100   //     behavior.
6101 
6102   auto *ExitingBB = L->getExitingBlock();
6103   auto *LatchBB = L->getLoopLatch();
6104   if (!ExitingBB || !LatchBB || ExitingBB != LatchBB)
6105     return false;
6106 
6107   SmallPtrSet<const Instruction *, 16> Pushed;
6108   SmallVector<const Instruction *, 8> PoisonStack;
6109 
6110   // We start by assuming \c I, the post-inc add recurrence, is poison.  Only
6111   // things that are known to be fully poison under that assumption go on the
6112   // PoisonStack.
6113   Pushed.insert(I);
6114   PoisonStack.push_back(I);
6115 
6116   bool LatchControlDependentOnPoison = false;
6117   while (!PoisonStack.empty() && !LatchControlDependentOnPoison) {
6118     const Instruction *Poison = PoisonStack.pop_back_val();
6119 
6120     for (auto *PoisonUser : Poison->users()) {
6121       if (propagatesFullPoison(cast<Instruction>(PoisonUser))) {
6122         if (Pushed.insert(cast<Instruction>(PoisonUser)).second)
6123           PoisonStack.push_back(cast<Instruction>(PoisonUser));
6124       } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) {
6125         assert(BI->isConditional() && "Only possibility!");
6126         if (BI->getParent() == LatchBB) {
6127           LatchControlDependentOnPoison = true;
6128           break;
6129         }
6130       }
6131     }
6132   }
6133 
6134   return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L);
6135 }
6136 
6137 ScalarEvolution::LoopProperties
6138 ScalarEvolution::getLoopProperties(const Loop *L) {
6139   using LoopProperties = ScalarEvolution::LoopProperties;
6140 
6141   auto Itr = LoopPropertiesCache.find(L);
6142   if (Itr == LoopPropertiesCache.end()) {
6143     auto HasSideEffects = [](Instruction *I) {
6144       if (auto *SI = dyn_cast<StoreInst>(I))
6145         return !SI->isSimple();
6146 
6147       return I->mayHaveSideEffects();
6148     };
6149 
6150     LoopProperties LP = {/* HasNoAbnormalExits */ true,
6151                          /*HasNoSideEffects*/ true};
6152 
6153     for (auto *BB : L->getBlocks())
6154       for (auto &I : *BB) {
6155         if (!isGuaranteedToTransferExecutionToSuccessor(&I))
6156           LP.HasNoAbnormalExits = false;
6157         if (HasSideEffects(&I))
6158           LP.HasNoSideEffects = false;
6159         if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
6160           break; // We're already as pessimistic as we can get.
6161       }
6162 
6163     auto InsertPair = LoopPropertiesCache.insert({L, LP});
6164     assert(InsertPair.second && "We just checked!");
6165     Itr = InsertPair.first;
6166   }
6167 
6168   return Itr->second;
6169 }
6170 
6171 const SCEV *ScalarEvolution::createSCEV(Value *V) {
6172   if (!isSCEVable(V->getType()))
6173     return getUnknown(V);
6174 
6175   if (Instruction *I = dyn_cast<Instruction>(V)) {
6176     // Don't attempt to analyze instructions in blocks that aren't
6177     // reachable. Such instructions don't matter, and they aren't required
6178     // to obey basic rules for definitions dominating uses which this
6179     // analysis depends on.
6180     if (!DT.isReachableFromEntry(I->getParent()))
6181       return getUnknown(UndefValue::get(V->getType()));
6182   } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
6183     return getConstant(CI);
6184   else if (isa<ConstantPointerNull>(V))
6185     return getZero(V->getType());
6186   else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
6187     return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee());
6188   else if (!isa<ConstantExpr>(V))
6189     return getUnknown(V);
6190 
6191   Operator *U = cast<Operator>(V);
6192   if (auto BO = MatchBinaryOp(U, DT)) {
6193     switch (BO->Opcode) {
6194     case Instruction::Add: {
6195       // The simple thing to do would be to just call getSCEV on both operands
6196       // and call getAddExpr with the result. However if we're looking at a
6197       // bunch of things all added together, this can be quite inefficient,
6198       // because it leads to N-1 getAddExpr calls for N ultimate operands.
6199       // Instead, gather up all the operands and make a single getAddExpr call.
6200       // LLVM IR canonical form means we need only traverse the left operands.
6201       SmallVector<const SCEV *, 4> AddOps;
6202       do {
6203         if (BO->Op) {
6204           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
6205             AddOps.push_back(OpSCEV);
6206             break;
6207           }
6208 
6209           // If a NUW or NSW flag can be applied to the SCEV for this
6210           // addition, then compute the SCEV for this addition by itself
6211           // with a separate call to getAddExpr. We need to do that
6212           // instead of pushing the operands of the addition onto AddOps,
6213           // since the flags are only known to apply to this particular
6214           // addition - they may not apply to other additions that can be
6215           // formed with operands from AddOps.
6216           const SCEV *RHS = getSCEV(BO->RHS);
6217           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
6218           if (Flags != SCEV::FlagAnyWrap) {
6219             const SCEV *LHS = getSCEV(BO->LHS);
6220             if (BO->Opcode == Instruction::Sub)
6221               AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
6222             else
6223               AddOps.push_back(getAddExpr(LHS, RHS, Flags));
6224             break;
6225           }
6226         }
6227 
6228         if (BO->Opcode == Instruction::Sub)
6229           AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
6230         else
6231           AddOps.push_back(getSCEV(BO->RHS));
6232 
6233         auto NewBO = MatchBinaryOp(BO->LHS, DT);
6234         if (!NewBO || (NewBO->Opcode != Instruction::Add &&
6235                        NewBO->Opcode != Instruction::Sub)) {
6236           AddOps.push_back(getSCEV(BO->LHS));
6237           break;
6238         }
6239         BO = NewBO;
6240       } while (true);
6241 
6242       return getAddExpr(AddOps);
6243     }
6244 
6245     case Instruction::Mul: {
6246       SmallVector<const SCEV *, 4> MulOps;
6247       do {
6248         if (BO->Op) {
6249           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
6250             MulOps.push_back(OpSCEV);
6251             break;
6252           }
6253 
6254           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
6255           if (Flags != SCEV::FlagAnyWrap) {
6256             MulOps.push_back(
6257                 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags));
6258             break;
6259           }
6260         }
6261 
6262         MulOps.push_back(getSCEV(BO->RHS));
6263         auto NewBO = MatchBinaryOp(BO->LHS, DT);
6264         if (!NewBO || NewBO->Opcode != Instruction::Mul) {
6265           MulOps.push_back(getSCEV(BO->LHS));
6266           break;
6267         }
6268         BO = NewBO;
6269       } while (true);
6270 
6271       return getMulExpr(MulOps);
6272     }
6273     case Instruction::UDiv:
6274       return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
6275     case Instruction::URem:
6276       return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
6277     case Instruction::Sub: {
6278       SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
6279       if (BO->Op)
6280         Flags = getNoWrapFlagsFromUB(BO->Op);
6281       return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags);
6282     }
6283     case Instruction::And:
6284       // For an expression like x&255 that merely masks off the high bits,
6285       // use zext(trunc(x)) as the SCEV expression.
6286       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6287         if (CI->isZero())
6288           return getSCEV(BO->RHS);
6289         if (CI->isMinusOne())
6290           return getSCEV(BO->LHS);
6291         const APInt &A = CI->getValue();
6292 
6293         // Instcombine's ShrinkDemandedConstant may strip bits out of
6294         // constants, obscuring what would otherwise be a low-bits mask.
6295         // Use computeKnownBits to compute what ShrinkDemandedConstant
6296         // knew about to reconstruct a low-bits mask value.
6297         unsigned LZ = A.countLeadingZeros();
6298         unsigned TZ = A.countTrailingZeros();
6299         unsigned BitWidth = A.getBitWidth();
6300         KnownBits Known(BitWidth);
6301         computeKnownBits(BO->LHS, Known, getDataLayout(),
6302                          0, &AC, nullptr, &DT);
6303 
6304         APInt EffectiveMask =
6305             APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
6306         if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
6307           const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
6308           const SCEV *LHS = getSCEV(BO->LHS);
6309           const SCEV *ShiftedLHS = nullptr;
6310           if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
6311             if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
6312               // For an expression like (x * 8) & 8, simplify the multiply.
6313               unsigned MulZeros = OpC->getAPInt().countTrailingZeros();
6314               unsigned GCD = std::min(MulZeros, TZ);
6315               APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
6316               SmallVector<const SCEV*, 4> MulOps;
6317               MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD)));
6318               MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end());
6319               auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
6320               ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
6321             }
6322           }
6323           if (!ShiftedLHS)
6324             ShiftedLHS = getUDivExpr(LHS, MulCount);
6325           return getMulExpr(
6326               getZeroExtendExpr(
6327                   getTruncateExpr(ShiftedLHS,
6328                       IntegerType::get(getContext(), BitWidth - LZ - TZ)),
6329                   BO->LHS->getType()),
6330               MulCount);
6331         }
6332       }
6333       break;
6334 
6335     case Instruction::Or:
6336       // If the RHS of the Or is a constant, we may have something like:
6337       // X*4+1 which got turned into X*4|1.  Handle this as an Add so loop
6338       // optimizations will transparently handle this case.
6339       //
6340       // In order for this transformation to be safe, the LHS must be of the
6341       // form X*(2^n) and the Or constant must be less than 2^n.
6342       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6343         const SCEV *LHS = getSCEV(BO->LHS);
6344         const APInt &CIVal = CI->getValue();
6345         if (GetMinTrailingZeros(LHS) >=
6346             (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
6347           // Build a plain add SCEV.
6348           const SCEV *S = getAddExpr(LHS, getSCEV(CI));
6349           // If the LHS of the add was an addrec and it has no-wrap flags,
6350           // transfer the no-wrap flags, since an or won't introduce a wrap.
6351           if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
6352             const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
6353             const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags(
6354                 OldAR->getNoWrapFlags());
6355           }
6356           return S;
6357         }
6358       }
6359       break;
6360 
6361     case Instruction::Xor:
6362       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6363         // If the RHS of xor is -1, then this is a not operation.
6364         if (CI->isMinusOne())
6365           return getNotSCEV(getSCEV(BO->LHS));
6366 
6367         // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
6368         // This is a variant of the check for xor with -1, and it handles
6369         // the case where instcombine has trimmed non-demanded bits out
6370         // of an xor with -1.
6371         if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
6372           if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
6373             if (LBO->getOpcode() == Instruction::And &&
6374                 LCI->getValue() == CI->getValue())
6375               if (const SCEVZeroExtendExpr *Z =
6376                       dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
6377                 Type *UTy = BO->LHS->getType();
6378                 const SCEV *Z0 = Z->getOperand();
6379                 Type *Z0Ty = Z0->getType();
6380                 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
6381 
6382                 // If C is a low-bits mask, the zero extend is serving to
6383                 // mask off the high bits. Complement the operand and
6384                 // re-apply the zext.
6385                 if (CI->getValue().isMask(Z0TySize))
6386                   return getZeroExtendExpr(getNotSCEV(Z0), UTy);
6387 
6388                 // If C is a single bit, it may be in the sign-bit position
6389                 // before the zero-extend. In this case, represent the xor
6390                 // using an add, which is equivalent, and re-apply the zext.
6391                 APInt Trunc = CI->getValue().trunc(Z0TySize);
6392                 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
6393                     Trunc.isSignMask())
6394                   return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
6395                                            UTy);
6396               }
6397       }
6398       break;
6399 
6400     case Instruction::Shl:
6401       // Turn shift left of a constant amount into a multiply.
6402       if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
6403         uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
6404 
6405         // If the shift count is not less than the bitwidth, the result of
6406         // the shift is undefined. Don't try to analyze it, because the
6407         // resolution chosen here may differ from the resolution chosen in
6408         // other parts of the compiler.
6409         if (SA->getValue().uge(BitWidth))
6410           break;
6411 
6412         // It is currently not resolved how to interpret NSW for left
6413         // shift by BitWidth - 1, so we avoid applying flags in that
6414         // case. Remove this check (or this comment) once the situation
6415         // is resolved. See
6416         // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html
6417         // and http://reviews.llvm.org/D8890 .
6418         auto Flags = SCEV::FlagAnyWrap;
6419         if (BO->Op && SA->getValue().ult(BitWidth - 1))
6420           Flags = getNoWrapFlagsFromUB(BO->Op);
6421 
6422         Constant *X = ConstantInt::get(
6423             getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
6424         return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags);
6425       }
6426       break;
6427 
6428     case Instruction::AShr: {
6429       // AShr X, C, where C is a constant.
6430       ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
6431       if (!CI)
6432         break;
6433 
6434       Type *OuterTy = BO->LHS->getType();
6435       uint64_t BitWidth = getTypeSizeInBits(OuterTy);
6436       // If the shift count is not less than the bitwidth, the result of
6437       // the shift is undefined. Don't try to analyze it, because the
6438       // resolution chosen here may differ from the resolution chosen in
6439       // other parts of the compiler.
6440       if (CI->getValue().uge(BitWidth))
6441         break;
6442 
6443       if (CI->isZero())
6444         return getSCEV(BO->LHS); // shift by zero --> noop
6445 
6446       uint64_t AShrAmt = CI->getZExtValue();
6447       Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
6448 
6449       Operator *L = dyn_cast<Operator>(BO->LHS);
6450       if (L && L->getOpcode() == Instruction::Shl) {
6451         // X = Shl A, n
6452         // Y = AShr X, m
6453         // Both n and m are constant.
6454 
6455         const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
6456         if (L->getOperand(1) == BO->RHS)
6457           // For a two-shift sext-inreg, i.e. n = m,
6458           // use sext(trunc(x)) as the SCEV expression.
6459           return getSignExtendExpr(
6460               getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy);
6461 
6462         ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
6463         if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) {
6464           uint64_t ShlAmt = ShlAmtCI->getZExtValue();
6465           if (ShlAmt > AShrAmt) {
6466             // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
6467             // expression. We already checked that ShlAmt < BitWidth, so
6468             // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
6469             // ShlAmt - AShrAmt < Amt.
6470             APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
6471                                             ShlAmt - AShrAmt);
6472             return getSignExtendExpr(
6473                 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy),
6474                 getConstant(Mul)), OuterTy);
6475           }
6476         }
6477       }
6478       break;
6479     }
6480     }
6481   }
6482 
6483   switch (U->getOpcode()) {
6484   case Instruction::Trunc:
6485     return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
6486 
6487   case Instruction::ZExt:
6488     return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
6489 
6490   case Instruction::SExt:
6491     if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) {
6492       // The NSW flag of a subtract does not always survive the conversion to
6493       // A + (-1)*B.  By pushing sign extension onto its operands we are much
6494       // more likely to preserve NSW and allow later AddRec optimisations.
6495       //
6496       // NOTE: This is effectively duplicating this logic from getSignExtend:
6497       //   sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
6498       // but by that point the NSW information has potentially been lost.
6499       if (BO->Opcode == Instruction::Sub && BO->IsNSW) {
6500         Type *Ty = U->getType();
6501         auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty);
6502         auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty);
6503         return getMinusSCEV(V1, V2, SCEV::FlagNSW);
6504       }
6505     }
6506     return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
6507 
6508   case Instruction::BitCast:
6509     // BitCasts are no-op casts so we just eliminate the cast.
6510     if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
6511       return getSCEV(U->getOperand(0));
6512     break;
6513 
6514   // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
6515   // lead to pointer expressions which cannot safely be expanded to GEPs,
6516   // because ScalarEvolution doesn't respect the GEP aliasing rules when
6517   // simplifying integer expressions.
6518 
6519   case Instruction::GetElementPtr:
6520     return createNodeForGEP(cast<GEPOperator>(U));
6521 
6522   case Instruction::PHI:
6523     return createNodeForPHI(cast<PHINode>(U));
6524 
6525   case Instruction::Select:
6526     // U can also be a select constant expr, which let fall through.  Since
6527     // createNodeForSelect only works for a condition that is an `ICmpInst`, and
6528     // constant expressions cannot have instructions as operands, we'd have
6529     // returned getUnknown for a select constant expressions anyway.
6530     if (isa<Instruction>(U))
6531       return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0),
6532                                       U->getOperand(1), U->getOperand(2));
6533     break;
6534 
6535   case Instruction::Call:
6536   case Instruction::Invoke:
6537     if (Value *RV = CallSite(U).getReturnedArgOperand())
6538       return getSCEV(RV);
6539     break;
6540   }
6541 
6542   return getUnknown(V);
6543 }
6544 
6545 //===----------------------------------------------------------------------===//
6546 //                   Iteration Count Computation Code
6547 //
6548 
6549 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
6550   if (!ExitCount)
6551     return 0;
6552 
6553   ConstantInt *ExitConst = ExitCount->getValue();
6554 
6555   // Guard against huge trip counts.
6556   if (ExitConst->getValue().getActiveBits() > 32)
6557     return 0;
6558 
6559   // In case of integer overflow, this returns 0, which is correct.
6560   return ((unsigned)ExitConst->getZExtValue()) + 1;
6561 }
6562 
6563 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) {
6564   if (BasicBlock *ExitingBB = L->getExitingBlock())
6565     return getSmallConstantTripCount(L, ExitingBB);
6566 
6567   // No trip count information for multiple exits.
6568   return 0;
6569 }
6570 
6571 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L,
6572                                                     BasicBlock *ExitingBlock) {
6573   assert(ExitingBlock && "Must pass a non-null exiting block!");
6574   assert(L->isLoopExiting(ExitingBlock) &&
6575          "Exiting block must actually branch out of the loop!");
6576   const SCEVConstant *ExitCount =
6577       dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
6578   return getConstantTripCount(ExitCount);
6579 }
6580 
6581 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) {
6582   const auto *MaxExitCount =
6583       dyn_cast<SCEVConstant>(getConstantMaxBackedgeTakenCount(L));
6584   return getConstantTripCount(MaxExitCount);
6585 }
6586 
6587 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) {
6588   if (BasicBlock *ExitingBB = L->getExitingBlock())
6589     return getSmallConstantTripMultiple(L, ExitingBB);
6590 
6591   // No trip multiple information for multiple exits.
6592   return 0;
6593 }
6594 
6595 /// Returns the largest constant divisor of the trip count of this loop as a
6596 /// normal unsigned value, if possible. This means that the actual trip count is
6597 /// always a multiple of the returned value (don't forget the trip count could
6598 /// very well be zero as well!).
6599 ///
6600 /// Returns 1 if the trip count is unknown or not guaranteed to be the
6601 /// multiple of a constant (which is also the case if the trip count is simply
6602 /// constant, use getSmallConstantTripCount for that case), Will also return 1
6603 /// if the trip count is very large (>= 2^32).
6604 ///
6605 /// As explained in the comments for getSmallConstantTripCount, this assumes
6606 /// that control exits the loop via ExitingBlock.
6607 unsigned
6608 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
6609                                               BasicBlock *ExitingBlock) {
6610   assert(ExitingBlock && "Must pass a non-null exiting block!");
6611   assert(L->isLoopExiting(ExitingBlock) &&
6612          "Exiting block must actually branch out of the loop!");
6613   const SCEV *ExitCount = getExitCount(L, ExitingBlock);
6614   if (ExitCount == getCouldNotCompute())
6615     return 1;
6616 
6617   // Get the trip count from the BE count by adding 1.
6618   const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType()));
6619 
6620   const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr);
6621   if (!TC)
6622     // Attempt to factor more general cases. Returns the greatest power of
6623     // two divisor. If overflow happens, the trip count expression is still
6624     // divisible by the greatest power of 2 divisor returned.
6625     return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr));
6626 
6627   ConstantInt *Result = TC->getValue();
6628 
6629   // Guard against huge trip counts (this requires checking
6630   // for zero to handle the case where the trip count == -1 and the
6631   // addition wraps).
6632   if (!Result || Result->getValue().getActiveBits() > 32 ||
6633       Result->getValue().getActiveBits() == 0)
6634     return 1;
6635 
6636   return (unsigned)Result->getZExtValue();
6637 }
6638 
6639 const SCEV *ScalarEvolution::getExitCount(const Loop *L,
6640                                           BasicBlock *ExitingBlock,
6641                                           ExitCountKind Kind) {
6642   switch (Kind) {
6643   case Exact:
6644     return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
6645   case ConstantMaximum:
6646     return getBackedgeTakenInfo(L).getMax(ExitingBlock, this);
6647   };
6648   llvm_unreachable("Invalid ExitCountKind!");
6649 }
6650 
6651 const SCEV *
6652 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
6653                                                  SCEVUnionPredicate &Preds) {
6654   return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds);
6655 }
6656 
6657 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L,
6658                                                    ExitCountKind Kind) {
6659   switch (Kind) {
6660   case Exact:
6661     return getBackedgeTakenInfo(L).getExact(L, this);
6662   case ConstantMaximum:
6663     return getBackedgeTakenInfo(L).getMax(this);
6664   };
6665   llvm_unreachable("Invalid ExitCountKind!");
6666 }
6667 
6668 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) {
6669   return getBackedgeTakenInfo(L).isMaxOrZero(this);
6670 }
6671 
6672 /// Push PHI nodes in the header of the given loop onto the given Worklist.
6673 static void
6674 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
6675   BasicBlock *Header = L->getHeader();
6676 
6677   // Push all Loop-header PHIs onto the Worklist stack.
6678   for (PHINode &PN : Header->phis())
6679     Worklist.push_back(&PN);
6680 }
6681 
6682 const ScalarEvolution::BackedgeTakenInfo &
6683 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
6684   auto &BTI = getBackedgeTakenInfo(L);
6685   if (BTI.hasFullInfo())
6686     return BTI;
6687 
6688   auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
6689 
6690   if (!Pair.second)
6691     return Pair.first->second;
6692 
6693   BackedgeTakenInfo Result =
6694       computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
6695 
6696   return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
6697 }
6698 
6699 const ScalarEvolution::BackedgeTakenInfo &
6700 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
6701   // Initially insert an invalid entry for this loop. If the insertion
6702   // succeeds, proceed to actually compute a backedge-taken count and
6703   // update the value. The temporary CouldNotCompute value tells SCEV
6704   // code elsewhere that it shouldn't attempt to request a new
6705   // backedge-taken count, which could result in infinite recursion.
6706   std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
6707       BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
6708   if (!Pair.second)
6709     return Pair.first->second;
6710 
6711   // computeBackedgeTakenCount may allocate memory for its result. Inserting it
6712   // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
6713   // must be cleared in this scope.
6714   BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
6715 
6716   // In product build, there are no usage of statistic.
6717   (void)NumTripCountsComputed;
6718   (void)NumTripCountsNotComputed;
6719 #if LLVM_ENABLE_STATS || !defined(NDEBUG)
6720   const SCEV *BEExact = Result.getExact(L, this);
6721   if (BEExact != getCouldNotCompute()) {
6722     assert(isLoopInvariant(BEExact, L) &&
6723            isLoopInvariant(Result.getMax(this), L) &&
6724            "Computed backedge-taken count isn't loop invariant for loop!");
6725     ++NumTripCountsComputed;
6726   }
6727   else if (Result.getMax(this) == getCouldNotCompute() &&
6728            isa<PHINode>(L->getHeader()->begin())) {
6729     // Only count loops that have phi nodes as not being computable.
6730     ++NumTripCountsNotComputed;
6731   }
6732 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG)
6733 
6734   // Now that we know more about the trip count for this loop, forget any
6735   // existing SCEV values for PHI nodes in this loop since they are only
6736   // conservative estimates made without the benefit of trip count
6737   // information. This is similar to the code in forgetLoop, except that
6738   // it handles SCEVUnknown PHI nodes specially.
6739   if (Result.hasAnyInfo()) {
6740     SmallVector<Instruction *, 16> Worklist;
6741     PushLoopPHIs(L, Worklist);
6742 
6743     SmallPtrSet<Instruction *, 8> Discovered;
6744     while (!Worklist.empty()) {
6745       Instruction *I = Worklist.pop_back_val();
6746 
6747       ValueExprMapType::iterator It =
6748         ValueExprMap.find_as(static_cast<Value *>(I));
6749       if (It != ValueExprMap.end()) {
6750         const SCEV *Old = It->second;
6751 
6752         // SCEVUnknown for a PHI either means that it has an unrecognized
6753         // structure, or it's a PHI that's in the progress of being computed
6754         // by createNodeForPHI.  In the former case, additional loop trip
6755         // count information isn't going to change anything. In the later
6756         // case, createNodeForPHI will perform the necessary updates on its
6757         // own when it gets to that point.
6758         if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
6759           eraseValueFromMap(It->first);
6760           forgetMemoizedResults(Old);
6761         }
6762         if (PHINode *PN = dyn_cast<PHINode>(I))
6763           ConstantEvolutionLoopExitValue.erase(PN);
6764       }
6765 
6766       // Since we don't need to invalidate anything for correctness and we're
6767       // only invalidating to make SCEV's results more precise, we get to stop
6768       // early to avoid invalidating too much.  This is especially important in
6769       // cases like:
6770       //
6771       //   %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node
6772       // loop0:
6773       //   %pn0 = phi
6774       //   ...
6775       // loop1:
6776       //   %pn1 = phi
6777       //   ...
6778       //
6779       // where both loop0 and loop1's backedge taken count uses the SCEV
6780       // expression for %v.  If we don't have the early stop below then in cases
6781       // like the above, getBackedgeTakenInfo(loop1) will clear out the trip
6782       // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip
6783       // count for loop1, effectively nullifying SCEV's trip count cache.
6784       for (auto *U : I->users())
6785         if (auto *I = dyn_cast<Instruction>(U)) {
6786           auto *LoopForUser = LI.getLoopFor(I->getParent());
6787           if (LoopForUser && L->contains(LoopForUser) &&
6788               Discovered.insert(I).second)
6789             Worklist.push_back(I);
6790         }
6791     }
6792   }
6793 
6794   // Re-lookup the insert position, since the call to
6795   // computeBackedgeTakenCount above could result in a
6796   // recusive call to getBackedgeTakenInfo (on a different
6797   // loop), which would invalidate the iterator computed
6798   // earlier.
6799   return BackedgeTakenCounts.find(L)->second = std::move(Result);
6800 }
6801 
6802 void ScalarEvolution::forgetAllLoops() {
6803   // This method is intended to forget all info about loops. It should
6804   // invalidate caches as if the following happened:
6805   // - The trip counts of all loops have changed arbitrarily
6806   // - Every llvm::Value has been updated in place to produce a different
6807   // result.
6808   BackedgeTakenCounts.clear();
6809   PredicatedBackedgeTakenCounts.clear();
6810   LoopPropertiesCache.clear();
6811   ConstantEvolutionLoopExitValue.clear();
6812   ValueExprMap.clear();
6813   ValuesAtScopes.clear();
6814   LoopDispositions.clear();
6815   BlockDispositions.clear();
6816   UnsignedRanges.clear();
6817   SignedRanges.clear();
6818   ExprValueMap.clear();
6819   HasRecMap.clear();
6820   MinTrailingZerosCache.clear();
6821   PredicatedSCEVRewrites.clear();
6822 }
6823 
6824 void ScalarEvolution::forgetLoop(const Loop *L) {
6825   // Drop any stored trip count value.
6826   auto RemoveLoopFromBackedgeMap =
6827       [](DenseMap<const Loop *, BackedgeTakenInfo> &Map, const Loop *L) {
6828         auto BTCPos = Map.find(L);
6829         if (BTCPos != Map.end()) {
6830           BTCPos->second.clear();
6831           Map.erase(BTCPos);
6832         }
6833       };
6834 
6835   SmallVector<const Loop *, 16> LoopWorklist(1, L);
6836   SmallVector<Instruction *, 32> Worklist;
6837   SmallPtrSet<Instruction *, 16> Visited;
6838 
6839   // Iterate over all the loops and sub-loops to drop SCEV information.
6840   while (!LoopWorklist.empty()) {
6841     auto *CurrL = LoopWorklist.pop_back_val();
6842 
6843     RemoveLoopFromBackedgeMap(BackedgeTakenCounts, CurrL);
6844     RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts, CurrL);
6845 
6846     // Drop information about predicated SCEV rewrites for this loop.
6847     for (auto I = PredicatedSCEVRewrites.begin();
6848          I != PredicatedSCEVRewrites.end();) {
6849       std::pair<const SCEV *, const Loop *> Entry = I->first;
6850       if (Entry.second == CurrL)
6851         PredicatedSCEVRewrites.erase(I++);
6852       else
6853         ++I;
6854     }
6855 
6856     auto LoopUsersItr = LoopUsers.find(CurrL);
6857     if (LoopUsersItr != LoopUsers.end()) {
6858       for (auto *S : LoopUsersItr->second)
6859         forgetMemoizedResults(S);
6860       LoopUsers.erase(LoopUsersItr);
6861     }
6862 
6863     // Drop information about expressions based on loop-header PHIs.
6864     PushLoopPHIs(CurrL, Worklist);
6865 
6866     while (!Worklist.empty()) {
6867       Instruction *I = Worklist.pop_back_val();
6868       if (!Visited.insert(I).second)
6869         continue;
6870 
6871       ValueExprMapType::iterator It =
6872           ValueExprMap.find_as(static_cast<Value *>(I));
6873       if (It != ValueExprMap.end()) {
6874         eraseValueFromMap(It->first);
6875         forgetMemoizedResults(It->second);
6876         if (PHINode *PN = dyn_cast<PHINode>(I))
6877           ConstantEvolutionLoopExitValue.erase(PN);
6878       }
6879 
6880       PushDefUseChildren(I, Worklist);
6881     }
6882 
6883     LoopPropertiesCache.erase(CurrL);
6884     // Forget all contained loops too, to avoid dangling entries in the
6885     // ValuesAtScopes map.
6886     LoopWorklist.append(CurrL->begin(), CurrL->end());
6887   }
6888 }
6889 
6890 void ScalarEvolution::forgetTopmostLoop(const Loop *L) {
6891   while (Loop *Parent = L->getParentLoop())
6892     L = Parent;
6893   forgetLoop(L);
6894 }
6895 
6896 void ScalarEvolution::forgetValue(Value *V) {
6897   Instruction *I = dyn_cast<Instruction>(V);
6898   if (!I) return;
6899 
6900   // Drop information about expressions based on loop-header PHIs.
6901   SmallVector<Instruction *, 16> Worklist;
6902   Worklist.push_back(I);
6903 
6904   SmallPtrSet<Instruction *, 8> Visited;
6905   while (!Worklist.empty()) {
6906     I = Worklist.pop_back_val();
6907     if (!Visited.insert(I).second)
6908       continue;
6909 
6910     ValueExprMapType::iterator It =
6911       ValueExprMap.find_as(static_cast<Value *>(I));
6912     if (It != ValueExprMap.end()) {
6913       eraseValueFromMap(It->first);
6914       forgetMemoizedResults(It->second);
6915       if (PHINode *PN = dyn_cast<PHINode>(I))
6916         ConstantEvolutionLoopExitValue.erase(PN);
6917     }
6918 
6919     PushDefUseChildren(I, Worklist);
6920   }
6921 }
6922 
6923 /// Get the exact loop backedge taken count considering all loop exits. A
6924 /// computable result can only be returned for loops with all exiting blocks
6925 /// dominating the latch. howFarToZero assumes that the limit of each loop test
6926 /// is never skipped. This is a valid assumption as long as the loop exits via
6927 /// that test. For precise results, it is the caller's responsibility to specify
6928 /// the relevant loop exiting block using getExact(ExitingBlock, SE).
6929 const SCEV *
6930 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE,
6931                                              SCEVUnionPredicate *Preds) const {
6932   // If any exits were not computable, the loop is not computable.
6933   if (!isComplete() || ExitNotTaken.empty())
6934     return SE->getCouldNotCompute();
6935 
6936   const BasicBlock *Latch = L->getLoopLatch();
6937   // All exiting blocks we have collected must dominate the only backedge.
6938   if (!Latch)
6939     return SE->getCouldNotCompute();
6940 
6941   // All exiting blocks we have gathered dominate loop's latch, so exact trip
6942   // count is simply a minimum out of all these calculated exit counts.
6943   SmallVector<const SCEV *, 2> Ops;
6944   for (auto &ENT : ExitNotTaken) {
6945     const SCEV *BECount = ENT.ExactNotTaken;
6946     assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!");
6947     assert(SE->DT.dominates(ENT.ExitingBlock, Latch) &&
6948            "We should only have known counts for exiting blocks that dominate "
6949            "latch!");
6950 
6951     Ops.push_back(BECount);
6952 
6953     if (Preds && !ENT.hasAlwaysTruePredicate())
6954       Preds->add(ENT.Predicate.get());
6955 
6956     assert((Preds || ENT.hasAlwaysTruePredicate()) &&
6957            "Predicate should be always true!");
6958   }
6959 
6960   return SE->getUMinFromMismatchedTypes(Ops);
6961 }
6962 
6963 /// Get the exact not taken count for this loop exit.
6964 const SCEV *
6965 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock,
6966                                              ScalarEvolution *SE) const {
6967   for (auto &ENT : ExitNotTaken)
6968     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
6969       return ENT.ExactNotTaken;
6970 
6971   return SE->getCouldNotCompute();
6972 }
6973 
6974 const SCEV *
6975 ScalarEvolution::BackedgeTakenInfo::getMax(BasicBlock *ExitingBlock,
6976                                            ScalarEvolution *SE) const {
6977   for (auto &ENT : ExitNotTaken)
6978     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
6979       return ENT.MaxNotTaken;
6980 
6981   return SE->getCouldNotCompute();
6982 }
6983 
6984 /// getMax - Get the max backedge taken count for the loop.
6985 const SCEV *
6986 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const {
6987   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
6988     return !ENT.hasAlwaysTruePredicate();
6989   };
6990 
6991   if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax())
6992     return SE->getCouldNotCompute();
6993 
6994   assert((isa<SCEVCouldNotCompute>(getMax()) || isa<SCEVConstant>(getMax())) &&
6995          "No point in having a non-constant max backedge taken count!");
6996   return getMax();
6997 }
6998 
6999 bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const {
7000   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
7001     return !ENT.hasAlwaysTruePredicate();
7002   };
7003   return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
7004 }
7005 
7006 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S,
7007                                                     ScalarEvolution *SE) const {
7008   if (getMax() && getMax() != SE->getCouldNotCompute() &&
7009       SE->hasOperand(getMax(), S))
7010     return true;
7011 
7012   for (auto &ENT : ExitNotTaken)
7013     if (ENT.ExactNotTaken != SE->getCouldNotCompute() &&
7014         SE->hasOperand(ENT.ExactNotTaken, S))
7015       return true;
7016 
7017   return false;
7018 }
7019 
7020 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E)
7021     : ExactNotTaken(E), MaxNotTaken(E) {
7022   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
7023           isa<SCEVConstant>(MaxNotTaken)) &&
7024          "No point in having a non-constant max backedge taken count!");
7025 }
7026 
7027 ScalarEvolution::ExitLimit::ExitLimit(
7028     const SCEV *E, const SCEV *M, bool MaxOrZero,
7029     ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList)
7030     : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) {
7031   assert((isa<SCEVCouldNotCompute>(ExactNotTaken) ||
7032           !isa<SCEVCouldNotCompute>(MaxNotTaken)) &&
7033          "Exact is not allowed to be less precise than Max");
7034   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
7035           isa<SCEVConstant>(MaxNotTaken)) &&
7036          "No point in having a non-constant max backedge taken count!");
7037   for (auto *PredSet : PredSetList)
7038     for (auto *P : *PredSet)
7039       addPredicate(P);
7040 }
7041 
7042 ScalarEvolution::ExitLimit::ExitLimit(
7043     const SCEV *E, const SCEV *M, bool MaxOrZero,
7044     const SmallPtrSetImpl<const SCEVPredicate *> &PredSet)
7045     : ExitLimit(E, M, MaxOrZero, {&PredSet}) {
7046   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
7047           isa<SCEVConstant>(MaxNotTaken)) &&
7048          "No point in having a non-constant max backedge taken count!");
7049 }
7050 
7051 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M,
7052                                       bool MaxOrZero)
7053     : ExitLimit(E, M, MaxOrZero, None) {
7054   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
7055           isa<SCEVConstant>(MaxNotTaken)) &&
7056          "No point in having a non-constant max backedge taken count!");
7057 }
7058 
7059 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
7060 /// computable exit into a persistent ExitNotTakenInfo array.
7061 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
7062     ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo>
7063         ExitCounts,
7064     bool Complete, const SCEV *MaxCount, bool MaxOrZero)
7065     : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) {
7066   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
7067 
7068   ExitNotTaken.reserve(ExitCounts.size());
7069   std::transform(
7070       ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken),
7071       [&](const EdgeExitInfo &EEI) {
7072         BasicBlock *ExitBB = EEI.first;
7073         const ExitLimit &EL = EEI.second;
7074         if (EL.Predicates.empty())
7075           return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken,
7076                                   nullptr);
7077 
7078         std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate);
7079         for (auto *Pred : EL.Predicates)
7080           Predicate->add(Pred);
7081 
7082         return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken,
7083                                 std::move(Predicate));
7084       });
7085   assert((isa<SCEVCouldNotCompute>(MaxCount) || isa<SCEVConstant>(MaxCount)) &&
7086          "No point in having a non-constant max backedge taken count!");
7087 }
7088 
7089 /// Invalidate this result and free the ExitNotTakenInfo array.
7090 void ScalarEvolution::BackedgeTakenInfo::clear() {
7091   ExitNotTaken.clear();
7092 }
7093 
7094 /// Compute the number of times the backedge of the specified loop will execute.
7095 ScalarEvolution::BackedgeTakenInfo
7096 ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
7097                                            bool AllowPredicates) {
7098   SmallVector<BasicBlock *, 8> ExitingBlocks;
7099   L->getExitingBlocks(ExitingBlocks);
7100 
7101   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
7102 
7103   SmallVector<EdgeExitInfo, 4> ExitCounts;
7104   bool CouldComputeBECount = true;
7105   BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
7106   const SCEV *MustExitMaxBECount = nullptr;
7107   const SCEV *MayExitMaxBECount = nullptr;
7108   bool MustExitMaxOrZero = false;
7109 
7110   // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
7111   // and compute maxBECount.
7112   // Do a union of all the predicates here.
7113   for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
7114     BasicBlock *ExitBB = ExitingBlocks[i];
7115 
7116     // We canonicalize untaken exits to br (constant), ignore them so that
7117     // proving an exit untaken doesn't negatively impact our ability to reason
7118     // about the loop as whole.
7119     if (auto *BI = dyn_cast<BranchInst>(ExitBB->getTerminator()))
7120       if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
7121         bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
7122         if ((ExitIfTrue && CI->isZero()) || (!ExitIfTrue && CI->isOne()))
7123           continue;
7124       }
7125 
7126     ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
7127 
7128     assert((AllowPredicates || EL.Predicates.empty()) &&
7129            "Predicated exit limit when predicates are not allowed!");
7130 
7131     // 1. For each exit that can be computed, add an entry to ExitCounts.
7132     // CouldComputeBECount is true only if all exits can be computed.
7133     if (EL.ExactNotTaken == getCouldNotCompute())
7134       // We couldn't compute an exact value for this exit, so
7135       // we won't be able to compute an exact value for the loop.
7136       CouldComputeBECount = false;
7137     else
7138       ExitCounts.emplace_back(ExitBB, EL);
7139 
7140     // 2. Derive the loop's MaxBECount from each exit's max number of
7141     // non-exiting iterations. Partition the loop exits into two kinds:
7142     // LoopMustExits and LoopMayExits.
7143     //
7144     // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
7145     // is a LoopMayExit.  If any computable LoopMustExit is found, then
7146     // MaxBECount is the minimum EL.MaxNotTaken of computable
7147     // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
7148     // EL.MaxNotTaken, where CouldNotCompute is considered greater than any
7149     // computable EL.MaxNotTaken.
7150     if (EL.MaxNotTaken != getCouldNotCompute() && Latch &&
7151         DT.dominates(ExitBB, Latch)) {
7152       if (!MustExitMaxBECount) {
7153         MustExitMaxBECount = EL.MaxNotTaken;
7154         MustExitMaxOrZero = EL.MaxOrZero;
7155       } else {
7156         MustExitMaxBECount =
7157             getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken);
7158       }
7159     } else if (MayExitMaxBECount != getCouldNotCompute()) {
7160       if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute())
7161         MayExitMaxBECount = EL.MaxNotTaken;
7162       else {
7163         MayExitMaxBECount =
7164             getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken);
7165       }
7166     }
7167   }
7168   const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
7169     (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
7170   // The loop backedge will be taken the maximum or zero times if there's
7171   // a single exit that must be taken the maximum or zero times.
7172   bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
7173   return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
7174                            MaxBECount, MaxOrZero);
7175 }
7176 
7177 ScalarEvolution::ExitLimit
7178 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
7179                                       bool AllowPredicates) {
7180   assert(L->contains(ExitingBlock) && "Exit count for non-loop block?");
7181   // If our exiting block does not dominate the latch, then its connection with
7182   // loop's exit limit may be far from trivial.
7183   const BasicBlock *Latch = L->getLoopLatch();
7184   if (!Latch || !DT.dominates(ExitingBlock, Latch))
7185     return getCouldNotCompute();
7186 
7187   bool IsOnlyExit = (L->getExitingBlock() != nullptr);
7188   Instruction *Term = ExitingBlock->getTerminator();
7189   if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
7190     assert(BI->isConditional() && "If unconditional, it can't be in loop!");
7191     bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
7192     assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) &&
7193            "It should have one successor in loop and one exit block!");
7194     // Proceed to the next level to examine the exit condition expression.
7195     return computeExitLimitFromCond(
7196         L, BI->getCondition(), ExitIfTrue,
7197         /*ControlsExit=*/IsOnlyExit, AllowPredicates);
7198   }
7199 
7200   if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) {
7201     // For switch, make sure that there is a single exit from the loop.
7202     BasicBlock *Exit = nullptr;
7203     for (auto *SBB : successors(ExitingBlock))
7204       if (!L->contains(SBB)) {
7205         if (Exit) // Multiple exit successors.
7206           return getCouldNotCompute();
7207         Exit = SBB;
7208       }
7209     assert(Exit && "Exiting block must have at least one exit");
7210     return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
7211                                                 /*ControlsExit=*/IsOnlyExit);
7212   }
7213 
7214   return getCouldNotCompute();
7215 }
7216 
7217 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond(
7218     const Loop *L, Value *ExitCond, bool ExitIfTrue,
7219     bool ControlsExit, bool AllowPredicates) {
7220   ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates);
7221   return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue,
7222                                         ControlsExit, AllowPredicates);
7223 }
7224 
7225 Optional<ScalarEvolution::ExitLimit>
7226 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
7227                                       bool ExitIfTrue, bool ControlsExit,
7228                                       bool AllowPredicates) {
7229   (void)this->L;
7230   (void)this->ExitIfTrue;
7231   (void)this->AllowPredicates;
7232 
7233   assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
7234          this->AllowPredicates == AllowPredicates &&
7235          "Variance in assumed invariant key components!");
7236   auto Itr = TripCountMap.find({ExitCond, ControlsExit});
7237   if (Itr == TripCountMap.end())
7238     return None;
7239   return Itr->second;
7240 }
7241 
7242 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
7243                                              bool ExitIfTrue,
7244                                              bool ControlsExit,
7245                                              bool AllowPredicates,
7246                                              const ExitLimit &EL) {
7247   assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
7248          this->AllowPredicates == AllowPredicates &&
7249          "Variance in assumed invariant key components!");
7250 
7251   auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL});
7252   assert(InsertResult.second && "Expected successful insertion!");
7253   (void)InsertResult;
7254   (void)ExitIfTrue;
7255 }
7256 
7257 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
7258     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
7259     bool ControlsExit, bool AllowPredicates) {
7260 
7261   if (auto MaybeEL =
7262           Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates))
7263     return *MaybeEL;
7264 
7265   ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue,
7266                                               ControlsExit, AllowPredicates);
7267   Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL);
7268   return EL;
7269 }
7270 
7271 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
7272     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
7273     bool ControlsExit, bool AllowPredicates) {
7274   // Check if the controlling expression for this loop is an And or Or.
7275   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
7276     if (BO->getOpcode() == Instruction::And) {
7277       // Recurse on the operands of the and.
7278       bool EitherMayExit = !ExitIfTrue;
7279       ExitLimit EL0 = computeExitLimitFromCondCached(
7280           Cache, L, BO->getOperand(0), ExitIfTrue,
7281           ControlsExit && !EitherMayExit, AllowPredicates);
7282       ExitLimit EL1 = computeExitLimitFromCondCached(
7283           Cache, L, BO->getOperand(1), ExitIfTrue,
7284           ControlsExit && !EitherMayExit, AllowPredicates);
7285       // Be robust against unsimplified IR for the form "and i1 X, true"
7286       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1)))
7287         return CI->isOne() ? EL0 : EL1;
7288       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(0)))
7289         return CI->isOne() ? EL1 : EL0;
7290       const SCEV *BECount = getCouldNotCompute();
7291       const SCEV *MaxBECount = getCouldNotCompute();
7292       if (EitherMayExit) {
7293         // Both conditions must be true for the loop to continue executing.
7294         // Choose the less conservative count.
7295         if (EL0.ExactNotTaken == getCouldNotCompute() ||
7296             EL1.ExactNotTaken == getCouldNotCompute())
7297           BECount = getCouldNotCompute();
7298         else
7299           BECount =
7300               getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
7301         if (EL0.MaxNotTaken == getCouldNotCompute())
7302           MaxBECount = EL1.MaxNotTaken;
7303         else if (EL1.MaxNotTaken == getCouldNotCompute())
7304           MaxBECount = EL0.MaxNotTaken;
7305         else
7306           MaxBECount =
7307               getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
7308       } else {
7309         // Both conditions must be true at the same time for the loop to exit.
7310         // For now, be conservative.
7311         if (EL0.MaxNotTaken == EL1.MaxNotTaken)
7312           MaxBECount = EL0.MaxNotTaken;
7313         if (EL0.ExactNotTaken == EL1.ExactNotTaken)
7314           BECount = EL0.ExactNotTaken;
7315       }
7316 
7317       // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
7318       // to be more aggressive when computing BECount than when computing
7319       // MaxBECount.  In these cases it is possible for EL0.ExactNotTaken and
7320       // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
7321       // to not.
7322       if (isa<SCEVCouldNotCompute>(MaxBECount) &&
7323           !isa<SCEVCouldNotCompute>(BECount))
7324         MaxBECount = getConstant(getUnsignedRangeMax(BECount));
7325 
7326       return ExitLimit(BECount, MaxBECount, false,
7327                        {&EL0.Predicates, &EL1.Predicates});
7328     }
7329     if (BO->getOpcode() == Instruction::Or) {
7330       // Recurse on the operands of the or.
7331       bool EitherMayExit = ExitIfTrue;
7332       ExitLimit EL0 = computeExitLimitFromCondCached(
7333           Cache, L, BO->getOperand(0), ExitIfTrue,
7334           ControlsExit && !EitherMayExit, AllowPredicates);
7335       ExitLimit EL1 = computeExitLimitFromCondCached(
7336           Cache, L, BO->getOperand(1), ExitIfTrue,
7337           ControlsExit && !EitherMayExit, AllowPredicates);
7338       // Be robust against unsimplified IR for the form "or i1 X, true"
7339       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1)))
7340         return CI->isZero() ? EL0 : EL1;
7341       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(0)))
7342         return CI->isZero() ? EL1 : EL0;
7343       const SCEV *BECount = getCouldNotCompute();
7344       const SCEV *MaxBECount = getCouldNotCompute();
7345       if (EitherMayExit) {
7346         // Both conditions must be false for the loop to continue executing.
7347         // Choose the less conservative count.
7348         if (EL0.ExactNotTaken == getCouldNotCompute() ||
7349             EL1.ExactNotTaken == getCouldNotCompute())
7350           BECount = getCouldNotCompute();
7351         else
7352           BECount =
7353               getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
7354         if (EL0.MaxNotTaken == getCouldNotCompute())
7355           MaxBECount = EL1.MaxNotTaken;
7356         else if (EL1.MaxNotTaken == getCouldNotCompute())
7357           MaxBECount = EL0.MaxNotTaken;
7358         else
7359           MaxBECount =
7360               getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
7361       } else {
7362         // Both conditions must be false at the same time for the loop to exit.
7363         // For now, be conservative.
7364         if (EL0.MaxNotTaken == EL1.MaxNotTaken)
7365           MaxBECount = EL0.MaxNotTaken;
7366         if (EL0.ExactNotTaken == EL1.ExactNotTaken)
7367           BECount = EL0.ExactNotTaken;
7368       }
7369       // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
7370       // to be more aggressive when computing BECount than when computing
7371       // MaxBECount.  In these cases it is possible for EL0.ExactNotTaken and
7372       // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
7373       // to not.
7374       if (isa<SCEVCouldNotCompute>(MaxBECount) &&
7375           !isa<SCEVCouldNotCompute>(BECount))
7376         MaxBECount = getConstant(getUnsignedRangeMax(BECount));
7377 
7378       return ExitLimit(BECount, MaxBECount, false,
7379                        {&EL0.Predicates, &EL1.Predicates});
7380     }
7381   }
7382 
7383   // With an icmp, it may be feasible to compute an exact backedge-taken count.
7384   // Proceed to the next level to examine the icmp.
7385   if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
7386     ExitLimit EL =
7387         computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit);
7388     if (EL.hasFullInfo() || !AllowPredicates)
7389       return EL;
7390 
7391     // Try again, but use SCEV predicates this time.
7392     return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit,
7393                                     /*AllowPredicates=*/true);
7394   }
7395 
7396   // Check for a constant condition. These are normally stripped out by
7397   // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
7398   // preserve the CFG and is temporarily leaving constant conditions
7399   // in place.
7400   if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
7401     if (ExitIfTrue == !CI->getZExtValue())
7402       // The backedge is always taken.
7403       return getCouldNotCompute();
7404     else
7405       // The backedge is never taken.
7406       return getZero(CI->getType());
7407   }
7408 
7409   // If it's not an integer or pointer comparison then compute it the hard way.
7410   return computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
7411 }
7412 
7413 ScalarEvolution::ExitLimit
7414 ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
7415                                           ICmpInst *ExitCond,
7416                                           bool ExitIfTrue,
7417                                           bool ControlsExit,
7418                                           bool AllowPredicates) {
7419   // If the condition was exit on true, convert the condition to exit on false
7420   ICmpInst::Predicate Pred;
7421   if (!ExitIfTrue)
7422     Pred = ExitCond->getPredicate();
7423   else
7424     Pred = ExitCond->getInversePredicate();
7425   const ICmpInst::Predicate OriginalPred = Pred;
7426 
7427   // Handle common loops like: for (X = "string"; *X; ++X)
7428   if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
7429     if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
7430       ExitLimit ItCnt =
7431         computeLoadConstantCompareExitLimit(LI, RHS, L, Pred);
7432       if (ItCnt.hasAnyInfo())
7433         return ItCnt;
7434     }
7435 
7436   const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
7437   const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
7438 
7439   // Try to evaluate any dependencies out of the loop.
7440   LHS = getSCEVAtScope(LHS, L);
7441   RHS = getSCEVAtScope(RHS, L);
7442 
7443   // At this point, we would like to compute how many iterations of the
7444   // loop the predicate will return true for these inputs.
7445   if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
7446     // If there is a loop-invariant, force it into the RHS.
7447     std::swap(LHS, RHS);
7448     Pred = ICmpInst::getSwappedPredicate(Pred);
7449   }
7450 
7451   // Simplify the operands before analyzing them.
7452   (void)SimplifyICmpOperands(Pred, LHS, RHS);
7453 
7454   // If we have a comparison of a chrec against a constant, try to use value
7455   // ranges to answer this query.
7456   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
7457     if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
7458       if (AddRec->getLoop() == L) {
7459         // Form the constant range.
7460         ConstantRange CompRange =
7461             ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt());
7462 
7463         const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
7464         if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
7465       }
7466 
7467   switch (Pred) {
7468   case ICmpInst::ICMP_NE: {                     // while (X != Y)
7469     // Convert to: while (X-Y != 0)
7470     ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit,
7471                                 AllowPredicates);
7472     if (EL.hasAnyInfo()) return EL;
7473     break;
7474   }
7475   case ICmpInst::ICMP_EQ: {                     // while (X == Y)
7476     // Convert to: while (X-Y == 0)
7477     ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
7478     if (EL.hasAnyInfo()) return EL;
7479     break;
7480   }
7481   case ICmpInst::ICMP_SLT:
7482   case ICmpInst::ICMP_ULT: {                    // while (X < Y)
7483     bool IsSigned = Pred == ICmpInst::ICMP_SLT;
7484     ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit,
7485                                     AllowPredicates);
7486     if (EL.hasAnyInfo()) return EL;
7487     break;
7488   }
7489   case ICmpInst::ICMP_SGT:
7490   case ICmpInst::ICMP_UGT: {                    // while (X > Y)
7491     bool IsSigned = Pred == ICmpInst::ICMP_SGT;
7492     ExitLimit EL =
7493         howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
7494                             AllowPredicates);
7495     if (EL.hasAnyInfo()) return EL;
7496     break;
7497   }
7498   default:
7499     break;
7500   }
7501 
7502   auto *ExhaustiveCount =
7503       computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
7504 
7505   if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
7506     return ExhaustiveCount;
7507 
7508   return computeShiftCompareExitLimit(ExitCond->getOperand(0),
7509                                       ExitCond->getOperand(1), L, OriginalPred);
7510 }
7511 
7512 ScalarEvolution::ExitLimit
7513 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
7514                                                       SwitchInst *Switch,
7515                                                       BasicBlock *ExitingBlock,
7516                                                       bool ControlsExit) {
7517   assert(!L->contains(ExitingBlock) && "Not an exiting block!");
7518 
7519   // Give up if the exit is the default dest of a switch.
7520   if (Switch->getDefaultDest() == ExitingBlock)
7521     return getCouldNotCompute();
7522 
7523   assert(L->contains(Switch->getDefaultDest()) &&
7524          "Default case must not exit the loop!");
7525   const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
7526   const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
7527 
7528   // while (X != Y) --> while (X-Y != 0)
7529   ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
7530   if (EL.hasAnyInfo())
7531     return EL;
7532 
7533   return getCouldNotCompute();
7534 }
7535 
7536 static ConstantInt *
7537 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
7538                                 ScalarEvolution &SE) {
7539   const SCEV *InVal = SE.getConstant(C);
7540   const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
7541   assert(isa<SCEVConstant>(Val) &&
7542          "Evaluation of SCEV at constant didn't fold correctly?");
7543   return cast<SCEVConstant>(Val)->getValue();
7544 }
7545 
7546 /// Given an exit condition of 'icmp op load X, cst', try to see if we can
7547 /// compute the backedge execution count.
7548 ScalarEvolution::ExitLimit
7549 ScalarEvolution::computeLoadConstantCompareExitLimit(
7550   LoadInst *LI,
7551   Constant *RHS,
7552   const Loop *L,
7553   ICmpInst::Predicate predicate) {
7554   if (LI->isVolatile()) return getCouldNotCompute();
7555 
7556   // Check to see if the loaded pointer is a getelementptr of a global.
7557   // TODO: Use SCEV instead of manually grubbing with GEPs.
7558   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
7559   if (!GEP) return getCouldNotCompute();
7560 
7561   // Make sure that it is really a constant global we are gepping, with an
7562   // initializer, and make sure the first IDX is really 0.
7563   GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
7564   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
7565       GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
7566       !cast<Constant>(GEP->getOperand(1))->isNullValue())
7567     return getCouldNotCompute();
7568 
7569   // Okay, we allow one non-constant index into the GEP instruction.
7570   Value *VarIdx = nullptr;
7571   std::vector<Constant*> Indexes;
7572   unsigned VarIdxNum = 0;
7573   for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
7574     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
7575       Indexes.push_back(CI);
7576     } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
7577       if (VarIdx) return getCouldNotCompute();  // Multiple non-constant idx's.
7578       VarIdx = GEP->getOperand(i);
7579       VarIdxNum = i-2;
7580       Indexes.push_back(nullptr);
7581     }
7582 
7583   // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
7584   if (!VarIdx)
7585     return getCouldNotCompute();
7586 
7587   // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
7588   // Check to see if X is a loop variant variable value now.
7589   const SCEV *Idx = getSCEV(VarIdx);
7590   Idx = getSCEVAtScope(Idx, L);
7591 
7592   // We can only recognize very limited forms of loop index expressions, in
7593   // particular, only affine AddRec's like {C1,+,C2}.
7594   const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
7595   if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
7596       !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
7597       !isa<SCEVConstant>(IdxExpr->getOperand(1)))
7598     return getCouldNotCompute();
7599 
7600   unsigned MaxSteps = MaxBruteForceIterations;
7601   for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
7602     ConstantInt *ItCst = ConstantInt::get(
7603                            cast<IntegerType>(IdxExpr->getType()), IterationNum);
7604     ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
7605 
7606     // Form the GEP offset.
7607     Indexes[VarIdxNum] = Val;
7608 
7609     Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
7610                                                          Indexes);
7611     if (!Result) break;  // Cannot compute!
7612 
7613     // Evaluate the condition for this iteration.
7614     Result = ConstantExpr::getICmp(predicate, Result, RHS);
7615     if (!isa<ConstantInt>(Result)) break;  // Couldn't decide for sure
7616     if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
7617       ++NumArrayLenItCounts;
7618       return getConstant(ItCst);   // Found terminating iteration!
7619     }
7620   }
7621   return getCouldNotCompute();
7622 }
7623 
7624 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
7625     Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
7626   ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
7627   if (!RHS)
7628     return getCouldNotCompute();
7629 
7630   const BasicBlock *Latch = L->getLoopLatch();
7631   if (!Latch)
7632     return getCouldNotCompute();
7633 
7634   const BasicBlock *Predecessor = L->getLoopPredecessor();
7635   if (!Predecessor)
7636     return getCouldNotCompute();
7637 
7638   // Return true if V is of the form "LHS `shift_op` <positive constant>".
7639   // Return LHS in OutLHS and shift_opt in OutOpCode.
7640   auto MatchPositiveShift =
7641       [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
7642 
7643     using namespace PatternMatch;
7644 
7645     ConstantInt *ShiftAmt;
7646     if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7647       OutOpCode = Instruction::LShr;
7648     else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7649       OutOpCode = Instruction::AShr;
7650     else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7651       OutOpCode = Instruction::Shl;
7652     else
7653       return false;
7654 
7655     return ShiftAmt->getValue().isStrictlyPositive();
7656   };
7657 
7658   // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
7659   //
7660   // loop:
7661   //   %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
7662   //   %iv.shifted = lshr i32 %iv, <positive constant>
7663   //
7664   // Return true on a successful match.  Return the corresponding PHI node (%iv
7665   // above) in PNOut and the opcode of the shift operation in OpCodeOut.
7666   auto MatchShiftRecurrence =
7667       [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
7668     Optional<Instruction::BinaryOps> PostShiftOpCode;
7669 
7670     {
7671       Instruction::BinaryOps OpC;
7672       Value *V;
7673 
7674       // If we encounter a shift instruction, "peel off" the shift operation,
7675       // and remember that we did so.  Later when we inspect %iv's backedge
7676       // value, we will make sure that the backedge value uses the same
7677       // operation.
7678       //
7679       // Note: the peeled shift operation does not have to be the same
7680       // instruction as the one feeding into the PHI's backedge value.  We only
7681       // really care about it being the same *kind* of shift instruction --
7682       // that's all that is required for our later inferences to hold.
7683       if (MatchPositiveShift(LHS, V, OpC)) {
7684         PostShiftOpCode = OpC;
7685         LHS = V;
7686       }
7687     }
7688 
7689     PNOut = dyn_cast<PHINode>(LHS);
7690     if (!PNOut || PNOut->getParent() != L->getHeader())
7691       return false;
7692 
7693     Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
7694     Value *OpLHS;
7695 
7696     return
7697         // The backedge value for the PHI node must be a shift by a positive
7698         // amount
7699         MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
7700 
7701         // of the PHI node itself
7702         OpLHS == PNOut &&
7703 
7704         // and the kind of shift should be match the kind of shift we peeled
7705         // off, if any.
7706         (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut);
7707   };
7708 
7709   PHINode *PN;
7710   Instruction::BinaryOps OpCode;
7711   if (!MatchShiftRecurrence(LHS, PN, OpCode))
7712     return getCouldNotCompute();
7713 
7714   const DataLayout &DL = getDataLayout();
7715 
7716   // The key rationale for this optimization is that for some kinds of shift
7717   // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
7718   // within a finite number of iterations.  If the condition guarding the
7719   // backedge (in the sense that the backedge is taken if the condition is true)
7720   // is false for the value the shift recurrence stabilizes to, then we know
7721   // that the backedge is taken only a finite number of times.
7722 
7723   ConstantInt *StableValue = nullptr;
7724   switch (OpCode) {
7725   default:
7726     llvm_unreachable("Impossible case!");
7727 
7728   case Instruction::AShr: {
7729     // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
7730     // bitwidth(K) iterations.
7731     Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
7732     KnownBits Known = computeKnownBits(FirstValue, DL, 0, nullptr,
7733                                        Predecessor->getTerminator(), &DT);
7734     auto *Ty = cast<IntegerType>(RHS->getType());
7735     if (Known.isNonNegative())
7736       StableValue = ConstantInt::get(Ty, 0);
7737     else if (Known.isNegative())
7738       StableValue = ConstantInt::get(Ty, -1, true);
7739     else
7740       return getCouldNotCompute();
7741 
7742     break;
7743   }
7744   case Instruction::LShr:
7745   case Instruction::Shl:
7746     // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
7747     // stabilize to 0 in at most bitwidth(K) iterations.
7748     StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
7749     break;
7750   }
7751 
7752   auto *Result =
7753       ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
7754   assert(Result->getType()->isIntegerTy(1) &&
7755          "Otherwise cannot be an operand to a branch instruction");
7756 
7757   if (Result->isZeroValue()) {
7758     unsigned BitWidth = getTypeSizeInBits(RHS->getType());
7759     const SCEV *UpperBound =
7760         getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
7761     return ExitLimit(getCouldNotCompute(), UpperBound, false);
7762   }
7763 
7764   return getCouldNotCompute();
7765 }
7766 
7767 /// Return true if we can constant fold an instruction of the specified type,
7768 /// assuming that all operands were constants.
7769 static bool CanConstantFold(const Instruction *I) {
7770   if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
7771       isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
7772       isa<LoadInst>(I) || isa<ExtractValueInst>(I))
7773     return true;
7774 
7775   if (const CallInst *CI = dyn_cast<CallInst>(I))
7776     if (const Function *F = CI->getCalledFunction())
7777       return canConstantFoldCallTo(CI, F);
7778   return false;
7779 }
7780 
7781 /// Determine whether this instruction can constant evolve within this loop
7782 /// assuming its operands can all constant evolve.
7783 static bool canConstantEvolve(Instruction *I, const Loop *L) {
7784   // An instruction outside of the loop can't be derived from a loop PHI.
7785   if (!L->contains(I)) return false;
7786 
7787   if (isa<PHINode>(I)) {
7788     // We don't currently keep track of the control flow needed to evaluate
7789     // PHIs, so we cannot handle PHIs inside of loops.
7790     return L->getHeader() == I->getParent();
7791   }
7792 
7793   // If we won't be able to constant fold this expression even if the operands
7794   // are constants, bail early.
7795   return CanConstantFold(I);
7796 }
7797 
7798 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
7799 /// recursing through each instruction operand until reaching a loop header phi.
7800 static PHINode *
7801 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
7802                                DenseMap<Instruction *, PHINode *> &PHIMap,
7803                                unsigned Depth) {
7804   if (Depth > MaxConstantEvolvingDepth)
7805     return nullptr;
7806 
7807   // Otherwise, we can evaluate this instruction if all of its operands are
7808   // constant or derived from a PHI node themselves.
7809   PHINode *PHI = nullptr;
7810   for (Value *Op : UseInst->operands()) {
7811     if (isa<Constant>(Op)) continue;
7812 
7813     Instruction *OpInst = dyn_cast<Instruction>(Op);
7814     if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
7815 
7816     PHINode *P = dyn_cast<PHINode>(OpInst);
7817     if (!P)
7818       // If this operand is already visited, reuse the prior result.
7819       // We may have P != PHI if this is the deepest point at which the
7820       // inconsistent paths meet.
7821       P = PHIMap.lookup(OpInst);
7822     if (!P) {
7823       // Recurse and memoize the results, whether a phi is found or not.
7824       // This recursive call invalidates pointers into PHIMap.
7825       P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1);
7826       PHIMap[OpInst] = P;
7827     }
7828     if (!P)
7829       return nullptr;  // Not evolving from PHI
7830     if (PHI && PHI != P)
7831       return nullptr;  // Evolving from multiple different PHIs.
7832     PHI = P;
7833   }
7834   // This is a expression evolving from a constant PHI!
7835   return PHI;
7836 }
7837 
7838 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
7839 /// in the loop that V is derived from.  We allow arbitrary operations along the
7840 /// way, but the operands of an operation must either be constants or a value
7841 /// derived from a constant PHI.  If this expression does not fit with these
7842 /// constraints, return null.
7843 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
7844   Instruction *I = dyn_cast<Instruction>(V);
7845   if (!I || !canConstantEvolve(I, L)) return nullptr;
7846 
7847   if (PHINode *PN = dyn_cast<PHINode>(I))
7848     return PN;
7849 
7850   // Record non-constant instructions contained by the loop.
7851   DenseMap<Instruction *, PHINode *> PHIMap;
7852   return getConstantEvolvingPHIOperands(I, L, PHIMap, 0);
7853 }
7854 
7855 /// EvaluateExpression - Given an expression that passes the
7856 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
7857 /// in the loop has the value PHIVal.  If we can't fold this expression for some
7858 /// reason, return null.
7859 static Constant *EvaluateExpression(Value *V, const Loop *L,
7860                                     DenseMap<Instruction *, Constant *> &Vals,
7861                                     const DataLayout &DL,
7862                                     const TargetLibraryInfo *TLI) {
7863   // Convenient constant check, but redundant for recursive calls.
7864   if (Constant *C = dyn_cast<Constant>(V)) return C;
7865   Instruction *I = dyn_cast<Instruction>(V);
7866   if (!I) return nullptr;
7867 
7868   if (Constant *C = Vals.lookup(I)) return C;
7869 
7870   // An instruction inside the loop depends on a value outside the loop that we
7871   // weren't given a mapping for, or a value such as a call inside the loop.
7872   if (!canConstantEvolve(I, L)) return nullptr;
7873 
7874   // An unmapped PHI can be due to a branch or another loop inside this loop,
7875   // or due to this not being the initial iteration through a loop where we
7876   // couldn't compute the evolution of this particular PHI last time.
7877   if (isa<PHINode>(I)) return nullptr;
7878 
7879   std::vector<Constant*> Operands(I->getNumOperands());
7880 
7881   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
7882     Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
7883     if (!Operand) {
7884       Operands[i] = dyn_cast<Constant>(I->getOperand(i));
7885       if (!Operands[i]) return nullptr;
7886       continue;
7887     }
7888     Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
7889     Vals[Operand] = C;
7890     if (!C) return nullptr;
7891     Operands[i] = C;
7892   }
7893 
7894   if (CmpInst *CI = dyn_cast<CmpInst>(I))
7895     return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
7896                                            Operands[1], DL, TLI);
7897   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
7898     if (!LI->isVolatile())
7899       return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
7900   }
7901   return ConstantFoldInstOperands(I, Operands, DL, TLI);
7902 }
7903 
7904 
7905 // If every incoming value to PN except the one for BB is a specific Constant,
7906 // return that, else return nullptr.
7907 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
7908   Constant *IncomingVal = nullptr;
7909 
7910   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
7911     if (PN->getIncomingBlock(i) == BB)
7912       continue;
7913 
7914     auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
7915     if (!CurrentVal)
7916       return nullptr;
7917 
7918     if (IncomingVal != CurrentVal) {
7919       if (IncomingVal)
7920         return nullptr;
7921       IncomingVal = CurrentVal;
7922     }
7923   }
7924 
7925   return IncomingVal;
7926 }
7927 
7928 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
7929 /// in the header of its containing loop, we know the loop executes a
7930 /// constant number of times, and the PHI node is just a recurrence
7931 /// involving constants, fold it.
7932 Constant *
7933 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
7934                                                    const APInt &BEs,
7935                                                    const Loop *L) {
7936   auto I = ConstantEvolutionLoopExitValue.find(PN);
7937   if (I != ConstantEvolutionLoopExitValue.end())
7938     return I->second;
7939 
7940   if (BEs.ugt(MaxBruteForceIterations))
7941     return ConstantEvolutionLoopExitValue[PN] = nullptr;  // Not going to evaluate it.
7942 
7943   Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
7944 
7945   DenseMap<Instruction *, Constant *> CurrentIterVals;
7946   BasicBlock *Header = L->getHeader();
7947   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
7948 
7949   BasicBlock *Latch = L->getLoopLatch();
7950   if (!Latch)
7951     return nullptr;
7952 
7953   for (PHINode &PHI : Header->phis()) {
7954     if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
7955       CurrentIterVals[&PHI] = StartCST;
7956   }
7957   if (!CurrentIterVals.count(PN))
7958     return RetVal = nullptr;
7959 
7960   Value *BEValue = PN->getIncomingValueForBlock(Latch);
7961 
7962   // Execute the loop symbolically to determine the exit value.
7963   assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) &&
7964          "BEs is <= MaxBruteForceIterations which is an 'unsigned'!");
7965 
7966   unsigned NumIterations = BEs.getZExtValue(); // must be in range
7967   unsigned IterationNum = 0;
7968   const DataLayout &DL = getDataLayout();
7969   for (; ; ++IterationNum) {
7970     if (IterationNum == NumIterations)
7971       return RetVal = CurrentIterVals[PN];  // Got exit value!
7972 
7973     // Compute the value of the PHIs for the next iteration.
7974     // EvaluateExpression adds non-phi values to the CurrentIterVals map.
7975     DenseMap<Instruction *, Constant *> NextIterVals;
7976     Constant *NextPHI =
7977         EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
7978     if (!NextPHI)
7979       return nullptr;        // Couldn't evaluate!
7980     NextIterVals[PN] = NextPHI;
7981 
7982     bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
7983 
7984     // Also evaluate the other PHI nodes.  However, we don't get to stop if we
7985     // cease to be able to evaluate one of them or if they stop evolving,
7986     // because that doesn't necessarily prevent us from computing PN.
7987     SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
7988     for (const auto &I : CurrentIterVals) {
7989       PHINode *PHI = dyn_cast<PHINode>(I.first);
7990       if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
7991       PHIsToCompute.emplace_back(PHI, I.second);
7992     }
7993     // We use two distinct loops because EvaluateExpression may invalidate any
7994     // iterators into CurrentIterVals.
7995     for (const auto &I : PHIsToCompute) {
7996       PHINode *PHI = I.first;
7997       Constant *&NextPHI = NextIterVals[PHI];
7998       if (!NextPHI) {   // Not already computed.
7999         Value *BEValue = PHI->getIncomingValueForBlock(Latch);
8000         NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
8001       }
8002       if (NextPHI != I.second)
8003         StoppedEvolving = false;
8004     }
8005 
8006     // If all entries in CurrentIterVals == NextIterVals then we can stop
8007     // iterating, the loop can't continue to change.
8008     if (StoppedEvolving)
8009       return RetVal = CurrentIterVals[PN];
8010 
8011     CurrentIterVals.swap(NextIterVals);
8012   }
8013 }
8014 
8015 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
8016                                                           Value *Cond,
8017                                                           bool ExitWhen) {
8018   PHINode *PN = getConstantEvolvingPHI(Cond, L);
8019   if (!PN) return getCouldNotCompute();
8020 
8021   // If the loop is canonicalized, the PHI will have exactly two entries.
8022   // That's the only form we support here.
8023   if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
8024 
8025   DenseMap<Instruction *, Constant *> CurrentIterVals;
8026   BasicBlock *Header = L->getHeader();
8027   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
8028 
8029   BasicBlock *Latch = L->getLoopLatch();
8030   assert(Latch && "Should follow from NumIncomingValues == 2!");
8031 
8032   for (PHINode &PHI : Header->phis()) {
8033     if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
8034       CurrentIterVals[&PHI] = StartCST;
8035   }
8036   if (!CurrentIterVals.count(PN))
8037     return getCouldNotCompute();
8038 
8039   // Okay, we find a PHI node that defines the trip count of this loop.  Execute
8040   // the loop symbolically to determine when the condition gets a value of
8041   // "ExitWhen".
8042   unsigned MaxIterations = MaxBruteForceIterations;   // Limit analysis.
8043   const DataLayout &DL = getDataLayout();
8044   for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
8045     auto *CondVal = dyn_cast_or_null<ConstantInt>(
8046         EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
8047 
8048     // Couldn't symbolically evaluate.
8049     if (!CondVal) return getCouldNotCompute();
8050 
8051     if (CondVal->getValue() == uint64_t(ExitWhen)) {
8052       ++NumBruteForceTripCountsComputed;
8053       return getConstant(Type::getInt32Ty(getContext()), IterationNum);
8054     }
8055 
8056     // Update all the PHI nodes for the next iteration.
8057     DenseMap<Instruction *, Constant *> NextIterVals;
8058 
8059     // Create a list of which PHIs we need to compute. We want to do this before
8060     // calling EvaluateExpression on them because that may invalidate iterators
8061     // into CurrentIterVals.
8062     SmallVector<PHINode *, 8> PHIsToCompute;
8063     for (const auto &I : CurrentIterVals) {
8064       PHINode *PHI = dyn_cast<PHINode>(I.first);
8065       if (!PHI || PHI->getParent() != Header) continue;
8066       PHIsToCompute.push_back(PHI);
8067     }
8068     for (PHINode *PHI : PHIsToCompute) {
8069       Constant *&NextPHI = NextIterVals[PHI];
8070       if (NextPHI) continue;    // Already computed!
8071 
8072       Value *BEValue = PHI->getIncomingValueForBlock(Latch);
8073       NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
8074     }
8075     CurrentIterVals.swap(NextIterVals);
8076   }
8077 
8078   // Too many iterations were needed to evaluate.
8079   return getCouldNotCompute();
8080 }
8081 
8082 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
8083   SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
8084       ValuesAtScopes[V];
8085   // Check to see if we've folded this expression at this loop before.
8086   for (auto &LS : Values)
8087     if (LS.first == L)
8088       return LS.second ? LS.second : V;
8089 
8090   Values.emplace_back(L, nullptr);
8091 
8092   // Otherwise compute it.
8093   const SCEV *C = computeSCEVAtScope(V, L);
8094   for (auto &LS : reverse(ValuesAtScopes[V]))
8095     if (LS.first == L) {
8096       LS.second = C;
8097       break;
8098     }
8099   return C;
8100 }
8101 
8102 /// This builds up a Constant using the ConstantExpr interface.  That way, we
8103 /// will return Constants for objects which aren't represented by a
8104 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
8105 /// Returns NULL if the SCEV isn't representable as a Constant.
8106 static Constant *BuildConstantFromSCEV(const SCEV *V) {
8107   switch (static_cast<SCEVTypes>(V->getSCEVType())) {
8108     case scCouldNotCompute:
8109     case scAddRecExpr:
8110       break;
8111     case scConstant:
8112       return cast<SCEVConstant>(V)->getValue();
8113     case scUnknown:
8114       return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
8115     case scSignExtend: {
8116       const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
8117       if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
8118         return ConstantExpr::getSExt(CastOp, SS->getType());
8119       break;
8120     }
8121     case scZeroExtend: {
8122       const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
8123       if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
8124         return ConstantExpr::getZExt(CastOp, SZ->getType());
8125       break;
8126     }
8127     case scTruncate: {
8128       const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
8129       if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
8130         return ConstantExpr::getTrunc(CastOp, ST->getType());
8131       break;
8132     }
8133     case scAddExpr: {
8134       const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
8135       if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
8136         if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
8137           unsigned AS = PTy->getAddressSpace();
8138           Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
8139           C = ConstantExpr::getBitCast(C, DestPtrTy);
8140         }
8141         for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
8142           Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
8143           if (!C2) return nullptr;
8144 
8145           // First pointer!
8146           if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
8147             unsigned AS = C2->getType()->getPointerAddressSpace();
8148             std::swap(C, C2);
8149             Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
8150             // The offsets have been converted to bytes.  We can add bytes to an
8151             // i8* by GEP with the byte count in the first index.
8152             C = ConstantExpr::getBitCast(C, DestPtrTy);
8153           }
8154 
8155           // Don't bother trying to sum two pointers. We probably can't
8156           // statically compute a load that results from it anyway.
8157           if (C2->getType()->isPointerTy())
8158             return nullptr;
8159 
8160           if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
8161             if (PTy->getElementType()->isStructTy())
8162               C2 = ConstantExpr::getIntegerCast(
8163                   C2, Type::getInt32Ty(C->getContext()), true);
8164             C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2);
8165           } else
8166             C = ConstantExpr::getAdd(C, C2);
8167         }
8168         return C;
8169       }
8170       break;
8171     }
8172     case scMulExpr: {
8173       const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
8174       if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
8175         // Don't bother with pointers at all.
8176         if (C->getType()->isPointerTy()) return nullptr;
8177         for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
8178           Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
8179           if (!C2 || C2->getType()->isPointerTy()) return nullptr;
8180           C = ConstantExpr::getMul(C, C2);
8181         }
8182         return C;
8183       }
8184       break;
8185     }
8186     case scUDivExpr: {
8187       const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
8188       if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
8189         if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
8190           if (LHS->getType() == RHS->getType())
8191             return ConstantExpr::getUDiv(LHS, RHS);
8192       break;
8193     }
8194     case scSMaxExpr:
8195     case scUMaxExpr:
8196     case scSMinExpr:
8197     case scUMinExpr:
8198       break; // TODO: smax, umax, smin, umax.
8199   }
8200   return nullptr;
8201 }
8202 
8203 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
8204   if (isa<SCEVConstant>(V)) return V;
8205 
8206   // If this instruction is evolved from a constant-evolving PHI, compute the
8207   // exit value from the loop without using SCEVs.
8208   if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
8209     if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
8210       if (PHINode *PN = dyn_cast<PHINode>(I)) {
8211         const Loop *LI = this->LI[I->getParent()];
8212         // Looking for loop exit value.
8213         if (LI && LI->getParentLoop() == L &&
8214             PN->getParent() == LI->getHeader()) {
8215           // Okay, there is no closed form solution for the PHI node.  Check
8216           // to see if the loop that contains it has a known backedge-taken
8217           // count.  If so, we may be able to force computation of the exit
8218           // value.
8219           const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
8220           // This trivial case can show up in some degenerate cases where
8221           // the incoming IR has not yet been fully simplified.
8222           if (BackedgeTakenCount->isZero()) {
8223             Value *InitValue = nullptr;
8224             bool MultipleInitValues = false;
8225             for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
8226               if (!LI->contains(PN->getIncomingBlock(i))) {
8227                 if (!InitValue)
8228                   InitValue = PN->getIncomingValue(i);
8229                 else if (InitValue != PN->getIncomingValue(i)) {
8230                   MultipleInitValues = true;
8231                   break;
8232                 }
8233               }
8234             }
8235             if (!MultipleInitValues && InitValue)
8236               return getSCEV(InitValue);
8237           }
8238           // Do we have a loop invariant value flowing around the backedge
8239           // for a loop which must execute the backedge?
8240           if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
8241               isKnownPositive(BackedgeTakenCount) &&
8242               PN->getNumIncomingValues() == 2) {
8243             unsigned InLoopPred = LI->contains(PN->getIncomingBlock(0)) ? 0 : 1;
8244             const SCEV *OnBackedge = getSCEV(PN->getIncomingValue(InLoopPred));
8245             if (IsAvailableOnEntry(LI, DT, OnBackedge, PN->getParent()))
8246               return OnBackedge;
8247           }
8248           if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
8249             // Okay, we know how many times the containing loop executes.  If
8250             // this is a constant evolving PHI node, get the final value at
8251             // the specified iteration number.
8252             Constant *RV =
8253                 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI);
8254             if (RV) return getSCEV(RV);
8255           }
8256         }
8257 
8258         // If there is a single-input Phi, evaluate it at our scope. If we can
8259         // prove that this replacement does not break LCSSA form, use new value.
8260         if (PN->getNumOperands() == 1) {
8261           const SCEV *Input = getSCEV(PN->getOperand(0));
8262           const SCEV *InputAtScope = getSCEVAtScope(Input, L);
8263           // TODO: We can generalize it using LI.replacementPreservesLCSSAForm,
8264           // for the simplest case just support constants.
8265           if (isa<SCEVConstant>(InputAtScope)) return InputAtScope;
8266         }
8267       }
8268 
8269       // Okay, this is an expression that we cannot symbolically evaluate
8270       // into a SCEV.  Check to see if it's possible to symbolically evaluate
8271       // the arguments into constants, and if so, try to constant propagate the
8272       // result.  This is particularly useful for computing loop exit values.
8273       if (CanConstantFold(I)) {
8274         SmallVector<Constant *, 4> Operands;
8275         bool MadeImprovement = false;
8276         for (Value *Op : I->operands()) {
8277           if (Constant *C = dyn_cast<Constant>(Op)) {
8278             Operands.push_back(C);
8279             continue;
8280           }
8281 
8282           // If any of the operands is non-constant and if they are
8283           // non-integer and non-pointer, don't even try to analyze them
8284           // with scev techniques.
8285           if (!isSCEVable(Op->getType()))
8286             return V;
8287 
8288           const SCEV *OrigV = getSCEV(Op);
8289           const SCEV *OpV = getSCEVAtScope(OrigV, L);
8290           MadeImprovement |= OrigV != OpV;
8291 
8292           Constant *C = BuildConstantFromSCEV(OpV);
8293           if (!C) return V;
8294           if (C->getType() != Op->getType())
8295             C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
8296                                                               Op->getType(),
8297                                                               false),
8298                                       C, Op->getType());
8299           Operands.push_back(C);
8300         }
8301 
8302         // Check to see if getSCEVAtScope actually made an improvement.
8303         if (MadeImprovement) {
8304           Constant *C = nullptr;
8305           const DataLayout &DL = getDataLayout();
8306           if (const CmpInst *CI = dyn_cast<CmpInst>(I))
8307             C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
8308                                                 Operands[1], DL, &TLI);
8309           else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
8310             if (!LI->isVolatile())
8311               C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
8312           } else
8313             C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
8314           if (!C) return V;
8315           return getSCEV(C);
8316         }
8317       }
8318     }
8319 
8320     // This is some other type of SCEVUnknown, just return it.
8321     return V;
8322   }
8323 
8324   if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
8325     // Avoid performing the look-up in the common case where the specified
8326     // expression has no loop-variant portions.
8327     for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
8328       const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
8329       if (OpAtScope != Comm->getOperand(i)) {
8330         // Okay, at least one of these operands is loop variant but might be
8331         // foldable.  Build a new instance of the folded commutative expression.
8332         SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
8333                                             Comm->op_begin()+i);
8334         NewOps.push_back(OpAtScope);
8335 
8336         for (++i; i != e; ++i) {
8337           OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
8338           NewOps.push_back(OpAtScope);
8339         }
8340         if (isa<SCEVAddExpr>(Comm))
8341           return getAddExpr(NewOps, Comm->getNoWrapFlags());
8342         if (isa<SCEVMulExpr>(Comm))
8343           return getMulExpr(NewOps, Comm->getNoWrapFlags());
8344         if (isa<SCEVMinMaxExpr>(Comm))
8345           return getMinMaxExpr(Comm->getSCEVType(), NewOps);
8346         llvm_unreachable("Unknown commutative SCEV type!");
8347       }
8348     }
8349     // If we got here, all operands are loop invariant.
8350     return Comm;
8351   }
8352 
8353   if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
8354     const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
8355     const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
8356     if (LHS == Div->getLHS() && RHS == Div->getRHS())
8357       return Div;   // must be loop invariant
8358     return getUDivExpr(LHS, RHS);
8359   }
8360 
8361   // If this is a loop recurrence for a loop that does not contain L, then we
8362   // are dealing with the final value computed by the loop.
8363   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
8364     // First, attempt to evaluate each operand.
8365     // Avoid performing the look-up in the common case where the specified
8366     // expression has no loop-variant portions.
8367     for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
8368       const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
8369       if (OpAtScope == AddRec->getOperand(i))
8370         continue;
8371 
8372       // Okay, at least one of these operands is loop variant but might be
8373       // foldable.  Build a new instance of the folded commutative expression.
8374       SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
8375                                           AddRec->op_begin()+i);
8376       NewOps.push_back(OpAtScope);
8377       for (++i; i != e; ++i)
8378         NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
8379 
8380       const SCEV *FoldedRec =
8381         getAddRecExpr(NewOps, AddRec->getLoop(),
8382                       AddRec->getNoWrapFlags(SCEV::FlagNW));
8383       AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
8384       // The addrec may be folded to a nonrecurrence, for example, if the
8385       // induction variable is multiplied by zero after constant folding. Go
8386       // ahead and return the folded value.
8387       if (!AddRec)
8388         return FoldedRec;
8389       break;
8390     }
8391 
8392     // If the scope is outside the addrec's loop, evaluate it by using the
8393     // loop exit value of the addrec.
8394     if (!AddRec->getLoop()->contains(L)) {
8395       // To evaluate this recurrence, we need to know how many times the AddRec
8396       // loop iterates.  Compute this now.
8397       const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
8398       if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
8399 
8400       // Then, evaluate the AddRec.
8401       return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
8402     }
8403 
8404     return AddRec;
8405   }
8406 
8407   if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
8408     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8409     if (Op == Cast->getOperand())
8410       return Cast;  // must be loop invariant
8411     return getZeroExtendExpr(Op, Cast->getType());
8412   }
8413 
8414   if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
8415     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8416     if (Op == Cast->getOperand())
8417       return Cast;  // must be loop invariant
8418     return getSignExtendExpr(Op, Cast->getType());
8419   }
8420 
8421   if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
8422     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8423     if (Op == Cast->getOperand())
8424       return Cast;  // must be loop invariant
8425     return getTruncateExpr(Op, Cast->getType());
8426   }
8427 
8428   llvm_unreachable("Unknown SCEV type!");
8429 }
8430 
8431 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
8432   return getSCEVAtScope(getSCEV(V), L);
8433 }
8434 
8435 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const {
8436   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S))
8437     return stripInjectiveFunctions(ZExt->getOperand());
8438   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S))
8439     return stripInjectiveFunctions(SExt->getOperand());
8440   return S;
8441 }
8442 
8443 /// Finds the minimum unsigned root of the following equation:
8444 ///
8445 ///     A * X = B (mod N)
8446 ///
8447 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
8448 /// A and B isn't important.
8449 ///
8450 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
8451 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B,
8452                                                ScalarEvolution &SE) {
8453   uint32_t BW = A.getBitWidth();
8454   assert(BW == SE.getTypeSizeInBits(B->getType()));
8455   assert(A != 0 && "A must be non-zero.");
8456 
8457   // 1. D = gcd(A, N)
8458   //
8459   // The gcd of A and N may have only one prime factor: 2. The number of
8460   // trailing zeros in A is its multiplicity
8461   uint32_t Mult2 = A.countTrailingZeros();
8462   // D = 2^Mult2
8463 
8464   // 2. Check if B is divisible by D.
8465   //
8466   // B is divisible by D if and only if the multiplicity of prime factor 2 for B
8467   // is not less than multiplicity of this prime factor for D.
8468   if (SE.GetMinTrailingZeros(B) < Mult2)
8469     return SE.getCouldNotCompute();
8470 
8471   // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
8472   // modulo (N / D).
8473   //
8474   // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
8475   // (N / D) in general. The inverse itself always fits into BW bits, though,
8476   // so we immediately truncate it.
8477   APInt AD = A.lshr(Mult2).zext(BW + 1);  // AD = A / D
8478   APInt Mod(BW + 1, 0);
8479   Mod.setBit(BW - Mult2);  // Mod = N / D
8480   APInt I = AD.multiplicativeInverse(Mod).trunc(BW);
8481 
8482   // 4. Compute the minimum unsigned root of the equation:
8483   // I * (B / D) mod (N / D)
8484   // To simplify the computation, we factor out the divide by D:
8485   // (I * B mod N) / D
8486   const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
8487   return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
8488 }
8489 
8490 /// For a given quadratic addrec, generate coefficients of the corresponding
8491 /// quadratic equation, multiplied by a common value to ensure that they are
8492 /// integers.
8493 /// The returned value is a tuple { A, B, C, M, BitWidth }, where
8494 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C
8495 /// were multiplied by, and BitWidth is the bit width of the original addrec
8496 /// coefficients.
8497 /// This function returns None if the addrec coefficients are not compile-
8498 /// time constants.
8499 static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>>
8500 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) {
8501   assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
8502   const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
8503   const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
8504   const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
8505   LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: "
8506                     << *AddRec << '\n');
8507 
8508   // We currently can only solve this if the coefficients are constants.
8509   if (!LC || !MC || !NC) {
8510     LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n");
8511     return None;
8512   }
8513 
8514   APInt L = LC->getAPInt();
8515   APInt M = MC->getAPInt();
8516   APInt N = NC->getAPInt();
8517   assert(!N.isNullValue() && "This is not a quadratic addrec");
8518 
8519   unsigned BitWidth = LC->getAPInt().getBitWidth();
8520   unsigned NewWidth = BitWidth + 1;
8521   LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: "
8522                     << BitWidth << '\n');
8523   // The sign-extension (as opposed to a zero-extension) here matches the
8524   // extension used in SolveQuadraticEquationWrap (with the same motivation).
8525   N = N.sext(NewWidth);
8526   M = M.sext(NewWidth);
8527   L = L.sext(NewWidth);
8528 
8529   // The increments are M, M+N, M+2N, ..., so the accumulated values are
8530   //   L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is,
8531   //   L+M, L+2M+N, L+3M+3N, ...
8532   // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N.
8533   //
8534   // The equation Acc = 0 is then
8535   //   L + nM + n(n-1)/2 N = 0,  or  2L + 2M n + n(n-1) N = 0.
8536   // In a quadratic form it becomes:
8537   //   N n^2 + (2M-N) n + 2L = 0.
8538 
8539   APInt A = N;
8540   APInt B = 2 * M - A;
8541   APInt C = 2 * L;
8542   APInt T = APInt(NewWidth, 2);
8543   LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B
8544                     << "x + " << C << ", coeff bw: " << NewWidth
8545                     << ", multiplied by " << T << '\n');
8546   return std::make_tuple(A, B, C, T, BitWidth);
8547 }
8548 
8549 /// Helper function to compare optional APInts:
8550 /// (a) if X and Y both exist, return min(X, Y),
8551 /// (b) if neither X nor Y exist, return None,
8552 /// (c) if exactly one of X and Y exists, return that value.
8553 static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) {
8554   if (X.hasValue() && Y.hasValue()) {
8555     unsigned W = std::max(X->getBitWidth(), Y->getBitWidth());
8556     APInt XW = X->sextOrSelf(W);
8557     APInt YW = Y->sextOrSelf(W);
8558     return XW.slt(YW) ? *X : *Y;
8559   }
8560   if (!X.hasValue() && !Y.hasValue())
8561     return None;
8562   return X.hasValue() ? *X : *Y;
8563 }
8564 
8565 /// Helper function to truncate an optional APInt to a given BitWidth.
8566 /// When solving addrec-related equations, it is preferable to return a value
8567 /// that has the same bit width as the original addrec's coefficients. If the
8568 /// solution fits in the original bit width, truncate it (except for i1).
8569 /// Returning a value of a different bit width may inhibit some optimizations.
8570 ///
8571 /// In general, a solution to a quadratic equation generated from an addrec
8572 /// may require BW+1 bits, where BW is the bit width of the addrec's
8573 /// coefficients. The reason is that the coefficients of the quadratic
8574 /// equation are BW+1 bits wide (to avoid truncation when converting from
8575 /// the addrec to the equation).
8576 static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) {
8577   if (!X.hasValue())
8578     return None;
8579   unsigned W = X->getBitWidth();
8580   if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth))
8581     return X->trunc(BitWidth);
8582   return X;
8583 }
8584 
8585 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n
8586 /// iterations. The values L, M, N are assumed to be signed, and they
8587 /// should all have the same bit widths.
8588 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW,
8589 /// where BW is the bit width of the addrec's coefficients.
8590 /// If the calculated value is a BW-bit integer (for BW > 1), it will be
8591 /// returned as such, otherwise the bit width of the returned value may
8592 /// be greater than BW.
8593 ///
8594 /// This function returns None if
8595 /// (a) the addrec coefficients are not constant, or
8596 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases
8597 ///     like x^2 = 5, no integer solutions exist, in other cases an integer
8598 ///     solution may exist, but SolveQuadraticEquationWrap may fail to find it.
8599 static Optional<APInt>
8600 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
8601   APInt A, B, C, M;
8602   unsigned BitWidth;
8603   auto T = GetQuadraticEquation(AddRec);
8604   if (!T.hasValue())
8605     return None;
8606 
8607   std::tie(A, B, C, M, BitWidth) = *T;
8608   LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n");
8609   Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1);
8610   if (!X.hasValue())
8611     return None;
8612 
8613   ConstantInt *CX = ConstantInt::get(SE.getContext(), *X);
8614   ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE);
8615   if (!V->isZero())
8616     return None;
8617 
8618   return TruncIfPossible(X, BitWidth);
8619 }
8620 
8621 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n
8622 /// iterations. The values M, N are assumed to be signed, and they
8623 /// should all have the same bit widths.
8624 /// Find the least n such that c(n) does not belong to the given range,
8625 /// while c(n-1) does.
8626 ///
8627 /// This function returns None if
8628 /// (a) the addrec coefficients are not constant, or
8629 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the
8630 ///     bounds of the range.
8631 static Optional<APInt>
8632 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec,
8633                           const ConstantRange &Range, ScalarEvolution &SE) {
8634   assert(AddRec->getOperand(0)->isZero() &&
8635          "Starting value of addrec should be 0");
8636   LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range "
8637                     << Range << ", addrec " << *AddRec << '\n');
8638   // This case is handled in getNumIterationsInRange. Here we can assume that
8639   // we start in the range.
8640   assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) &&
8641          "Addrec's initial value should be in range");
8642 
8643   APInt A, B, C, M;
8644   unsigned BitWidth;
8645   auto T = GetQuadraticEquation(AddRec);
8646   if (!T.hasValue())
8647     return None;
8648 
8649   // Be careful about the return value: there can be two reasons for not
8650   // returning an actual number. First, if no solutions to the equations
8651   // were found, and second, if the solutions don't leave the given range.
8652   // The first case means that the actual solution is "unknown", the second
8653   // means that it's known, but not valid. If the solution is unknown, we
8654   // cannot make any conclusions.
8655   // Return a pair: the optional solution and a flag indicating if the
8656   // solution was found.
8657   auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> {
8658     // Solve for signed overflow and unsigned overflow, pick the lower
8659     // solution.
8660     LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary "
8661                       << Bound << " (before multiplying by " << M << ")\n");
8662     Bound *= M; // The quadratic equation multiplier.
8663 
8664     Optional<APInt> SO = None;
8665     if (BitWidth > 1) {
8666       LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
8667                            "signed overflow\n");
8668       SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth);
8669     }
8670     LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
8671                          "unsigned overflow\n");
8672     Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound,
8673                                                               BitWidth+1);
8674 
8675     auto LeavesRange = [&] (const APInt &X) {
8676       ConstantInt *C0 = ConstantInt::get(SE.getContext(), X);
8677       ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE);
8678       if (Range.contains(V0->getValue()))
8679         return false;
8680       // X should be at least 1, so X-1 is non-negative.
8681       ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1);
8682       ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE);
8683       if (Range.contains(V1->getValue()))
8684         return true;
8685       return false;
8686     };
8687 
8688     // If SolveQuadraticEquationWrap returns None, it means that there can
8689     // be a solution, but the function failed to find it. We cannot treat it
8690     // as "no solution".
8691     if (!SO.hasValue() || !UO.hasValue())
8692       return { None, false };
8693 
8694     // Check the smaller value first to see if it leaves the range.
8695     // At this point, both SO and UO must have values.
8696     Optional<APInt> Min = MinOptional(SO, UO);
8697     if (LeavesRange(*Min))
8698       return { Min, true };
8699     Optional<APInt> Max = Min == SO ? UO : SO;
8700     if (LeavesRange(*Max))
8701       return { Max, true };
8702 
8703     // Solutions were found, but were eliminated, hence the "true".
8704     return { None, true };
8705   };
8706 
8707   std::tie(A, B, C, M, BitWidth) = *T;
8708   // Lower bound is inclusive, subtract 1 to represent the exiting value.
8709   APInt Lower = Range.getLower().sextOrSelf(A.getBitWidth()) - 1;
8710   APInt Upper = Range.getUpper().sextOrSelf(A.getBitWidth());
8711   auto SL = SolveForBoundary(Lower);
8712   auto SU = SolveForBoundary(Upper);
8713   // If any of the solutions was unknown, no meaninigful conclusions can
8714   // be made.
8715   if (!SL.second || !SU.second)
8716     return None;
8717 
8718   // Claim: The correct solution is not some value between Min and Max.
8719   //
8720   // Justification: Assuming that Min and Max are different values, one of
8721   // them is when the first signed overflow happens, the other is when the
8722   // first unsigned overflow happens. Crossing the range boundary is only
8723   // possible via an overflow (treating 0 as a special case of it, modeling
8724   // an overflow as crossing k*2^W for some k).
8725   //
8726   // The interesting case here is when Min was eliminated as an invalid
8727   // solution, but Max was not. The argument is that if there was another
8728   // overflow between Min and Max, it would also have been eliminated if
8729   // it was considered.
8730   //
8731   // For a given boundary, it is possible to have two overflows of the same
8732   // type (signed/unsigned) without having the other type in between: this
8733   // can happen when the vertex of the parabola is between the iterations
8734   // corresponding to the overflows. This is only possible when the two
8735   // overflows cross k*2^W for the same k. In such case, if the second one
8736   // left the range (and was the first one to do so), the first overflow
8737   // would have to enter the range, which would mean that either we had left
8738   // the range before or that we started outside of it. Both of these cases
8739   // are contradictions.
8740   //
8741   // Claim: In the case where SolveForBoundary returns None, the correct
8742   // solution is not some value between the Max for this boundary and the
8743   // Min of the other boundary.
8744   //
8745   // Justification: Assume that we had such Max_A and Min_B corresponding
8746   // to range boundaries A and B and such that Max_A < Min_B. If there was
8747   // a solution between Max_A and Min_B, it would have to be caused by an
8748   // overflow corresponding to either A or B. It cannot correspond to B,
8749   // since Min_B is the first occurrence of such an overflow. If it
8750   // corresponded to A, it would have to be either a signed or an unsigned
8751   // overflow that is larger than both eliminated overflows for A. But
8752   // between the eliminated overflows and this overflow, the values would
8753   // cover the entire value space, thus crossing the other boundary, which
8754   // is a contradiction.
8755 
8756   return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth);
8757 }
8758 
8759 ScalarEvolution::ExitLimit
8760 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit,
8761                               bool AllowPredicates) {
8762 
8763   // This is only used for loops with a "x != y" exit test. The exit condition
8764   // is now expressed as a single expression, V = x-y. So the exit test is
8765   // effectively V != 0.  We know and take advantage of the fact that this
8766   // expression only being used in a comparison by zero context.
8767 
8768   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
8769   // If the value is a constant
8770   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
8771     // If the value is already zero, the branch will execute zero times.
8772     if (C->getValue()->isZero()) return C;
8773     return getCouldNotCompute();  // Otherwise it will loop infinitely.
8774   }
8775 
8776   const SCEVAddRecExpr *AddRec =
8777       dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V));
8778 
8779   if (!AddRec && AllowPredicates)
8780     // Try to make this an AddRec using runtime tests, in the first X
8781     // iterations of this loop, where X is the SCEV expression found by the
8782     // algorithm below.
8783     AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
8784 
8785   if (!AddRec || AddRec->getLoop() != L)
8786     return getCouldNotCompute();
8787 
8788   // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
8789   // the quadratic equation to solve it.
8790   if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
8791     // We can only use this value if the chrec ends up with an exact zero
8792     // value at this index.  When solving for "X*X != 5", for example, we
8793     // should not accept a root of 2.
8794     if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) {
8795       const auto *R = cast<SCEVConstant>(getConstant(S.getValue()));
8796       return ExitLimit(R, R, false, Predicates);
8797     }
8798     return getCouldNotCompute();
8799   }
8800 
8801   // Otherwise we can only handle this if it is affine.
8802   if (!AddRec->isAffine())
8803     return getCouldNotCompute();
8804 
8805   // If this is an affine expression, the execution count of this branch is
8806   // the minimum unsigned root of the following equation:
8807   //
8808   //     Start + Step*N = 0 (mod 2^BW)
8809   //
8810   // equivalent to:
8811   //
8812   //             Step*N = -Start (mod 2^BW)
8813   //
8814   // where BW is the common bit width of Start and Step.
8815 
8816   // Get the initial value for the loop.
8817   const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
8818   const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
8819 
8820   // For now we handle only constant steps.
8821   //
8822   // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
8823   // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
8824   // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
8825   // We have not yet seen any such cases.
8826   const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
8827   if (!StepC || StepC->getValue()->isZero())
8828     return getCouldNotCompute();
8829 
8830   // For positive steps (counting up until unsigned overflow):
8831   //   N = -Start/Step (as unsigned)
8832   // For negative steps (counting down to zero):
8833   //   N = Start/-Step
8834   // First compute the unsigned distance from zero in the direction of Step.
8835   bool CountDown = StepC->getAPInt().isNegative();
8836   const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
8837 
8838   // Handle unitary steps, which cannot wraparound.
8839   // 1*N = -Start; -1*N = Start (mod 2^BW), so:
8840   //   N = Distance (as unsigned)
8841   if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) {
8842     APInt MaxBECount = getUnsignedRangeMax(Distance);
8843 
8844     // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
8845     // we end up with a loop whose backedge-taken count is n - 1.  Detect this
8846     // case, and see if we can improve the bound.
8847     //
8848     // Explicitly handling this here is necessary because getUnsignedRange
8849     // isn't context-sensitive; it doesn't know that we only care about the
8850     // range inside the loop.
8851     const SCEV *Zero = getZero(Distance->getType());
8852     const SCEV *One = getOne(Distance->getType());
8853     const SCEV *DistancePlusOne = getAddExpr(Distance, One);
8854     if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
8855       // If Distance + 1 doesn't overflow, we can compute the maximum distance
8856       // as "unsigned_max(Distance + 1) - 1".
8857       ConstantRange CR = getUnsignedRange(DistancePlusOne);
8858       MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1);
8859     }
8860     return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates);
8861   }
8862 
8863   // If the condition controls loop exit (the loop exits only if the expression
8864   // is true) and the addition is no-wrap we can use unsigned divide to
8865   // compute the backedge count.  In this case, the step may not divide the
8866   // distance, but we don't care because if the condition is "missed" the loop
8867   // will have undefined behavior due to wrapping.
8868   if (ControlsExit && AddRec->hasNoSelfWrap() &&
8869       loopHasNoAbnormalExits(AddRec->getLoop())) {
8870     const SCEV *Exact =
8871         getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
8872     const SCEV *Max =
8873         Exact == getCouldNotCompute()
8874             ? Exact
8875             : getConstant(getUnsignedRangeMax(Exact));
8876     return ExitLimit(Exact, Max, false, Predicates);
8877   }
8878 
8879   // Solve the general equation.
8880   const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(),
8881                                                getNegativeSCEV(Start), *this);
8882   const SCEV *M = E == getCouldNotCompute()
8883                       ? E
8884                       : getConstant(getUnsignedRangeMax(E));
8885   return ExitLimit(E, M, false, Predicates);
8886 }
8887 
8888 ScalarEvolution::ExitLimit
8889 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
8890   // Loops that look like: while (X == 0) are very strange indeed.  We don't
8891   // handle them yet except for the trivial case.  This could be expanded in the
8892   // future as needed.
8893 
8894   // If the value is a constant, check to see if it is known to be non-zero
8895   // already.  If so, the backedge will execute zero times.
8896   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
8897     if (!C->getValue()->isZero())
8898       return getZero(C->getType());
8899     return getCouldNotCompute();  // Otherwise it will loop infinitely.
8900   }
8901 
8902   // We could implement others, but I really doubt anyone writes loops like
8903   // this, and if they did, they would already be constant folded.
8904   return getCouldNotCompute();
8905 }
8906 
8907 std::pair<BasicBlock *, BasicBlock *>
8908 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
8909   // If the block has a unique predecessor, then there is no path from the
8910   // predecessor to the block that does not go through the direct edge
8911   // from the predecessor to the block.
8912   if (BasicBlock *Pred = BB->getSinglePredecessor())
8913     return {Pred, BB};
8914 
8915   // A loop's header is defined to be a block that dominates the loop.
8916   // If the header has a unique predecessor outside the loop, it must be
8917   // a block that has exactly one successor that can reach the loop.
8918   if (Loop *L = LI.getLoopFor(BB))
8919     return {L->getLoopPredecessor(), L->getHeader()};
8920 
8921   return {nullptr, nullptr};
8922 }
8923 
8924 /// SCEV structural equivalence is usually sufficient for testing whether two
8925 /// expressions are equal, however for the purposes of looking for a condition
8926 /// guarding a loop, it can be useful to be a little more general, since a
8927 /// front-end may have replicated the controlling expression.
8928 static bool HasSameValue(const SCEV *A, const SCEV *B) {
8929   // Quick check to see if they are the same SCEV.
8930   if (A == B) return true;
8931 
8932   auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
8933     // Not all instructions that are "identical" compute the same value.  For
8934     // instance, two distinct alloca instructions allocating the same type are
8935     // identical and do not read memory; but compute distinct values.
8936     return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
8937   };
8938 
8939   // Otherwise, if they're both SCEVUnknown, it's possible that they hold
8940   // two different instructions with the same value. Check for this case.
8941   if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
8942     if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
8943       if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
8944         if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
8945           if (ComputesEqualValues(AI, BI))
8946             return true;
8947 
8948   // Otherwise assume they may have a different value.
8949   return false;
8950 }
8951 
8952 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
8953                                            const SCEV *&LHS, const SCEV *&RHS,
8954                                            unsigned Depth) {
8955   bool Changed = false;
8956   // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or
8957   // '0 != 0'.
8958   auto TrivialCase = [&](bool TriviallyTrue) {
8959     LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
8960     Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
8961     return true;
8962   };
8963   // If we hit the max recursion limit bail out.
8964   if (Depth >= 3)
8965     return false;
8966 
8967   // Canonicalize a constant to the right side.
8968   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
8969     // Check for both operands constant.
8970     if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
8971       if (ConstantExpr::getICmp(Pred,
8972                                 LHSC->getValue(),
8973                                 RHSC->getValue())->isNullValue())
8974         return TrivialCase(false);
8975       else
8976         return TrivialCase(true);
8977     }
8978     // Otherwise swap the operands to put the constant on the right.
8979     std::swap(LHS, RHS);
8980     Pred = ICmpInst::getSwappedPredicate(Pred);
8981     Changed = true;
8982   }
8983 
8984   // If we're comparing an addrec with a value which is loop-invariant in the
8985   // addrec's loop, put the addrec on the left. Also make a dominance check,
8986   // as both operands could be addrecs loop-invariant in each other's loop.
8987   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
8988     const Loop *L = AR->getLoop();
8989     if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
8990       std::swap(LHS, RHS);
8991       Pred = ICmpInst::getSwappedPredicate(Pred);
8992       Changed = true;
8993     }
8994   }
8995 
8996   // If there's a constant operand, canonicalize comparisons with boundary
8997   // cases, and canonicalize *-or-equal comparisons to regular comparisons.
8998   if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
8999     const APInt &RA = RC->getAPInt();
9000 
9001     bool SimplifiedByConstantRange = false;
9002 
9003     if (!ICmpInst::isEquality(Pred)) {
9004       ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA);
9005       if (ExactCR.isFullSet())
9006         return TrivialCase(true);
9007       else if (ExactCR.isEmptySet())
9008         return TrivialCase(false);
9009 
9010       APInt NewRHS;
9011       CmpInst::Predicate NewPred;
9012       if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
9013           ICmpInst::isEquality(NewPred)) {
9014         // We were able to convert an inequality to an equality.
9015         Pred = NewPred;
9016         RHS = getConstant(NewRHS);
9017         Changed = SimplifiedByConstantRange = true;
9018       }
9019     }
9020 
9021     if (!SimplifiedByConstantRange) {
9022       switch (Pred) {
9023       default:
9024         break;
9025       case ICmpInst::ICMP_EQ:
9026       case ICmpInst::ICMP_NE:
9027         // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
9028         if (!RA)
9029           if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
9030             if (const SCEVMulExpr *ME =
9031                     dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
9032               if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
9033                   ME->getOperand(0)->isAllOnesValue()) {
9034                 RHS = AE->getOperand(1);
9035                 LHS = ME->getOperand(1);
9036                 Changed = true;
9037               }
9038         break;
9039 
9040 
9041         // The "Should have been caught earlier!" messages refer to the fact
9042         // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
9043         // should have fired on the corresponding cases, and canonicalized the
9044         // check to trivial case.
9045 
9046       case ICmpInst::ICMP_UGE:
9047         assert(!RA.isMinValue() && "Should have been caught earlier!");
9048         Pred = ICmpInst::ICMP_UGT;
9049         RHS = getConstant(RA - 1);
9050         Changed = true;
9051         break;
9052       case ICmpInst::ICMP_ULE:
9053         assert(!RA.isMaxValue() && "Should have been caught earlier!");
9054         Pred = ICmpInst::ICMP_ULT;
9055         RHS = getConstant(RA + 1);
9056         Changed = true;
9057         break;
9058       case ICmpInst::ICMP_SGE:
9059         assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
9060         Pred = ICmpInst::ICMP_SGT;
9061         RHS = getConstant(RA - 1);
9062         Changed = true;
9063         break;
9064       case ICmpInst::ICMP_SLE:
9065         assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
9066         Pred = ICmpInst::ICMP_SLT;
9067         RHS = getConstant(RA + 1);
9068         Changed = true;
9069         break;
9070       }
9071     }
9072   }
9073 
9074   // Check for obvious equality.
9075   if (HasSameValue(LHS, RHS)) {
9076     if (ICmpInst::isTrueWhenEqual(Pred))
9077       return TrivialCase(true);
9078     if (ICmpInst::isFalseWhenEqual(Pred))
9079       return TrivialCase(false);
9080   }
9081 
9082   // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
9083   // adding or subtracting 1 from one of the operands.
9084   switch (Pred) {
9085   case ICmpInst::ICMP_SLE:
9086     if (!getSignedRangeMax(RHS).isMaxSignedValue()) {
9087       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
9088                        SCEV::FlagNSW);
9089       Pred = ICmpInst::ICMP_SLT;
9090       Changed = true;
9091     } else if (!getSignedRangeMin(LHS).isMinSignedValue()) {
9092       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
9093                        SCEV::FlagNSW);
9094       Pred = ICmpInst::ICMP_SLT;
9095       Changed = true;
9096     }
9097     break;
9098   case ICmpInst::ICMP_SGE:
9099     if (!getSignedRangeMin(RHS).isMinSignedValue()) {
9100       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
9101                        SCEV::FlagNSW);
9102       Pred = ICmpInst::ICMP_SGT;
9103       Changed = true;
9104     } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) {
9105       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
9106                        SCEV::FlagNSW);
9107       Pred = ICmpInst::ICMP_SGT;
9108       Changed = true;
9109     }
9110     break;
9111   case ICmpInst::ICMP_ULE:
9112     if (!getUnsignedRangeMax(RHS).isMaxValue()) {
9113       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
9114                        SCEV::FlagNUW);
9115       Pred = ICmpInst::ICMP_ULT;
9116       Changed = true;
9117     } else if (!getUnsignedRangeMin(LHS).isMinValue()) {
9118       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
9119       Pred = ICmpInst::ICMP_ULT;
9120       Changed = true;
9121     }
9122     break;
9123   case ICmpInst::ICMP_UGE:
9124     if (!getUnsignedRangeMin(RHS).isMinValue()) {
9125       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
9126       Pred = ICmpInst::ICMP_UGT;
9127       Changed = true;
9128     } else if (!getUnsignedRangeMax(LHS).isMaxValue()) {
9129       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
9130                        SCEV::FlagNUW);
9131       Pred = ICmpInst::ICMP_UGT;
9132       Changed = true;
9133     }
9134     break;
9135   default:
9136     break;
9137   }
9138 
9139   // TODO: More simplifications are possible here.
9140 
9141   // Recursively simplify until we either hit a recursion limit or nothing
9142   // changes.
9143   if (Changed)
9144     return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
9145 
9146   return Changed;
9147 }
9148 
9149 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
9150   return getSignedRangeMax(S).isNegative();
9151 }
9152 
9153 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
9154   return getSignedRangeMin(S).isStrictlyPositive();
9155 }
9156 
9157 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
9158   return !getSignedRangeMin(S).isNegative();
9159 }
9160 
9161 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
9162   return !getSignedRangeMax(S).isStrictlyPositive();
9163 }
9164 
9165 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
9166   return isKnownNegative(S) || isKnownPositive(S);
9167 }
9168 
9169 std::pair<const SCEV *, const SCEV *>
9170 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) {
9171   // Compute SCEV on entry of loop L.
9172   const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this);
9173   if (Start == getCouldNotCompute())
9174     return { Start, Start };
9175   // Compute post increment SCEV for loop L.
9176   const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this);
9177   assert(PostInc != getCouldNotCompute() && "Unexpected could not compute");
9178   return { Start, PostInc };
9179 }
9180 
9181 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred,
9182                                           const SCEV *LHS, const SCEV *RHS) {
9183   // First collect all loops.
9184   SmallPtrSet<const Loop *, 8> LoopsUsed;
9185   getUsedLoops(LHS, LoopsUsed);
9186   getUsedLoops(RHS, LoopsUsed);
9187 
9188   if (LoopsUsed.empty())
9189     return false;
9190 
9191   // Domination relationship must be a linear order on collected loops.
9192 #ifndef NDEBUG
9193   for (auto *L1 : LoopsUsed)
9194     for (auto *L2 : LoopsUsed)
9195       assert((DT.dominates(L1->getHeader(), L2->getHeader()) ||
9196               DT.dominates(L2->getHeader(), L1->getHeader())) &&
9197              "Domination relationship is not a linear order");
9198 #endif
9199 
9200   const Loop *MDL =
9201       *std::max_element(LoopsUsed.begin(), LoopsUsed.end(),
9202                         [&](const Loop *L1, const Loop *L2) {
9203          return DT.properlyDominates(L1->getHeader(), L2->getHeader());
9204        });
9205 
9206   // Get init and post increment value for LHS.
9207   auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS);
9208   // if LHS contains unknown non-invariant SCEV then bail out.
9209   if (SplitLHS.first == getCouldNotCompute())
9210     return false;
9211   assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC");
9212   // Get init and post increment value for RHS.
9213   auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS);
9214   // if RHS contains unknown non-invariant SCEV then bail out.
9215   if (SplitRHS.first == getCouldNotCompute())
9216     return false;
9217   assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC");
9218   // It is possible that init SCEV contains an invariant load but it does
9219   // not dominate MDL and is not available at MDL loop entry, so we should
9220   // check it here.
9221   if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) ||
9222       !isAvailableAtLoopEntry(SplitRHS.first, MDL))
9223     return false;
9224 
9225   return isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first) &&
9226          isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second,
9227                                      SplitRHS.second);
9228 }
9229 
9230 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
9231                                        const SCEV *LHS, const SCEV *RHS) {
9232   // Canonicalize the inputs first.
9233   (void)SimplifyICmpOperands(Pred, LHS, RHS);
9234 
9235   if (isKnownViaInduction(Pred, LHS, RHS))
9236     return true;
9237 
9238   if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
9239     return true;
9240 
9241   // Otherwise see what can be done with some simple reasoning.
9242   return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS);
9243 }
9244 
9245 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred,
9246                                               const SCEVAddRecExpr *LHS,
9247                                               const SCEV *RHS) {
9248   const Loop *L = LHS->getLoop();
9249   return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) &&
9250          isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS);
9251 }
9252 
9253 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS,
9254                                            ICmpInst::Predicate Pred,
9255                                            bool &Increasing) {
9256   bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing);
9257 
9258 #ifndef NDEBUG
9259   // Verify an invariant: inverting the predicate should turn a monotonically
9260   // increasing change to a monotonically decreasing one, and vice versa.
9261   bool IncreasingSwapped;
9262   bool ResultSwapped = isMonotonicPredicateImpl(
9263       LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped);
9264 
9265   assert(Result == ResultSwapped && "should be able to analyze both!");
9266   if (ResultSwapped)
9267     assert(Increasing == !IncreasingSwapped &&
9268            "monotonicity should flip as we flip the predicate");
9269 #endif
9270 
9271   return Result;
9272 }
9273 
9274 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS,
9275                                                ICmpInst::Predicate Pred,
9276                                                bool &Increasing) {
9277 
9278   // A zero step value for LHS means the induction variable is essentially a
9279   // loop invariant value. We don't really depend on the predicate actually
9280   // flipping from false to true (for increasing predicates, and the other way
9281   // around for decreasing predicates), all we care about is that *if* the
9282   // predicate changes then it only changes from false to true.
9283   //
9284   // A zero step value in itself is not very useful, but there may be places
9285   // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
9286   // as general as possible.
9287 
9288   switch (Pred) {
9289   default:
9290     return false; // Conservative answer
9291 
9292   case ICmpInst::ICMP_UGT:
9293   case ICmpInst::ICMP_UGE:
9294   case ICmpInst::ICMP_ULT:
9295   case ICmpInst::ICMP_ULE:
9296     if (!LHS->hasNoUnsignedWrap())
9297       return false;
9298 
9299     Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE;
9300     return true;
9301 
9302   case ICmpInst::ICMP_SGT:
9303   case ICmpInst::ICMP_SGE:
9304   case ICmpInst::ICMP_SLT:
9305   case ICmpInst::ICMP_SLE: {
9306     if (!LHS->hasNoSignedWrap())
9307       return false;
9308 
9309     const SCEV *Step = LHS->getStepRecurrence(*this);
9310 
9311     if (isKnownNonNegative(Step)) {
9312       Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE;
9313       return true;
9314     }
9315 
9316     if (isKnownNonPositive(Step)) {
9317       Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE;
9318       return true;
9319     }
9320 
9321     return false;
9322   }
9323 
9324   }
9325 
9326   llvm_unreachable("switch has default clause!");
9327 }
9328 
9329 bool ScalarEvolution::isLoopInvariantPredicate(
9330     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
9331     ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS,
9332     const SCEV *&InvariantRHS) {
9333 
9334   // If there is a loop-invariant, force it into the RHS, otherwise bail out.
9335   if (!isLoopInvariant(RHS, L)) {
9336     if (!isLoopInvariant(LHS, L))
9337       return false;
9338 
9339     std::swap(LHS, RHS);
9340     Pred = ICmpInst::getSwappedPredicate(Pred);
9341   }
9342 
9343   const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
9344   if (!ArLHS || ArLHS->getLoop() != L)
9345     return false;
9346 
9347   bool Increasing;
9348   if (!isMonotonicPredicate(ArLHS, Pred, Increasing))
9349     return false;
9350 
9351   // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
9352   // true as the loop iterates, and the backedge is control dependent on
9353   // "ArLHS `Pred` RHS" == true then we can reason as follows:
9354   //
9355   //   * if the predicate was false in the first iteration then the predicate
9356   //     is never evaluated again, since the loop exits without taking the
9357   //     backedge.
9358   //   * if the predicate was true in the first iteration then it will
9359   //     continue to be true for all future iterations since it is
9360   //     monotonically increasing.
9361   //
9362   // For both the above possibilities, we can replace the loop varying
9363   // predicate with its value on the first iteration of the loop (which is
9364   // loop invariant).
9365   //
9366   // A similar reasoning applies for a monotonically decreasing predicate, by
9367   // replacing true with false and false with true in the above two bullets.
9368 
9369   auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
9370 
9371   if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
9372     return false;
9373 
9374   InvariantPred = Pred;
9375   InvariantLHS = ArLHS->getStart();
9376   InvariantRHS = RHS;
9377   return true;
9378 }
9379 
9380 bool ScalarEvolution::isKnownPredicateViaConstantRanges(
9381     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
9382   if (HasSameValue(LHS, RHS))
9383     return ICmpInst::isTrueWhenEqual(Pred);
9384 
9385   // This code is split out from isKnownPredicate because it is called from
9386   // within isLoopEntryGuardedByCond.
9387 
9388   auto CheckRanges =
9389       [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) {
9390     return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS)
9391         .contains(RangeLHS);
9392   };
9393 
9394   // The check at the top of the function catches the case where the values are
9395   // known to be equal.
9396   if (Pred == CmpInst::ICMP_EQ)
9397     return false;
9398 
9399   if (Pred == CmpInst::ICMP_NE)
9400     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) ||
9401            CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) ||
9402            isKnownNonZero(getMinusSCEV(LHS, RHS));
9403 
9404   if (CmpInst::isSigned(Pred))
9405     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS));
9406 
9407   return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS));
9408 }
9409 
9410 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
9411                                                     const SCEV *LHS,
9412                                                     const SCEV *RHS) {
9413   // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer.
9414   // Return Y via OutY.
9415   auto MatchBinaryAddToConst =
9416       [this](const SCEV *Result, const SCEV *X, APInt &OutY,
9417              SCEV::NoWrapFlags ExpectedFlags) {
9418     const SCEV *NonConstOp, *ConstOp;
9419     SCEV::NoWrapFlags FlagsPresent;
9420 
9421     if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) ||
9422         !isa<SCEVConstant>(ConstOp) || NonConstOp != X)
9423       return false;
9424 
9425     OutY = cast<SCEVConstant>(ConstOp)->getAPInt();
9426     return (FlagsPresent & ExpectedFlags) == ExpectedFlags;
9427   };
9428 
9429   APInt C;
9430 
9431   switch (Pred) {
9432   default:
9433     break;
9434 
9435   case ICmpInst::ICMP_SGE:
9436     std::swap(LHS, RHS);
9437     LLVM_FALLTHROUGH;
9438   case ICmpInst::ICMP_SLE:
9439     // X s<= (X + C)<nsw> if C >= 0
9440     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative())
9441       return true;
9442 
9443     // (X + C)<nsw> s<= X if C <= 0
9444     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) &&
9445         !C.isStrictlyPositive())
9446       return true;
9447     break;
9448 
9449   case ICmpInst::ICMP_SGT:
9450     std::swap(LHS, RHS);
9451     LLVM_FALLTHROUGH;
9452   case ICmpInst::ICMP_SLT:
9453     // X s< (X + C)<nsw> if C > 0
9454     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) &&
9455         C.isStrictlyPositive())
9456       return true;
9457 
9458     // (X + C)<nsw> s< X if C < 0
9459     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative())
9460       return true;
9461     break;
9462   }
9463 
9464   return false;
9465 }
9466 
9467 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
9468                                                    const SCEV *LHS,
9469                                                    const SCEV *RHS) {
9470   if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
9471     return false;
9472 
9473   // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
9474   // the stack can result in exponential time complexity.
9475   SaveAndRestore<bool> Restore(ProvingSplitPredicate, true);
9476 
9477   // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
9478   //
9479   // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
9480   // isKnownPredicate.  isKnownPredicate is more powerful, but also more
9481   // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
9482   // interesting cases seen in practice.  We can consider "upgrading" L >= 0 to
9483   // use isKnownPredicate later if needed.
9484   return isKnownNonNegative(RHS) &&
9485          isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
9486          isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
9487 }
9488 
9489 bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB,
9490                                         ICmpInst::Predicate Pred,
9491                                         const SCEV *LHS, const SCEV *RHS) {
9492   // No need to even try if we know the module has no guards.
9493   if (!HasGuards)
9494     return false;
9495 
9496   return any_of(*BB, [&](Instruction &I) {
9497     using namespace llvm::PatternMatch;
9498 
9499     Value *Condition;
9500     return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
9501                          m_Value(Condition))) &&
9502            isImpliedCond(Pred, LHS, RHS, Condition, false);
9503   });
9504 }
9505 
9506 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
9507 /// protected by a conditional between LHS and RHS.  This is used to
9508 /// to eliminate casts.
9509 bool
9510 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
9511                                              ICmpInst::Predicate Pred,
9512                                              const SCEV *LHS, const SCEV *RHS) {
9513   // Interpret a null as meaning no loop, where there is obviously no guard
9514   // (interprocedural conditions notwithstanding).
9515   if (!L) return true;
9516 
9517   if (VerifyIR)
9518     assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) &&
9519            "This cannot be done on broken IR!");
9520 
9521 
9522   if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
9523     return true;
9524 
9525   BasicBlock *Latch = L->getLoopLatch();
9526   if (!Latch)
9527     return false;
9528 
9529   BranchInst *LoopContinuePredicate =
9530     dyn_cast<BranchInst>(Latch->getTerminator());
9531   if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
9532       isImpliedCond(Pred, LHS, RHS,
9533                     LoopContinuePredicate->getCondition(),
9534                     LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
9535     return true;
9536 
9537   // We don't want more than one activation of the following loops on the stack
9538   // -- that can lead to O(n!) time complexity.
9539   if (WalkingBEDominatingConds)
9540     return false;
9541 
9542   SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true);
9543 
9544   // See if we can exploit a trip count to prove the predicate.
9545   const auto &BETakenInfo = getBackedgeTakenInfo(L);
9546   const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
9547   if (LatchBECount != getCouldNotCompute()) {
9548     // We know that Latch branches back to the loop header exactly
9549     // LatchBECount times.  This means the backdege condition at Latch is
9550     // equivalent to  "{0,+,1} u< LatchBECount".
9551     Type *Ty = LatchBECount->getType();
9552     auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
9553     const SCEV *LoopCounter =
9554       getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
9555     if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
9556                       LatchBECount))
9557       return true;
9558   }
9559 
9560   // Check conditions due to any @llvm.assume intrinsics.
9561   for (auto &AssumeVH : AC.assumptions()) {
9562     if (!AssumeVH)
9563       continue;
9564     auto *CI = cast<CallInst>(AssumeVH);
9565     if (!DT.dominates(CI, Latch->getTerminator()))
9566       continue;
9567 
9568     if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
9569       return true;
9570   }
9571 
9572   // If the loop is not reachable from the entry block, we risk running into an
9573   // infinite loop as we walk up into the dom tree.  These loops do not matter
9574   // anyway, so we just return a conservative answer when we see them.
9575   if (!DT.isReachableFromEntry(L->getHeader()))
9576     return false;
9577 
9578   if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
9579     return true;
9580 
9581   for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
9582        DTN != HeaderDTN; DTN = DTN->getIDom()) {
9583     assert(DTN && "should reach the loop header before reaching the root!");
9584 
9585     BasicBlock *BB = DTN->getBlock();
9586     if (isImpliedViaGuard(BB, Pred, LHS, RHS))
9587       return true;
9588 
9589     BasicBlock *PBB = BB->getSinglePredecessor();
9590     if (!PBB)
9591       continue;
9592 
9593     BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
9594     if (!ContinuePredicate || !ContinuePredicate->isConditional())
9595       continue;
9596 
9597     Value *Condition = ContinuePredicate->getCondition();
9598 
9599     // If we have an edge `E` within the loop body that dominates the only
9600     // latch, the condition guarding `E` also guards the backedge.  This
9601     // reasoning works only for loops with a single latch.
9602 
9603     BasicBlockEdge DominatingEdge(PBB, BB);
9604     if (DominatingEdge.isSingleEdge()) {
9605       // We're constructively (and conservatively) enumerating edges within the
9606       // loop body that dominate the latch.  The dominator tree better agree
9607       // with us on this:
9608       assert(DT.dominates(DominatingEdge, Latch) && "should be!");
9609 
9610       if (isImpliedCond(Pred, LHS, RHS, Condition,
9611                         BB != ContinuePredicate->getSuccessor(0)))
9612         return true;
9613     }
9614   }
9615 
9616   return false;
9617 }
9618 
9619 bool
9620 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
9621                                           ICmpInst::Predicate Pred,
9622                                           const SCEV *LHS, const SCEV *RHS) {
9623   // Interpret a null as meaning no loop, where there is obviously no guard
9624   // (interprocedural conditions notwithstanding).
9625   if (!L) return false;
9626 
9627   if (VerifyIR)
9628     assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) &&
9629            "This cannot be done on broken IR!");
9630 
9631   // Both LHS and RHS must be available at loop entry.
9632   assert(isAvailableAtLoopEntry(LHS, L) &&
9633          "LHS is not available at Loop Entry");
9634   assert(isAvailableAtLoopEntry(RHS, L) &&
9635          "RHS is not available at Loop Entry");
9636 
9637   if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
9638     return true;
9639 
9640   // If we cannot prove strict comparison (e.g. a > b), maybe we can prove
9641   // the facts (a >= b && a != b) separately. A typical situation is when the
9642   // non-strict comparison is known from ranges and non-equality is known from
9643   // dominating predicates. If we are proving strict comparison, we always try
9644   // to prove non-equality and non-strict comparison separately.
9645   auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred);
9646   const bool ProvingStrictComparison = (Pred != NonStrictPredicate);
9647   bool ProvedNonStrictComparison = false;
9648   bool ProvedNonEquality = false;
9649 
9650   if (ProvingStrictComparison) {
9651     ProvedNonStrictComparison =
9652         isKnownViaNonRecursiveReasoning(NonStrictPredicate, LHS, RHS);
9653     ProvedNonEquality =
9654         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, LHS, RHS);
9655     if (ProvedNonStrictComparison && ProvedNonEquality)
9656       return true;
9657   }
9658 
9659   // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard.
9660   auto ProveViaGuard = [&](BasicBlock *Block) {
9661     if (isImpliedViaGuard(Block, Pred, LHS, RHS))
9662       return true;
9663     if (ProvingStrictComparison) {
9664       if (!ProvedNonStrictComparison)
9665         ProvedNonStrictComparison =
9666             isImpliedViaGuard(Block, NonStrictPredicate, LHS, RHS);
9667       if (!ProvedNonEquality)
9668         ProvedNonEquality =
9669             isImpliedViaGuard(Block, ICmpInst::ICMP_NE, LHS, RHS);
9670       if (ProvedNonStrictComparison && ProvedNonEquality)
9671         return true;
9672     }
9673     return false;
9674   };
9675 
9676   // Try to prove (Pred, LHS, RHS) using isImpliedCond.
9677   auto ProveViaCond = [&](Value *Condition, bool Inverse) {
9678     if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse))
9679       return true;
9680     if (ProvingStrictComparison) {
9681       if (!ProvedNonStrictComparison)
9682         ProvedNonStrictComparison =
9683             isImpliedCond(NonStrictPredicate, LHS, RHS, Condition, Inverse);
9684       if (!ProvedNonEquality)
9685         ProvedNonEquality =
9686             isImpliedCond(ICmpInst::ICMP_NE, LHS, RHS, Condition, Inverse);
9687       if (ProvedNonStrictComparison && ProvedNonEquality)
9688         return true;
9689     }
9690     return false;
9691   };
9692 
9693   // Starting at the loop predecessor, climb up the predecessor chain, as long
9694   // as there are predecessors that can be found that have unique successors
9695   // leading to the original header.
9696   for (std::pair<BasicBlock *, BasicBlock *>
9697          Pair(L->getLoopPredecessor(), L->getHeader());
9698        Pair.first;
9699        Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
9700 
9701     if (ProveViaGuard(Pair.first))
9702       return true;
9703 
9704     BranchInst *LoopEntryPredicate =
9705       dyn_cast<BranchInst>(Pair.first->getTerminator());
9706     if (!LoopEntryPredicate ||
9707         LoopEntryPredicate->isUnconditional())
9708       continue;
9709 
9710     if (ProveViaCond(LoopEntryPredicate->getCondition(),
9711                      LoopEntryPredicate->getSuccessor(0) != Pair.second))
9712       return true;
9713   }
9714 
9715   // Check conditions due to any @llvm.assume intrinsics.
9716   for (auto &AssumeVH : AC.assumptions()) {
9717     if (!AssumeVH)
9718       continue;
9719     auto *CI = cast<CallInst>(AssumeVH);
9720     if (!DT.dominates(CI, L->getHeader()))
9721       continue;
9722 
9723     if (ProveViaCond(CI->getArgOperand(0), false))
9724       return true;
9725   }
9726 
9727   return false;
9728 }
9729 
9730 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
9731                                     const SCEV *LHS, const SCEV *RHS,
9732                                     Value *FoundCondValue,
9733                                     bool Inverse) {
9734   if (!PendingLoopPredicates.insert(FoundCondValue).second)
9735     return false;
9736 
9737   auto ClearOnExit =
9738       make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
9739 
9740   // Recursively handle And and Or conditions.
9741   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
9742     if (BO->getOpcode() == Instruction::And) {
9743       if (!Inverse)
9744         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
9745                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
9746     } else if (BO->getOpcode() == Instruction::Or) {
9747       if (Inverse)
9748         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
9749                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
9750     }
9751   }
9752 
9753   ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
9754   if (!ICI) return false;
9755 
9756   // Now that we found a conditional branch that dominates the loop or controls
9757   // the loop latch. Check to see if it is the comparison we are looking for.
9758   ICmpInst::Predicate FoundPred;
9759   if (Inverse)
9760     FoundPred = ICI->getInversePredicate();
9761   else
9762     FoundPred = ICI->getPredicate();
9763 
9764   const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
9765   const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
9766 
9767   return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS);
9768 }
9769 
9770 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
9771                                     const SCEV *RHS,
9772                                     ICmpInst::Predicate FoundPred,
9773                                     const SCEV *FoundLHS,
9774                                     const SCEV *FoundRHS) {
9775   // Balance the types.
9776   if (getTypeSizeInBits(LHS->getType()) <
9777       getTypeSizeInBits(FoundLHS->getType())) {
9778     if (CmpInst::isSigned(Pred)) {
9779       LHS = getSignExtendExpr(LHS, FoundLHS->getType());
9780       RHS = getSignExtendExpr(RHS, FoundLHS->getType());
9781     } else {
9782       LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
9783       RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
9784     }
9785   } else if (getTypeSizeInBits(LHS->getType()) >
9786       getTypeSizeInBits(FoundLHS->getType())) {
9787     if (CmpInst::isSigned(FoundPred)) {
9788       FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
9789       FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
9790     } else {
9791       FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
9792       FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
9793     }
9794   }
9795 
9796   // Canonicalize the query to match the way instcombine will have
9797   // canonicalized the comparison.
9798   if (SimplifyICmpOperands(Pred, LHS, RHS))
9799     if (LHS == RHS)
9800       return CmpInst::isTrueWhenEqual(Pred);
9801   if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
9802     if (FoundLHS == FoundRHS)
9803       return CmpInst::isFalseWhenEqual(FoundPred);
9804 
9805   // Check to see if we can make the LHS or RHS match.
9806   if (LHS == FoundRHS || RHS == FoundLHS) {
9807     if (isa<SCEVConstant>(RHS)) {
9808       std::swap(FoundLHS, FoundRHS);
9809       FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
9810     } else {
9811       std::swap(LHS, RHS);
9812       Pred = ICmpInst::getSwappedPredicate(Pred);
9813     }
9814   }
9815 
9816   // Check whether the found predicate is the same as the desired predicate.
9817   if (FoundPred == Pred)
9818     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
9819 
9820   // Check whether swapping the found predicate makes it the same as the
9821   // desired predicate.
9822   if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
9823     if (isa<SCEVConstant>(RHS))
9824       return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
9825     else
9826       return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
9827                                    RHS, LHS, FoundLHS, FoundRHS);
9828   }
9829 
9830   // Unsigned comparison is the same as signed comparison when both the operands
9831   // are non-negative.
9832   if (CmpInst::isUnsigned(FoundPred) &&
9833       CmpInst::getSignedPredicate(FoundPred) == Pred &&
9834       isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS))
9835     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
9836 
9837   // Check if we can make progress by sharpening ranges.
9838   if (FoundPred == ICmpInst::ICMP_NE &&
9839       (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
9840 
9841     const SCEVConstant *C = nullptr;
9842     const SCEV *V = nullptr;
9843 
9844     if (isa<SCEVConstant>(FoundLHS)) {
9845       C = cast<SCEVConstant>(FoundLHS);
9846       V = FoundRHS;
9847     } else {
9848       C = cast<SCEVConstant>(FoundRHS);
9849       V = FoundLHS;
9850     }
9851 
9852     // The guarding predicate tells us that C != V. If the known range
9853     // of V is [C, t), we can sharpen the range to [C + 1, t).  The
9854     // range we consider has to correspond to same signedness as the
9855     // predicate we're interested in folding.
9856 
9857     APInt Min = ICmpInst::isSigned(Pred) ?
9858         getSignedRangeMin(V) : getUnsignedRangeMin(V);
9859 
9860     if (Min == C->getAPInt()) {
9861       // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
9862       // This is true even if (Min + 1) wraps around -- in case of
9863       // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
9864 
9865       APInt SharperMin = Min + 1;
9866 
9867       switch (Pred) {
9868         case ICmpInst::ICMP_SGE:
9869         case ICmpInst::ICMP_UGE:
9870           // We know V `Pred` SharperMin.  If this implies LHS `Pred`
9871           // RHS, we're done.
9872           if (isImpliedCondOperands(Pred, LHS, RHS, V,
9873                                     getConstant(SharperMin)))
9874             return true;
9875           LLVM_FALLTHROUGH;
9876 
9877         case ICmpInst::ICMP_SGT:
9878         case ICmpInst::ICMP_UGT:
9879           // We know from the range information that (V `Pred` Min ||
9880           // V == Min).  We know from the guarding condition that !(V
9881           // == Min).  This gives us
9882           //
9883           //       V `Pred` Min || V == Min && !(V == Min)
9884           //   =>  V `Pred` Min
9885           //
9886           // If V `Pred` Min implies LHS `Pred` RHS, we're done.
9887 
9888           if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min)))
9889             return true;
9890           LLVM_FALLTHROUGH;
9891 
9892         default:
9893           // No change
9894           break;
9895       }
9896     }
9897   }
9898 
9899   // Check whether the actual condition is beyond sufficient.
9900   if (FoundPred == ICmpInst::ICMP_EQ)
9901     if (ICmpInst::isTrueWhenEqual(Pred))
9902       if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
9903         return true;
9904   if (Pred == ICmpInst::ICMP_NE)
9905     if (!ICmpInst::isTrueWhenEqual(FoundPred))
9906       if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
9907         return true;
9908 
9909   // Otherwise assume the worst.
9910   return false;
9911 }
9912 
9913 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
9914                                      const SCEV *&L, const SCEV *&R,
9915                                      SCEV::NoWrapFlags &Flags) {
9916   const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
9917   if (!AE || AE->getNumOperands() != 2)
9918     return false;
9919 
9920   L = AE->getOperand(0);
9921   R = AE->getOperand(1);
9922   Flags = AE->getNoWrapFlags();
9923   return true;
9924 }
9925 
9926 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More,
9927                                                            const SCEV *Less) {
9928   // We avoid subtracting expressions here because this function is usually
9929   // fairly deep in the call stack (i.e. is called many times).
9930 
9931   // X - X = 0.
9932   if (More == Less)
9933     return APInt(getTypeSizeInBits(More->getType()), 0);
9934 
9935   if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
9936     const auto *LAR = cast<SCEVAddRecExpr>(Less);
9937     const auto *MAR = cast<SCEVAddRecExpr>(More);
9938 
9939     if (LAR->getLoop() != MAR->getLoop())
9940       return None;
9941 
9942     // We look at affine expressions only; not for correctness but to keep
9943     // getStepRecurrence cheap.
9944     if (!LAR->isAffine() || !MAR->isAffine())
9945       return None;
9946 
9947     if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
9948       return None;
9949 
9950     Less = LAR->getStart();
9951     More = MAR->getStart();
9952 
9953     // fall through
9954   }
9955 
9956   if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
9957     const auto &M = cast<SCEVConstant>(More)->getAPInt();
9958     const auto &L = cast<SCEVConstant>(Less)->getAPInt();
9959     return M - L;
9960   }
9961 
9962   SCEV::NoWrapFlags Flags;
9963   const SCEV *LLess = nullptr, *RLess = nullptr;
9964   const SCEV *LMore = nullptr, *RMore = nullptr;
9965   const SCEVConstant *C1 = nullptr, *C2 = nullptr;
9966   // Compare (X + C1) vs X.
9967   if (splitBinaryAdd(Less, LLess, RLess, Flags))
9968     if ((C1 = dyn_cast<SCEVConstant>(LLess)))
9969       if (RLess == More)
9970         return -(C1->getAPInt());
9971 
9972   // Compare X vs (X + C2).
9973   if (splitBinaryAdd(More, LMore, RMore, Flags))
9974     if ((C2 = dyn_cast<SCEVConstant>(LMore)))
9975       if (RMore == Less)
9976         return C2->getAPInt();
9977 
9978   // Compare (X + C1) vs (X + C2).
9979   if (C1 && C2 && RLess == RMore)
9980     return C2->getAPInt() - C1->getAPInt();
9981 
9982   return None;
9983 }
9984 
9985 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
9986     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
9987     const SCEV *FoundLHS, const SCEV *FoundRHS) {
9988   if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
9989     return false;
9990 
9991   const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
9992   if (!AddRecLHS)
9993     return false;
9994 
9995   const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
9996   if (!AddRecFoundLHS)
9997     return false;
9998 
9999   // We'd like to let SCEV reason about control dependencies, so we constrain
10000   // both the inequalities to be about add recurrences on the same loop.  This
10001   // way we can use isLoopEntryGuardedByCond later.
10002 
10003   const Loop *L = AddRecFoundLHS->getLoop();
10004   if (L != AddRecLHS->getLoop())
10005     return false;
10006 
10007   //  FoundLHS u< FoundRHS u< -C =>  (FoundLHS + C) u< (FoundRHS + C) ... (1)
10008   //
10009   //  FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
10010   //                                                                  ... (2)
10011   //
10012   // Informal proof for (2), assuming (1) [*]:
10013   //
10014   // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
10015   //
10016   // Then
10017   //
10018   //       FoundLHS s< FoundRHS s< INT_MIN - C
10019   // <=>  (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C   [ using (3) ]
10020   // <=>  (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
10021   // <=>  (FoundLHS + INT_MIN + C + INT_MIN) s<
10022   //                        (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
10023   // <=>  FoundLHS + C s< FoundRHS + C
10024   //
10025   // [*]: (1) can be proved by ruling out overflow.
10026   //
10027   // [**]: This can be proved by analyzing all the four possibilities:
10028   //    (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
10029   //    (A s>= 0, B s>= 0).
10030   //
10031   // Note:
10032   // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
10033   // will not sign underflow.  For instance, say FoundLHS = (i8 -128), FoundRHS
10034   // = (i8 -127) and C = (i8 -100).  Then INT_MIN - C = (i8 -28), and FoundRHS
10035   // s< (INT_MIN - C).  Lack of sign overflow / underflow in "FoundRHS + C" is
10036   // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
10037   // C)".
10038 
10039   Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
10040   Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
10041   if (!LDiff || !RDiff || *LDiff != *RDiff)
10042     return false;
10043 
10044   if (LDiff->isMinValue())
10045     return true;
10046 
10047   APInt FoundRHSLimit;
10048 
10049   if (Pred == CmpInst::ICMP_ULT) {
10050     FoundRHSLimit = -(*RDiff);
10051   } else {
10052     assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
10053     FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
10054   }
10055 
10056   // Try to prove (1) or (2), as needed.
10057   return isAvailableAtLoopEntry(FoundRHS, L) &&
10058          isLoopEntryGuardedByCond(L, Pred, FoundRHS,
10059                                   getConstant(FoundRHSLimit));
10060 }
10061 
10062 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred,
10063                                         const SCEV *LHS, const SCEV *RHS,
10064                                         const SCEV *FoundLHS,
10065                                         const SCEV *FoundRHS, unsigned Depth) {
10066   const PHINode *LPhi = nullptr, *RPhi = nullptr;
10067 
10068   auto ClearOnExit = make_scope_exit([&]() {
10069     if (LPhi) {
10070       bool Erased = PendingMerges.erase(LPhi);
10071       assert(Erased && "Failed to erase LPhi!");
10072       (void)Erased;
10073     }
10074     if (RPhi) {
10075       bool Erased = PendingMerges.erase(RPhi);
10076       assert(Erased && "Failed to erase RPhi!");
10077       (void)Erased;
10078     }
10079   });
10080 
10081   // Find respective Phis and check that they are not being pending.
10082   if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS))
10083     if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) {
10084       if (!PendingMerges.insert(Phi).second)
10085         return false;
10086       LPhi = Phi;
10087     }
10088   if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS))
10089     if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) {
10090       // If we detect a loop of Phi nodes being processed by this method, for
10091       // example:
10092       //
10093       //   %a = phi i32 [ %some1, %preheader ], [ %b, %latch ]
10094       //   %b = phi i32 [ %some2, %preheader ], [ %a, %latch ]
10095       //
10096       // we don't want to deal with a case that complex, so return conservative
10097       // answer false.
10098       if (!PendingMerges.insert(Phi).second)
10099         return false;
10100       RPhi = Phi;
10101     }
10102 
10103   // If none of LHS, RHS is a Phi, nothing to do here.
10104   if (!LPhi && !RPhi)
10105     return false;
10106 
10107   // If there is a SCEVUnknown Phi we are interested in, make it left.
10108   if (!LPhi) {
10109     std::swap(LHS, RHS);
10110     std::swap(FoundLHS, FoundRHS);
10111     std::swap(LPhi, RPhi);
10112     Pred = ICmpInst::getSwappedPredicate(Pred);
10113   }
10114 
10115   assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!");
10116   const BasicBlock *LBB = LPhi->getParent();
10117   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
10118 
10119   auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) {
10120     return isKnownViaNonRecursiveReasoning(Pred, S1, S2) ||
10121            isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) ||
10122            isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth);
10123   };
10124 
10125   if (RPhi && RPhi->getParent() == LBB) {
10126     // Case one: RHS is also a SCEVUnknown Phi from the same basic block.
10127     // If we compare two Phis from the same block, and for each entry block
10128     // the predicate is true for incoming values from this block, then the
10129     // predicate is also true for the Phis.
10130     for (const BasicBlock *IncBB : predecessors(LBB)) {
10131       const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
10132       const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB));
10133       if (!ProvedEasily(L, R))
10134         return false;
10135     }
10136   } else if (RAR && RAR->getLoop()->getHeader() == LBB) {
10137     // Case two: RHS is also a Phi from the same basic block, and it is an
10138     // AddRec. It means that there is a loop which has both AddRec and Unknown
10139     // PHIs, for it we can compare incoming values of AddRec from above the loop
10140     // and latch with their respective incoming values of LPhi.
10141     // TODO: Generalize to handle loops with many inputs in a header.
10142     if (LPhi->getNumIncomingValues() != 2) return false;
10143 
10144     auto *RLoop = RAR->getLoop();
10145     auto *Predecessor = RLoop->getLoopPredecessor();
10146     assert(Predecessor && "Loop with AddRec with no predecessor?");
10147     const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor));
10148     if (!ProvedEasily(L1, RAR->getStart()))
10149       return false;
10150     auto *Latch = RLoop->getLoopLatch();
10151     assert(Latch && "Loop with AddRec with no latch?");
10152     const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch));
10153     if (!ProvedEasily(L2, RAR->getPostIncExpr(*this)))
10154       return false;
10155   } else {
10156     // In all other cases go over inputs of LHS and compare each of them to RHS,
10157     // the predicate is true for (LHS, RHS) if it is true for all such pairs.
10158     // At this point RHS is either a non-Phi, or it is a Phi from some block
10159     // different from LBB.
10160     for (const BasicBlock *IncBB : predecessors(LBB)) {
10161       // Check that RHS is available in this block.
10162       if (!dominates(RHS, IncBB))
10163         return false;
10164       const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
10165       if (!ProvedEasily(L, RHS))
10166         return false;
10167     }
10168   }
10169   return true;
10170 }
10171 
10172 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
10173                                             const SCEV *LHS, const SCEV *RHS,
10174                                             const SCEV *FoundLHS,
10175                                             const SCEV *FoundRHS) {
10176   if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
10177     return true;
10178 
10179   if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
10180     return true;
10181 
10182   return isImpliedCondOperandsHelper(Pred, LHS, RHS,
10183                                      FoundLHS, FoundRHS) ||
10184          // ~x < ~y --> x > y
10185          isImpliedCondOperandsHelper(Pred, LHS, RHS,
10186                                      getNotSCEV(FoundRHS),
10187                                      getNotSCEV(FoundLHS));
10188 }
10189 
10190 /// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values?
10191 template <typename MinMaxExprType>
10192 static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr,
10193                                  const SCEV *Candidate) {
10194   const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr);
10195   if (!MinMaxExpr)
10196     return false;
10197 
10198   return find(MinMaxExpr->operands(), Candidate) != MinMaxExpr->op_end();
10199 }
10200 
10201 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
10202                                            ICmpInst::Predicate Pred,
10203                                            const SCEV *LHS, const SCEV *RHS) {
10204   // If both sides are affine addrecs for the same loop, with equal
10205   // steps, and we know the recurrences don't wrap, then we only
10206   // need to check the predicate on the starting values.
10207 
10208   if (!ICmpInst::isRelational(Pred))
10209     return false;
10210 
10211   const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
10212   if (!LAR)
10213     return false;
10214   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
10215   if (!RAR)
10216     return false;
10217   if (LAR->getLoop() != RAR->getLoop())
10218     return false;
10219   if (!LAR->isAffine() || !RAR->isAffine())
10220     return false;
10221 
10222   if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
10223     return false;
10224 
10225   SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
10226                          SCEV::FlagNSW : SCEV::FlagNUW;
10227   if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
10228     return false;
10229 
10230   return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
10231 }
10232 
10233 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
10234 /// expression?
10235 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
10236                                         ICmpInst::Predicate Pred,
10237                                         const SCEV *LHS, const SCEV *RHS) {
10238   switch (Pred) {
10239   default:
10240     return false;
10241 
10242   case ICmpInst::ICMP_SGE:
10243     std::swap(LHS, RHS);
10244     LLVM_FALLTHROUGH;
10245   case ICmpInst::ICMP_SLE:
10246     return
10247         // min(A, ...) <= A
10248         IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) ||
10249         // A <= max(A, ...)
10250         IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
10251 
10252   case ICmpInst::ICMP_UGE:
10253     std::swap(LHS, RHS);
10254     LLVM_FALLTHROUGH;
10255   case ICmpInst::ICMP_ULE:
10256     return
10257         // min(A, ...) <= A
10258         IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) ||
10259         // A <= max(A, ...)
10260         IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
10261   }
10262 
10263   llvm_unreachable("covered switch fell through?!");
10264 }
10265 
10266 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred,
10267                                              const SCEV *LHS, const SCEV *RHS,
10268                                              const SCEV *FoundLHS,
10269                                              const SCEV *FoundRHS,
10270                                              unsigned Depth) {
10271   assert(getTypeSizeInBits(LHS->getType()) ==
10272              getTypeSizeInBits(RHS->getType()) &&
10273          "LHS and RHS have different sizes?");
10274   assert(getTypeSizeInBits(FoundLHS->getType()) ==
10275              getTypeSizeInBits(FoundRHS->getType()) &&
10276          "FoundLHS and FoundRHS have different sizes?");
10277   // We want to avoid hurting the compile time with analysis of too big trees.
10278   if (Depth > MaxSCEVOperationsImplicationDepth)
10279     return false;
10280   // We only want to work with ICMP_SGT comparison so far.
10281   // TODO: Extend to ICMP_UGT?
10282   if (Pred == ICmpInst::ICMP_SLT) {
10283     Pred = ICmpInst::ICMP_SGT;
10284     std::swap(LHS, RHS);
10285     std::swap(FoundLHS, FoundRHS);
10286   }
10287   if (Pred != ICmpInst::ICMP_SGT)
10288     return false;
10289 
10290   auto GetOpFromSExt = [&](const SCEV *S) {
10291     if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
10292       return Ext->getOperand();
10293     // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
10294     // the constant in some cases.
10295     return S;
10296   };
10297 
10298   // Acquire values from extensions.
10299   auto *OrigLHS = LHS;
10300   auto *OrigFoundLHS = FoundLHS;
10301   LHS = GetOpFromSExt(LHS);
10302   FoundLHS = GetOpFromSExt(FoundLHS);
10303 
10304   // Is the SGT predicate can be proved trivially or using the found context.
10305   auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
10306     return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
10307            isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
10308                                   FoundRHS, Depth + 1);
10309   };
10310 
10311   if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
10312     // We want to avoid creation of any new non-constant SCEV. Since we are
10313     // going to compare the operands to RHS, we should be certain that we don't
10314     // need any size extensions for this. So let's decline all cases when the
10315     // sizes of types of LHS and RHS do not match.
10316     // TODO: Maybe try to get RHS from sext to catch more cases?
10317     if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType()))
10318       return false;
10319 
10320     // Should not overflow.
10321     if (!LHSAddExpr->hasNoSignedWrap())
10322       return false;
10323 
10324     auto *LL = LHSAddExpr->getOperand(0);
10325     auto *LR = LHSAddExpr->getOperand(1);
10326     auto *MinusOne = getNegativeSCEV(getOne(RHS->getType()));
10327 
10328     // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
10329     auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
10330       return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
10331     };
10332     // Try to prove the following rule:
10333     // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
10334     // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
10335     if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
10336       return true;
10337   } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
10338     Value *LL, *LR;
10339     // FIXME: Once we have SDiv implemented, we can get rid of this matching.
10340 
10341     using namespace llvm::PatternMatch;
10342 
10343     if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
10344       // Rules for division.
10345       // We are going to perform some comparisons with Denominator and its
10346       // derivative expressions. In general case, creating a SCEV for it may
10347       // lead to a complex analysis of the entire graph, and in particular it
10348       // can request trip count recalculation for the same loop. This would
10349       // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
10350       // this, we only want to create SCEVs that are constants in this section.
10351       // So we bail if Denominator is not a constant.
10352       if (!isa<ConstantInt>(LR))
10353         return false;
10354 
10355       auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
10356 
10357       // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
10358       // then a SCEV for the numerator already exists and matches with FoundLHS.
10359       auto *Numerator = getExistingSCEV(LL);
10360       if (!Numerator || Numerator->getType() != FoundLHS->getType())
10361         return false;
10362 
10363       // Make sure that the numerator matches with FoundLHS and the denominator
10364       // is positive.
10365       if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
10366         return false;
10367 
10368       auto *DTy = Denominator->getType();
10369       auto *FRHSTy = FoundRHS->getType();
10370       if (DTy->isPointerTy() != FRHSTy->isPointerTy())
10371         // One of types is a pointer and another one is not. We cannot extend
10372         // them properly to a wider type, so let us just reject this case.
10373         // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
10374         // to avoid this check.
10375         return false;
10376 
10377       // Given that:
10378       // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
10379       auto *WTy = getWiderType(DTy, FRHSTy);
10380       auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
10381       auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
10382 
10383       // Try to prove the following rule:
10384       // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
10385       // For example, given that FoundLHS > 2. It means that FoundLHS is at
10386       // least 3. If we divide it by Denominator < 4, we will have at least 1.
10387       auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
10388       if (isKnownNonPositive(RHS) &&
10389           IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
10390         return true;
10391 
10392       // Try to prove the following rule:
10393       // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
10394       // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
10395       // If we divide it by Denominator > 2, then:
10396       // 1. If FoundLHS is negative, then the result is 0.
10397       // 2. If FoundLHS is non-negative, then the result is non-negative.
10398       // Anyways, the result is non-negative.
10399       auto *MinusOne = getNegativeSCEV(getOne(WTy));
10400       auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
10401       if (isKnownNegative(RHS) &&
10402           IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
10403         return true;
10404     }
10405   }
10406 
10407   // If our expression contained SCEVUnknown Phis, and we split it down and now
10408   // need to prove something for them, try to prove the predicate for every
10409   // possible incoming values of those Phis.
10410   if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1))
10411     return true;
10412 
10413   return false;
10414 }
10415 
10416 static bool isKnownPredicateExtendIdiom(ICmpInst::Predicate Pred,
10417                                         const SCEV *LHS, const SCEV *RHS) {
10418   // zext x u<= sext x, sext x s<= zext x
10419   switch (Pred) {
10420   case ICmpInst::ICMP_SGE:
10421     std::swap(LHS, RHS);
10422     LLVM_FALLTHROUGH;
10423   case ICmpInst::ICMP_SLE: {
10424     // If operand >=s 0 then ZExt == SExt.  If operand <s 0 then SExt <s ZExt.
10425     const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(LHS);
10426     const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(RHS);
10427     if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand())
10428       return true;
10429     break;
10430   }
10431   case ICmpInst::ICMP_UGE:
10432     std::swap(LHS, RHS);
10433     LLVM_FALLTHROUGH;
10434   case ICmpInst::ICMP_ULE: {
10435     // If operand >=s 0 then ZExt == SExt.  If operand <s 0 then ZExt <u SExt.
10436     const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS);
10437     const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(RHS);
10438     if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand())
10439       return true;
10440     break;
10441   }
10442   default:
10443     break;
10444   };
10445   return false;
10446 }
10447 
10448 bool
10449 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred,
10450                                            const SCEV *LHS, const SCEV *RHS) {
10451   return isKnownPredicateExtendIdiom(Pred, LHS, RHS) ||
10452          isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
10453          IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
10454          IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
10455          isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
10456 }
10457 
10458 bool
10459 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
10460                                              const SCEV *LHS, const SCEV *RHS,
10461                                              const SCEV *FoundLHS,
10462                                              const SCEV *FoundRHS) {
10463   switch (Pred) {
10464   default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
10465   case ICmpInst::ICMP_EQ:
10466   case ICmpInst::ICMP_NE:
10467     if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
10468       return true;
10469     break;
10470   case ICmpInst::ICMP_SLT:
10471   case ICmpInst::ICMP_SLE:
10472     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
10473         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS))
10474       return true;
10475     break;
10476   case ICmpInst::ICMP_SGT:
10477   case ICmpInst::ICMP_SGE:
10478     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
10479         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS))
10480       return true;
10481     break;
10482   case ICmpInst::ICMP_ULT:
10483   case ICmpInst::ICMP_ULE:
10484     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
10485         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS))
10486       return true;
10487     break;
10488   case ICmpInst::ICMP_UGT:
10489   case ICmpInst::ICMP_UGE:
10490     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
10491         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS))
10492       return true;
10493     break;
10494   }
10495 
10496   // Maybe it can be proved via operations?
10497   if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
10498     return true;
10499 
10500   return false;
10501 }
10502 
10503 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
10504                                                      const SCEV *LHS,
10505                                                      const SCEV *RHS,
10506                                                      const SCEV *FoundLHS,
10507                                                      const SCEV *FoundRHS) {
10508   if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
10509     // The restriction on `FoundRHS` be lifted easily -- it exists only to
10510     // reduce the compile time impact of this optimization.
10511     return false;
10512 
10513   Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
10514   if (!Addend)
10515     return false;
10516 
10517   const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
10518 
10519   // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
10520   // antecedent "`FoundLHS` `Pred` `FoundRHS`".
10521   ConstantRange FoundLHSRange =
10522       ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS);
10523 
10524   // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
10525   ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
10526 
10527   // We can also compute the range of values for `LHS` that satisfy the
10528   // consequent, "`LHS` `Pred` `RHS`":
10529   const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
10530   ConstantRange SatisfyingLHSRange =
10531       ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS);
10532 
10533   // The antecedent implies the consequent if every value of `LHS` that
10534   // satisfies the antecedent also satisfies the consequent.
10535   return SatisfyingLHSRange.contains(LHSRange);
10536 }
10537 
10538 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
10539                                          bool IsSigned, bool NoWrap) {
10540   assert(isKnownPositive(Stride) && "Positive stride expected!");
10541 
10542   if (NoWrap) return false;
10543 
10544   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
10545   const SCEV *One = getOne(Stride->getType());
10546 
10547   if (IsSigned) {
10548     APInt MaxRHS = getSignedRangeMax(RHS);
10549     APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
10550     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
10551 
10552     // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
10553     return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS);
10554   }
10555 
10556   APInt MaxRHS = getUnsignedRangeMax(RHS);
10557   APInt MaxValue = APInt::getMaxValue(BitWidth);
10558   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
10559 
10560   // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
10561   return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS);
10562 }
10563 
10564 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
10565                                          bool IsSigned, bool NoWrap) {
10566   if (NoWrap) return false;
10567 
10568   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
10569   const SCEV *One = getOne(Stride->getType());
10570 
10571   if (IsSigned) {
10572     APInt MinRHS = getSignedRangeMin(RHS);
10573     APInt MinValue = APInt::getSignedMinValue(BitWidth);
10574     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
10575 
10576     // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
10577     return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS);
10578   }
10579 
10580   APInt MinRHS = getUnsignedRangeMin(RHS);
10581   APInt MinValue = APInt::getMinValue(BitWidth);
10582   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
10583 
10584   // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
10585   return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS);
10586 }
10587 
10588 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step,
10589                                             bool Equality) {
10590   const SCEV *One = getOne(Step->getType());
10591   Delta = Equality ? getAddExpr(Delta, Step)
10592                    : getAddExpr(Delta, getMinusSCEV(Step, One));
10593   return getUDivExpr(Delta, Step);
10594 }
10595 
10596 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start,
10597                                                     const SCEV *Stride,
10598                                                     const SCEV *End,
10599                                                     unsigned BitWidth,
10600                                                     bool IsSigned) {
10601 
10602   assert(!isKnownNonPositive(Stride) &&
10603          "Stride is expected strictly positive!");
10604   // Calculate the maximum backedge count based on the range of values
10605   // permitted by Start, End, and Stride.
10606   const SCEV *MaxBECount;
10607   APInt MinStart =
10608       IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start);
10609 
10610   APInt StrideForMaxBECount =
10611       IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride);
10612 
10613   // We already know that the stride is positive, so we paper over conservatism
10614   // in our range computation by forcing StrideForMaxBECount to be at least one.
10615   // In theory this is unnecessary, but we expect MaxBECount to be a
10616   // SCEVConstant, and (udiv <constant> 0) is not constant folded by SCEV (there
10617   // is nothing to constant fold it to).
10618   APInt One(BitWidth, 1, IsSigned);
10619   StrideForMaxBECount = APIntOps::smax(One, StrideForMaxBECount);
10620 
10621   APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth)
10622                             : APInt::getMaxValue(BitWidth);
10623   APInt Limit = MaxValue - (StrideForMaxBECount - 1);
10624 
10625   // Although End can be a MAX expression we estimate MaxEnd considering only
10626   // the case End = RHS of the loop termination condition. This is safe because
10627   // in the other case (End - Start) is zero, leading to a zero maximum backedge
10628   // taken count.
10629   APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit)
10630                           : APIntOps::umin(getUnsignedRangeMax(End), Limit);
10631 
10632   MaxBECount = computeBECount(getConstant(MaxEnd - MinStart) /* Delta */,
10633                               getConstant(StrideForMaxBECount) /* Step */,
10634                               false /* Equality */);
10635 
10636   return MaxBECount;
10637 }
10638 
10639 ScalarEvolution::ExitLimit
10640 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
10641                                   const Loop *L, bool IsSigned,
10642                                   bool ControlsExit, bool AllowPredicates) {
10643   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
10644 
10645   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
10646   bool PredicatedIV = false;
10647 
10648   if (!IV && AllowPredicates) {
10649     // Try to make this an AddRec using runtime tests, in the first X
10650     // iterations of this loop, where X is the SCEV expression found by the
10651     // algorithm below.
10652     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
10653     PredicatedIV = true;
10654   }
10655 
10656   // Avoid weird loops
10657   if (!IV || IV->getLoop() != L || !IV->isAffine())
10658     return getCouldNotCompute();
10659 
10660   bool NoWrap = ControlsExit &&
10661                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
10662 
10663   const SCEV *Stride = IV->getStepRecurrence(*this);
10664 
10665   bool PositiveStride = isKnownPositive(Stride);
10666 
10667   // Avoid negative or zero stride values.
10668   if (!PositiveStride) {
10669     // We can compute the correct backedge taken count for loops with unknown
10670     // strides if we can prove that the loop is not an infinite loop with side
10671     // effects. Here's the loop structure we are trying to handle -
10672     //
10673     // i = start
10674     // do {
10675     //   A[i] = i;
10676     //   i += s;
10677     // } while (i < end);
10678     //
10679     // The backedge taken count for such loops is evaluated as -
10680     // (max(end, start + stride) - start - 1) /u stride
10681     //
10682     // The additional preconditions that we need to check to prove correctness
10683     // of the above formula is as follows -
10684     //
10685     // a) IV is either nuw or nsw depending upon signedness (indicated by the
10686     //    NoWrap flag).
10687     // b) loop is single exit with no side effects.
10688     //
10689     //
10690     // Precondition a) implies that if the stride is negative, this is a single
10691     // trip loop. The backedge taken count formula reduces to zero in this case.
10692     //
10693     // Precondition b) implies that the unknown stride cannot be zero otherwise
10694     // we have UB.
10695     //
10696     // The positive stride case is the same as isKnownPositive(Stride) returning
10697     // true (original behavior of the function).
10698     //
10699     // We want to make sure that the stride is truly unknown as there are edge
10700     // cases where ScalarEvolution propagates no wrap flags to the
10701     // post-increment/decrement IV even though the increment/decrement operation
10702     // itself is wrapping. The computed backedge taken count may be wrong in
10703     // such cases. This is prevented by checking that the stride is not known to
10704     // be either positive or non-positive. For example, no wrap flags are
10705     // propagated to the post-increment IV of this loop with a trip count of 2 -
10706     //
10707     // unsigned char i;
10708     // for(i=127; i<128; i+=129)
10709     //   A[i] = i;
10710     //
10711     if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) ||
10712         !loopHasNoSideEffects(L))
10713       return getCouldNotCompute();
10714   } else if (!Stride->isOne() &&
10715              doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap))
10716     // Avoid proven overflow cases: this will ensure that the backedge taken
10717     // count will not generate any unsigned overflow. Relaxed no-overflow
10718     // conditions exploit NoWrapFlags, allowing to optimize in presence of
10719     // undefined behaviors like the case of C language.
10720     return getCouldNotCompute();
10721 
10722   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT
10723                                       : ICmpInst::ICMP_ULT;
10724   const SCEV *Start = IV->getStart();
10725   const SCEV *End = RHS;
10726   // When the RHS is not invariant, we do not know the end bound of the loop and
10727   // cannot calculate the ExactBECount needed by ExitLimit. However, we can
10728   // calculate the MaxBECount, given the start, stride and max value for the end
10729   // bound of the loop (RHS), and the fact that IV does not overflow (which is
10730   // checked above).
10731   if (!isLoopInvariant(RHS, L)) {
10732     const SCEV *MaxBECount = computeMaxBECountForLT(
10733         Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
10734     return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount,
10735                      false /*MaxOrZero*/, Predicates);
10736   }
10737   // If the backedge is taken at least once, then it will be taken
10738   // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start
10739   // is the LHS value of the less-than comparison the first time it is evaluated
10740   // and End is the RHS.
10741   const SCEV *BECountIfBackedgeTaken =
10742     computeBECount(getMinusSCEV(End, Start), Stride, false);
10743   // If the loop entry is guarded by the result of the backedge test of the
10744   // first loop iteration, then we know the backedge will be taken at least
10745   // once and so the backedge taken count is as above. If not then we use the
10746   // expression (max(End,Start)-Start)/Stride to describe the backedge count,
10747   // as if the backedge is taken at least once max(End,Start) is End and so the
10748   // result is as above, and if not max(End,Start) is Start so we get a backedge
10749   // count of zero.
10750   const SCEV *BECount;
10751   if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS))
10752     BECount = BECountIfBackedgeTaken;
10753   else {
10754     End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
10755     BECount = computeBECount(getMinusSCEV(End, Start), Stride, false);
10756   }
10757 
10758   const SCEV *MaxBECount;
10759   bool MaxOrZero = false;
10760   if (isa<SCEVConstant>(BECount))
10761     MaxBECount = BECount;
10762   else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) {
10763     // If we know exactly how many times the backedge will be taken if it's
10764     // taken at least once, then the backedge count will either be that or
10765     // zero.
10766     MaxBECount = BECountIfBackedgeTaken;
10767     MaxOrZero = true;
10768   } else {
10769     MaxBECount = computeMaxBECountForLT(
10770         Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
10771   }
10772 
10773   if (isa<SCEVCouldNotCompute>(MaxBECount) &&
10774       !isa<SCEVCouldNotCompute>(BECount))
10775     MaxBECount = getConstant(getUnsignedRangeMax(BECount));
10776 
10777   return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates);
10778 }
10779 
10780 ScalarEvolution::ExitLimit
10781 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
10782                                      const Loop *L, bool IsSigned,
10783                                      bool ControlsExit, bool AllowPredicates) {
10784   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
10785   // We handle only IV > Invariant
10786   if (!isLoopInvariant(RHS, L))
10787     return getCouldNotCompute();
10788 
10789   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
10790   if (!IV && AllowPredicates)
10791     // Try to make this an AddRec using runtime tests, in the first X
10792     // iterations of this loop, where X is the SCEV expression found by the
10793     // algorithm below.
10794     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
10795 
10796   // Avoid weird loops
10797   if (!IV || IV->getLoop() != L || !IV->isAffine())
10798     return getCouldNotCompute();
10799 
10800   bool NoWrap = ControlsExit &&
10801                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
10802 
10803   const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
10804 
10805   // Avoid negative or zero stride values
10806   if (!isKnownPositive(Stride))
10807     return getCouldNotCompute();
10808 
10809   // Avoid proven overflow cases: this will ensure that the backedge taken count
10810   // will not generate any unsigned overflow. Relaxed no-overflow conditions
10811   // exploit NoWrapFlags, allowing to optimize in presence of undefined
10812   // behaviors like the case of C language.
10813   if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap))
10814     return getCouldNotCompute();
10815 
10816   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT
10817                                       : ICmpInst::ICMP_UGT;
10818 
10819   const SCEV *Start = IV->getStart();
10820   const SCEV *End = RHS;
10821   if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS))
10822     End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
10823 
10824   const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false);
10825 
10826   APInt MaxStart = IsSigned ? getSignedRangeMax(Start)
10827                             : getUnsignedRangeMax(Start);
10828 
10829   APInt MinStride = IsSigned ? getSignedRangeMin(Stride)
10830                              : getUnsignedRangeMin(Stride);
10831 
10832   unsigned BitWidth = getTypeSizeInBits(LHS->getType());
10833   APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
10834                          : APInt::getMinValue(BitWidth) + (MinStride - 1);
10835 
10836   // Although End can be a MIN expression we estimate MinEnd considering only
10837   // the case End = RHS. This is safe because in the other case (Start - End)
10838   // is zero, leading to a zero maximum backedge taken count.
10839   APInt MinEnd =
10840     IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit)
10841              : APIntOps::umax(getUnsignedRangeMin(RHS), Limit);
10842 
10843   const SCEV *MaxBECount = isa<SCEVConstant>(BECount)
10844                                ? BECount
10845                                : computeBECount(getConstant(MaxStart - MinEnd),
10846                                                 getConstant(MinStride), false);
10847 
10848   if (isa<SCEVCouldNotCompute>(MaxBECount))
10849     MaxBECount = BECount;
10850 
10851   return ExitLimit(BECount, MaxBECount, false, Predicates);
10852 }
10853 
10854 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range,
10855                                                     ScalarEvolution &SE) const {
10856   if (Range.isFullSet())  // Infinite loop.
10857     return SE.getCouldNotCompute();
10858 
10859   // If the start is a non-zero constant, shift the range to simplify things.
10860   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
10861     if (!SC->getValue()->isZero()) {
10862       SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
10863       Operands[0] = SE.getZero(SC->getType());
10864       const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
10865                                              getNoWrapFlags(FlagNW));
10866       if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
10867         return ShiftedAddRec->getNumIterationsInRange(
10868             Range.subtract(SC->getAPInt()), SE);
10869       // This is strange and shouldn't happen.
10870       return SE.getCouldNotCompute();
10871     }
10872 
10873   // The only time we can solve this is when we have all constant indices.
10874   // Otherwise, we cannot determine the overflow conditions.
10875   if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
10876     return SE.getCouldNotCompute();
10877 
10878   // Okay at this point we know that all elements of the chrec are constants and
10879   // that the start element is zero.
10880 
10881   // First check to see if the range contains zero.  If not, the first
10882   // iteration exits.
10883   unsigned BitWidth = SE.getTypeSizeInBits(getType());
10884   if (!Range.contains(APInt(BitWidth, 0)))
10885     return SE.getZero(getType());
10886 
10887   if (isAffine()) {
10888     // If this is an affine expression then we have this situation:
10889     //   Solve {0,+,A} in Range  ===  Ax in Range
10890 
10891     // We know that zero is in the range.  If A is positive then we know that
10892     // the upper value of the range must be the first possible exit value.
10893     // If A is negative then the lower of the range is the last possible loop
10894     // value.  Also note that we already checked for a full range.
10895     APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
10896     APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower();
10897 
10898     // The exit value should be (End+A)/A.
10899     APInt ExitVal = (End + A).udiv(A);
10900     ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
10901 
10902     // Evaluate at the exit value.  If we really did fall out of the valid
10903     // range, then we computed our trip count, otherwise wrap around or other
10904     // things must have happened.
10905     ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
10906     if (Range.contains(Val->getValue()))
10907       return SE.getCouldNotCompute();  // Something strange happened
10908 
10909     // Ensure that the previous value is in the range.  This is a sanity check.
10910     assert(Range.contains(
10911            EvaluateConstantChrecAtConstant(this,
10912            ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&
10913            "Linear scev computation is off in a bad way!");
10914     return SE.getConstant(ExitValue);
10915   }
10916 
10917   if (isQuadratic()) {
10918     if (auto S = SolveQuadraticAddRecRange(this, Range, SE))
10919       return SE.getConstant(S.getValue());
10920   }
10921 
10922   return SE.getCouldNotCompute();
10923 }
10924 
10925 const SCEVAddRecExpr *
10926 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const {
10927   assert(getNumOperands() > 1 && "AddRec with zero step?");
10928   // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)),
10929   // but in this case we cannot guarantee that the value returned will be an
10930   // AddRec because SCEV does not have a fixed point where it stops
10931   // simplification: it is legal to return ({rec1} + {rec2}). For example, it
10932   // may happen if we reach arithmetic depth limit while simplifying. So we
10933   // construct the returned value explicitly.
10934   SmallVector<const SCEV *, 3> Ops;
10935   // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and
10936   // (this + Step) is {A+B,+,B+C,+...,+,N}.
10937   for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i)
10938     Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1)));
10939   // We know that the last operand is not a constant zero (otherwise it would
10940   // have been popped out earlier). This guarantees us that if the result has
10941   // the same last operand, then it will also not be popped out, meaning that
10942   // the returned value will be an AddRec.
10943   const SCEV *Last = getOperand(getNumOperands() - 1);
10944   assert(!Last->isZero() && "Recurrency with zero step?");
10945   Ops.push_back(Last);
10946   return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(),
10947                                                SCEV::FlagAnyWrap));
10948 }
10949 
10950 // Return true when S contains at least an undef value.
10951 static inline bool containsUndefs(const SCEV *S) {
10952   return SCEVExprContains(S, [](const SCEV *S) {
10953     if (const auto *SU = dyn_cast<SCEVUnknown>(S))
10954       return isa<UndefValue>(SU->getValue());
10955     return false;
10956   });
10957 }
10958 
10959 namespace {
10960 
10961 // Collect all steps of SCEV expressions.
10962 struct SCEVCollectStrides {
10963   ScalarEvolution &SE;
10964   SmallVectorImpl<const SCEV *> &Strides;
10965 
10966   SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S)
10967       : SE(SE), Strides(S) {}
10968 
10969   bool follow(const SCEV *S) {
10970     if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
10971       Strides.push_back(AR->getStepRecurrence(SE));
10972     return true;
10973   }
10974 
10975   bool isDone() const { return false; }
10976 };
10977 
10978 // Collect all SCEVUnknown and SCEVMulExpr expressions.
10979 struct SCEVCollectTerms {
10980   SmallVectorImpl<const SCEV *> &Terms;
10981 
10982   SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) : Terms(T) {}
10983 
10984   bool follow(const SCEV *S) {
10985     if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) ||
10986         isa<SCEVSignExtendExpr>(S)) {
10987       if (!containsUndefs(S))
10988         Terms.push_back(S);
10989 
10990       // Stop recursion: once we collected a term, do not walk its operands.
10991       return false;
10992     }
10993 
10994     // Keep looking.
10995     return true;
10996   }
10997 
10998   bool isDone() const { return false; }
10999 };
11000 
11001 // Check if a SCEV contains an AddRecExpr.
11002 struct SCEVHasAddRec {
11003   bool &ContainsAddRec;
11004 
11005   SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) {
11006     ContainsAddRec = false;
11007   }
11008 
11009   bool follow(const SCEV *S) {
11010     if (isa<SCEVAddRecExpr>(S)) {
11011       ContainsAddRec = true;
11012 
11013       // Stop recursion: once we collected a term, do not walk its operands.
11014       return false;
11015     }
11016 
11017     // Keep looking.
11018     return true;
11019   }
11020 
11021   bool isDone() const { return false; }
11022 };
11023 
11024 // Find factors that are multiplied with an expression that (possibly as a
11025 // subexpression) contains an AddRecExpr. In the expression:
11026 //
11027 //  8 * (100 +  %p * %q * (%a + {0, +, 1}_loop))
11028 //
11029 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)"
11030 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size
11031 // parameters as they form a product with an induction variable.
11032 //
11033 // This collector expects all array size parameters to be in the same MulExpr.
11034 // It might be necessary to later add support for collecting parameters that are
11035 // spread over different nested MulExpr.
11036 struct SCEVCollectAddRecMultiplies {
11037   SmallVectorImpl<const SCEV *> &Terms;
11038   ScalarEvolution &SE;
11039 
11040   SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE)
11041       : Terms(T), SE(SE) {}
11042 
11043   bool follow(const SCEV *S) {
11044     if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) {
11045       bool HasAddRec = false;
11046       SmallVector<const SCEV *, 0> Operands;
11047       for (auto Op : Mul->operands()) {
11048         const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op);
11049         if (Unknown && !isa<CallInst>(Unknown->getValue())) {
11050           Operands.push_back(Op);
11051         } else if (Unknown) {
11052           HasAddRec = true;
11053         } else {
11054           bool ContainsAddRec = false;
11055           SCEVHasAddRec ContiansAddRec(ContainsAddRec);
11056           visitAll(Op, ContiansAddRec);
11057           HasAddRec |= ContainsAddRec;
11058         }
11059       }
11060       if (Operands.size() == 0)
11061         return true;
11062 
11063       if (!HasAddRec)
11064         return false;
11065 
11066       Terms.push_back(SE.getMulExpr(Operands));
11067       // Stop recursion: once we collected a term, do not walk its operands.
11068       return false;
11069     }
11070 
11071     // Keep looking.
11072     return true;
11073   }
11074 
11075   bool isDone() const { return false; }
11076 };
11077 
11078 } // end anonymous namespace
11079 
11080 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in
11081 /// two places:
11082 ///   1) The strides of AddRec expressions.
11083 ///   2) Unknowns that are multiplied with AddRec expressions.
11084 void ScalarEvolution::collectParametricTerms(const SCEV *Expr,
11085     SmallVectorImpl<const SCEV *> &Terms) {
11086   SmallVector<const SCEV *, 4> Strides;
11087   SCEVCollectStrides StrideCollector(*this, Strides);
11088   visitAll(Expr, StrideCollector);
11089 
11090   LLVM_DEBUG({
11091     dbgs() << "Strides:\n";
11092     for (const SCEV *S : Strides)
11093       dbgs() << *S << "\n";
11094   });
11095 
11096   for (const SCEV *S : Strides) {
11097     SCEVCollectTerms TermCollector(Terms);
11098     visitAll(S, TermCollector);
11099   }
11100 
11101   LLVM_DEBUG({
11102     dbgs() << "Terms:\n";
11103     for (const SCEV *T : Terms)
11104       dbgs() << *T << "\n";
11105   });
11106 
11107   SCEVCollectAddRecMultiplies MulCollector(Terms, *this);
11108   visitAll(Expr, MulCollector);
11109 }
11110 
11111 static bool findArrayDimensionsRec(ScalarEvolution &SE,
11112                                    SmallVectorImpl<const SCEV *> &Terms,
11113                                    SmallVectorImpl<const SCEV *> &Sizes) {
11114   int Last = Terms.size() - 1;
11115   const SCEV *Step = Terms[Last];
11116 
11117   // End of recursion.
11118   if (Last == 0) {
11119     if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) {
11120       SmallVector<const SCEV *, 2> Qs;
11121       for (const SCEV *Op : M->operands())
11122         if (!isa<SCEVConstant>(Op))
11123           Qs.push_back(Op);
11124 
11125       Step = SE.getMulExpr(Qs);
11126     }
11127 
11128     Sizes.push_back(Step);
11129     return true;
11130   }
11131 
11132   for (const SCEV *&Term : Terms) {
11133     // Normalize the terms before the next call to findArrayDimensionsRec.
11134     const SCEV *Q, *R;
11135     SCEVDivision::divide(SE, Term, Step, &Q, &R);
11136 
11137     // Bail out when GCD does not evenly divide one of the terms.
11138     if (!R->isZero())
11139       return false;
11140 
11141     Term = Q;
11142   }
11143 
11144   // Remove all SCEVConstants.
11145   Terms.erase(
11146       remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }),
11147       Terms.end());
11148 
11149   if (Terms.size() > 0)
11150     if (!findArrayDimensionsRec(SE, Terms, Sizes))
11151       return false;
11152 
11153   Sizes.push_back(Step);
11154   return true;
11155 }
11156 
11157 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter.
11158 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) {
11159   for (const SCEV *T : Terms)
11160     if (SCEVExprContains(T, isa<SCEVUnknown, const SCEV *>))
11161       return true;
11162   return false;
11163 }
11164 
11165 // Return the number of product terms in S.
11166 static inline int numberOfTerms(const SCEV *S) {
11167   if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S))
11168     return Expr->getNumOperands();
11169   return 1;
11170 }
11171 
11172 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) {
11173   if (isa<SCEVConstant>(T))
11174     return nullptr;
11175 
11176   if (isa<SCEVUnknown>(T))
11177     return T;
11178 
11179   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) {
11180     SmallVector<const SCEV *, 2> Factors;
11181     for (const SCEV *Op : M->operands())
11182       if (!isa<SCEVConstant>(Op))
11183         Factors.push_back(Op);
11184 
11185     return SE.getMulExpr(Factors);
11186   }
11187 
11188   return T;
11189 }
11190 
11191 /// Return the size of an element read or written by Inst.
11192 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
11193   Type *Ty;
11194   if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
11195     Ty = Store->getValueOperand()->getType();
11196   else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
11197     Ty = Load->getType();
11198   else
11199     return nullptr;
11200 
11201   Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
11202   return getSizeOfExpr(ETy, Ty);
11203 }
11204 
11205 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
11206                                           SmallVectorImpl<const SCEV *> &Sizes,
11207                                           const SCEV *ElementSize) {
11208   if (Terms.size() < 1 || !ElementSize)
11209     return;
11210 
11211   // Early return when Terms do not contain parameters: we do not delinearize
11212   // non parametric SCEVs.
11213   if (!containsParameters(Terms))
11214     return;
11215 
11216   LLVM_DEBUG({
11217     dbgs() << "Terms:\n";
11218     for (const SCEV *T : Terms)
11219       dbgs() << *T << "\n";
11220   });
11221 
11222   // Remove duplicates.
11223   array_pod_sort(Terms.begin(), Terms.end());
11224   Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end());
11225 
11226   // Put larger terms first.
11227   llvm::sort(Terms, [](const SCEV *LHS, const SCEV *RHS) {
11228     return numberOfTerms(LHS) > numberOfTerms(RHS);
11229   });
11230 
11231   // Try to divide all terms by the element size. If term is not divisible by
11232   // element size, proceed with the original term.
11233   for (const SCEV *&Term : Terms) {
11234     const SCEV *Q, *R;
11235     SCEVDivision::divide(*this, Term, ElementSize, &Q, &R);
11236     if (!Q->isZero())
11237       Term = Q;
11238   }
11239 
11240   SmallVector<const SCEV *, 4> NewTerms;
11241 
11242   // Remove constant factors.
11243   for (const SCEV *T : Terms)
11244     if (const SCEV *NewT = removeConstantFactors(*this, T))
11245       NewTerms.push_back(NewT);
11246 
11247   LLVM_DEBUG({
11248     dbgs() << "Terms after sorting:\n";
11249     for (const SCEV *T : NewTerms)
11250       dbgs() << *T << "\n";
11251   });
11252 
11253   if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) {
11254     Sizes.clear();
11255     return;
11256   }
11257 
11258   // The last element to be pushed into Sizes is the size of an element.
11259   Sizes.push_back(ElementSize);
11260 
11261   LLVM_DEBUG({
11262     dbgs() << "Sizes:\n";
11263     for (const SCEV *S : Sizes)
11264       dbgs() << *S << "\n";
11265   });
11266 }
11267 
11268 void ScalarEvolution::computeAccessFunctions(
11269     const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts,
11270     SmallVectorImpl<const SCEV *> &Sizes) {
11271   // Early exit in case this SCEV is not an affine multivariate function.
11272   if (Sizes.empty())
11273     return;
11274 
11275   if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr))
11276     if (!AR->isAffine())
11277       return;
11278 
11279   const SCEV *Res = Expr;
11280   int Last = Sizes.size() - 1;
11281   for (int i = Last; i >= 0; i--) {
11282     const SCEV *Q, *R;
11283     SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R);
11284 
11285     LLVM_DEBUG({
11286       dbgs() << "Res: " << *Res << "\n";
11287       dbgs() << "Sizes[i]: " << *Sizes[i] << "\n";
11288       dbgs() << "Res divided by Sizes[i]:\n";
11289       dbgs() << "Quotient: " << *Q << "\n";
11290       dbgs() << "Remainder: " << *R << "\n";
11291     });
11292 
11293     Res = Q;
11294 
11295     // Do not record the last subscript corresponding to the size of elements in
11296     // the array.
11297     if (i == Last) {
11298 
11299       // Bail out if the remainder is too complex.
11300       if (isa<SCEVAddRecExpr>(R)) {
11301         Subscripts.clear();
11302         Sizes.clear();
11303         return;
11304       }
11305 
11306       continue;
11307     }
11308 
11309     // Record the access function for the current subscript.
11310     Subscripts.push_back(R);
11311   }
11312 
11313   // Also push in last position the remainder of the last division: it will be
11314   // the access function of the innermost dimension.
11315   Subscripts.push_back(Res);
11316 
11317   std::reverse(Subscripts.begin(), Subscripts.end());
11318 
11319   LLVM_DEBUG({
11320     dbgs() << "Subscripts:\n";
11321     for (const SCEV *S : Subscripts)
11322       dbgs() << *S << "\n";
11323   });
11324 }
11325 
11326 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and
11327 /// sizes of an array access. Returns the remainder of the delinearization that
11328 /// is the offset start of the array.  The SCEV->delinearize algorithm computes
11329 /// the multiples of SCEV coefficients: that is a pattern matching of sub
11330 /// expressions in the stride and base of a SCEV corresponding to the
11331 /// computation of a GCD (greatest common divisor) of base and stride.  When
11332 /// SCEV->delinearize fails, it returns the SCEV unchanged.
11333 ///
11334 /// For example: when analyzing the memory access A[i][j][k] in this loop nest
11335 ///
11336 ///  void foo(long n, long m, long o, double A[n][m][o]) {
11337 ///
11338 ///    for (long i = 0; i < n; i++)
11339 ///      for (long j = 0; j < m; j++)
11340 ///        for (long k = 0; k < o; k++)
11341 ///          A[i][j][k] = 1.0;
11342 ///  }
11343 ///
11344 /// the delinearization input is the following AddRec SCEV:
11345 ///
11346 ///  AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k>
11347 ///
11348 /// From this SCEV, we are able to say that the base offset of the access is %A
11349 /// because it appears as an offset that does not divide any of the strides in
11350 /// the loops:
11351 ///
11352 ///  CHECK: Base offset: %A
11353 ///
11354 /// and then SCEV->delinearize determines the size of some of the dimensions of
11355 /// the array as these are the multiples by which the strides are happening:
11356 ///
11357 ///  CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes.
11358 ///
11359 /// Note that the outermost dimension remains of UnknownSize because there are
11360 /// no strides that would help identifying the size of the last dimension: when
11361 /// the array has been statically allocated, one could compute the size of that
11362 /// dimension by dividing the overall size of the array by the size of the known
11363 /// dimensions: %m * %o * 8.
11364 ///
11365 /// Finally delinearize provides the access functions for the array reference
11366 /// that does correspond to A[i][j][k] of the above C testcase:
11367 ///
11368 ///  CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>]
11369 ///
11370 /// The testcases are checking the output of a function pass:
11371 /// DelinearizationPass that walks through all loads and stores of a function
11372 /// asking for the SCEV of the memory access with respect to all enclosing
11373 /// loops, calling SCEV->delinearize on that and printing the results.
11374 void ScalarEvolution::delinearize(const SCEV *Expr,
11375                                  SmallVectorImpl<const SCEV *> &Subscripts,
11376                                  SmallVectorImpl<const SCEV *> &Sizes,
11377                                  const SCEV *ElementSize) {
11378   // First step: collect parametric terms.
11379   SmallVector<const SCEV *, 4> Terms;
11380   collectParametricTerms(Expr, Terms);
11381 
11382   if (Terms.empty())
11383     return;
11384 
11385   // Second step: find subscript sizes.
11386   findArrayDimensions(Terms, Sizes, ElementSize);
11387 
11388   if (Sizes.empty())
11389     return;
11390 
11391   // Third step: compute the access functions for each subscript.
11392   computeAccessFunctions(Expr, Subscripts, Sizes);
11393 
11394   if (Subscripts.empty())
11395     return;
11396 
11397   LLVM_DEBUG({
11398     dbgs() << "succeeded to delinearize " << *Expr << "\n";
11399     dbgs() << "ArrayDecl[UnknownSize]";
11400     for (const SCEV *S : Sizes)
11401       dbgs() << "[" << *S << "]";
11402 
11403     dbgs() << "\nArrayRef";
11404     for (const SCEV *S : Subscripts)
11405       dbgs() << "[" << *S << "]";
11406     dbgs() << "\n";
11407   });
11408 }
11409 
11410 //===----------------------------------------------------------------------===//
11411 //                   SCEVCallbackVH Class Implementation
11412 //===----------------------------------------------------------------------===//
11413 
11414 void ScalarEvolution::SCEVCallbackVH::deleted() {
11415   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
11416   if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
11417     SE->ConstantEvolutionLoopExitValue.erase(PN);
11418   SE->eraseValueFromMap(getValPtr());
11419   // this now dangles!
11420 }
11421 
11422 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
11423   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
11424 
11425   // Forget all the expressions associated with users of the old value,
11426   // so that future queries will recompute the expressions using the new
11427   // value.
11428   Value *Old = getValPtr();
11429   SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end());
11430   SmallPtrSet<User *, 8> Visited;
11431   while (!Worklist.empty()) {
11432     User *U = Worklist.pop_back_val();
11433     // Deleting the Old value will cause this to dangle. Postpone
11434     // that until everything else is done.
11435     if (U == Old)
11436       continue;
11437     if (!Visited.insert(U).second)
11438       continue;
11439     if (PHINode *PN = dyn_cast<PHINode>(U))
11440       SE->ConstantEvolutionLoopExitValue.erase(PN);
11441     SE->eraseValueFromMap(U);
11442     Worklist.insert(Worklist.end(), U->user_begin(), U->user_end());
11443   }
11444   // Delete the Old value.
11445   if (PHINode *PN = dyn_cast<PHINode>(Old))
11446     SE->ConstantEvolutionLoopExitValue.erase(PN);
11447   SE->eraseValueFromMap(Old);
11448   // this now dangles!
11449 }
11450 
11451 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
11452   : CallbackVH(V), SE(se) {}
11453 
11454 //===----------------------------------------------------------------------===//
11455 //                   ScalarEvolution Class Implementation
11456 //===----------------------------------------------------------------------===//
11457 
11458 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
11459                                  AssumptionCache &AC, DominatorTree &DT,
11460                                  LoopInfo &LI)
11461     : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
11462       CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64),
11463       LoopDispositions(64), BlockDispositions(64) {
11464   // To use guards for proving predicates, we need to scan every instruction in
11465   // relevant basic blocks, and not just terminators.  Doing this is a waste of
11466   // time if the IR does not actually contain any calls to
11467   // @llvm.experimental.guard, so do a quick check and remember this beforehand.
11468   //
11469   // This pessimizes the case where a pass that preserves ScalarEvolution wants
11470   // to _add_ guards to the module when there weren't any before, and wants
11471   // ScalarEvolution to optimize based on those guards.  For now we prefer to be
11472   // efficient in lieu of being smart in that rather obscure case.
11473 
11474   auto *GuardDecl = F.getParent()->getFunction(
11475       Intrinsic::getName(Intrinsic::experimental_guard));
11476   HasGuards = GuardDecl && !GuardDecl->use_empty();
11477 }
11478 
11479 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
11480     : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT),
11481       LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
11482       ValueExprMap(std::move(Arg.ValueExprMap)),
11483       PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
11484       PendingPhiRanges(std::move(Arg.PendingPhiRanges)),
11485       PendingMerges(std::move(Arg.PendingMerges)),
11486       MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)),
11487       BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
11488       PredicatedBackedgeTakenCounts(
11489           std::move(Arg.PredicatedBackedgeTakenCounts)),
11490       ConstantEvolutionLoopExitValue(
11491           std::move(Arg.ConstantEvolutionLoopExitValue)),
11492       ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
11493       LoopDispositions(std::move(Arg.LoopDispositions)),
11494       LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
11495       BlockDispositions(std::move(Arg.BlockDispositions)),
11496       UnsignedRanges(std::move(Arg.UnsignedRanges)),
11497       SignedRanges(std::move(Arg.SignedRanges)),
11498       UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
11499       UniquePreds(std::move(Arg.UniquePreds)),
11500       SCEVAllocator(std::move(Arg.SCEVAllocator)),
11501       LoopUsers(std::move(Arg.LoopUsers)),
11502       PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)),
11503       FirstUnknown(Arg.FirstUnknown) {
11504   Arg.FirstUnknown = nullptr;
11505 }
11506 
11507 ScalarEvolution::~ScalarEvolution() {
11508   // Iterate through all the SCEVUnknown instances and call their
11509   // destructors, so that they release their references to their values.
11510   for (SCEVUnknown *U = FirstUnknown; U;) {
11511     SCEVUnknown *Tmp = U;
11512     U = U->Next;
11513     Tmp->~SCEVUnknown();
11514   }
11515   FirstUnknown = nullptr;
11516 
11517   ExprValueMap.clear();
11518   ValueExprMap.clear();
11519   HasRecMap.clear();
11520 
11521   // Free any extra memory created for ExitNotTakenInfo in the unlikely event
11522   // that a loop had multiple computable exits.
11523   for (auto &BTCI : BackedgeTakenCounts)
11524     BTCI.second.clear();
11525   for (auto &BTCI : PredicatedBackedgeTakenCounts)
11526     BTCI.second.clear();
11527 
11528   assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
11529   assert(PendingPhiRanges.empty() && "getRangeRef garbage");
11530   assert(PendingMerges.empty() && "isImpliedViaMerge garbage");
11531   assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
11532   assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
11533 }
11534 
11535 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
11536   return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
11537 }
11538 
11539 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
11540                           const Loop *L) {
11541   // Print all inner loops first
11542   for (Loop *I : *L)
11543     PrintLoopInfo(OS, SE, I);
11544 
11545   OS << "Loop ";
11546   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
11547   OS << ": ";
11548 
11549   SmallVector<BasicBlock *, 8> ExitingBlocks;
11550   L->getExitingBlocks(ExitingBlocks);
11551   if (ExitingBlocks.size() != 1)
11552     OS << "<multiple exits> ";
11553 
11554   if (SE->hasLoopInvariantBackedgeTakenCount(L))
11555     OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L) << "\n";
11556   else
11557     OS << "Unpredictable backedge-taken count.\n";
11558 
11559   if (ExitingBlocks.size() > 1)
11560     for (BasicBlock *ExitingBlock : ExitingBlocks) {
11561       OS << "  exit count for " << ExitingBlock->getName() << ": "
11562          << *SE->getExitCount(L, ExitingBlock) << "\n";
11563     }
11564 
11565   OS << "Loop ";
11566   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
11567   OS << ": ";
11568 
11569   if (!isa<SCEVCouldNotCompute>(SE->getConstantMaxBackedgeTakenCount(L))) {
11570     OS << "max backedge-taken count is " << *SE->getConstantMaxBackedgeTakenCount(L);
11571     if (SE->isBackedgeTakenCountMaxOrZero(L))
11572       OS << ", actual taken count either this or zero.";
11573   } else {
11574     OS << "Unpredictable max backedge-taken count. ";
11575   }
11576 
11577   OS << "\n"
11578         "Loop ";
11579   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
11580   OS << ": ";
11581 
11582   SCEVUnionPredicate Pred;
11583   auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred);
11584   if (!isa<SCEVCouldNotCompute>(PBT)) {
11585     OS << "Predicated backedge-taken count is " << *PBT << "\n";
11586     OS << " Predicates:\n";
11587     Pred.print(OS, 4);
11588   } else {
11589     OS << "Unpredictable predicated backedge-taken count. ";
11590   }
11591   OS << "\n";
11592 
11593   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
11594     OS << "Loop ";
11595     L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
11596     OS << ": ";
11597     OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
11598   }
11599 }
11600 
11601 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) {
11602   switch (LD) {
11603   case ScalarEvolution::LoopVariant:
11604     return "Variant";
11605   case ScalarEvolution::LoopInvariant:
11606     return "Invariant";
11607   case ScalarEvolution::LoopComputable:
11608     return "Computable";
11609   }
11610   llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!");
11611 }
11612 
11613 void ScalarEvolution::print(raw_ostream &OS) const {
11614   // ScalarEvolution's implementation of the print method is to print
11615   // out SCEV values of all instructions that are interesting. Doing
11616   // this potentially causes it to create new SCEV objects though,
11617   // which technically conflicts with the const qualifier. This isn't
11618   // observable from outside the class though, so casting away the
11619   // const isn't dangerous.
11620   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
11621 
11622   if (ClassifyExpressions) {
11623     OS << "Classifying expressions for: ";
11624     F.printAsOperand(OS, /*PrintType=*/false);
11625     OS << "\n";
11626     for (Instruction &I : instructions(F))
11627       if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
11628         OS << I << '\n';
11629         OS << "  -->  ";
11630         const SCEV *SV = SE.getSCEV(&I);
11631         SV->print(OS);
11632         if (!isa<SCEVCouldNotCompute>(SV)) {
11633           OS << " U: ";
11634           SE.getUnsignedRange(SV).print(OS);
11635           OS << " S: ";
11636           SE.getSignedRange(SV).print(OS);
11637         }
11638 
11639         const Loop *L = LI.getLoopFor(I.getParent());
11640 
11641         const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
11642         if (AtUse != SV) {
11643           OS << "  -->  ";
11644           AtUse->print(OS);
11645           if (!isa<SCEVCouldNotCompute>(AtUse)) {
11646             OS << " U: ";
11647             SE.getUnsignedRange(AtUse).print(OS);
11648             OS << " S: ";
11649             SE.getSignedRange(AtUse).print(OS);
11650           }
11651         }
11652 
11653         if (L) {
11654           OS << "\t\t" "Exits: ";
11655           const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
11656           if (!SE.isLoopInvariant(ExitValue, L)) {
11657             OS << "<<Unknown>>";
11658           } else {
11659             OS << *ExitValue;
11660           }
11661 
11662           bool First = true;
11663           for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
11664             if (First) {
11665               OS << "\t\t" "LoopDispositions: { ";
11666               First = false;
11667             } else {
11668               OS << ", ";
11669             }
11670 
11671             Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
11672             OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter));
11673           }
11674 
11675           for (auto *InnerL : depth_first(L)) {
11676             if (InnerL == L)
11677               continue;
11678             if (First) {
11679               OS << "\t\t" "LoopDispositions: { ";
11680               First = false;
11681             } else {
11682               OS << ", ";
11683             }
11684 
11685             InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
11686             OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL));
11687           }
11688 
11689           OS << " }";
11690         }
11691 
11692         OS << "\n";
11693       }
11694   }
11695 
11696   OS << "Determining loop execution counts for: ";
11697   F.printAsOperand(OS, /*PrintType=*/false);
11698   OS << "\n";
11699   for (Loop *I : LI)
11700     PrintLoopInfo(OS, &SE, I);
11701 }
11702 
11703 ScalarEvolution::LoopDisposition
11704 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
11705   auto &Values = LoopDispositions[S];
11706   for (auto &V : Values) {
11707     if (V.getPointer() == L)
11708       return V.getInt();
11709   }
11710   Values.emplace_back(L, LoopVariant);
11711   LoopDisposition D = computeLoopDisposition(S, L);
11712   auto &Values2 = LoopDispositions[S];
11713   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
11714     if (V.getPointer() == L) {
11715       V.setInt(D);
11716       break;
11717     }
11718   }
11719   return D;
11720 }
11721 
11722 ScalarEvolution::LoopDisposition
11723 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
11724   switch (static_cast<SCEVTypes>(S->getSCEVType())) {
11725   case scConstant:
11726     return LoopInvariant;
11727   case scTruncate:
11728   case scZeroExtend:
11729   case scSignExtend:
11730     return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
11731   case scAddRecExpr: {
11732     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
11733 
11734     // If L is the addrec's loop, it's computable.
11735     if (AR->getLoop() == L)
11736       return LoopComputable;
11737 
11738     // Add recurrences are never invariant in the function-body (null loop).
11739     if (!L)
11740       return LoopVariant;
11741 
11742     // Everything that is not defined at loop entry is variant.
11743     if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader()))
11744       return LoopVariant;
11745     assert(!L->contains(AR->getLoop()) && "Containing loop's header does not"
11746            " dominate the contained loop's header?");
11747 
11748     // This recurrence is invariant w.r.t. L if AR's loop contains L.
11749     if (AR->getLoop()->contains(L))
11750       return LoopInvariant;
11751 
11752     // This recurrence is variant w.r.t. L if any of its operands
11753     // are variant.
11754     for (auto *Op : AR->operands())
11755       if (!isLoopInvariant(Op, L))
11756         return LoopVariant;
11757 
11758     // Otherwise it's loop-invariant.
11759     return LoopInvariant;
11760   }
11761   case scAddExpr:
11762   case scMulExpr:
11763   case scUMaxExpr:
11764   case scSMaxExpr:
11765   case scUMinExpr:
11766   case scSMinExpr: {
11767     bool HasVarying = false;
11768     for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) {
11769       LoopDisposition D = getLoopDisposition(Op, L);
11770       if (D == LoopVariant)
11771         return LoopVariant;
11772       if (D == LoopComputable)
11773         HasVarying = true;
11774     }
11775     return HasVarying ? LoopComputable : LoopInvariant;
11776   }
11777   case scUDivExpr: {
11778     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
11779     LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
11780     if (LD == LoopVariant)
11781       return LoopVariant;
11782     LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
11783     if (RD == LoopVariant)
11784       return LoopVariant;
11785     return (LD == LoopInvariant && RD == LoopInvariant) ?
11786            LoopInvariant : LoopComputable;
11787   }
11788   case scUnknown:
11789     // All non-instruction values are loop invariant.  All instructions are loop
11790     // invariant if they are not contained in the specified loop.
11791     // Instructions are never considered invariant in the function body
11792     // (null loop) because they are defined within the "loop".
11793     if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
11794       return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
11795     return LoopInvariant;
11796   case scCouldNotCompute:
11797     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
11798   }
11799   llvm_unreachable("Unknown SCEV kind!");
11800 }
11801 
11802 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
11803   return getLoopDisposition(S, L) == LoopInvariant;
11804 }
11805 
11806 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
11807   return getLoopDisposition(S, L) == LoopComputable;
11808 }
11809 
11810 ScalarEvolution::BlockDisposition
11811 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
11812   auto &Values = BlockDispositions[S];
11813   for (auto &V : Values) {
11814     if (V.getPointer() == BB)
11815       return V.getInt();
11816   }
11817   Values.emplace_back(BB, DoesNotDominateBlock);
11818   BlockDisposition D = computeBlockDisposition(S, BB);
11819   auto &Values2 = BlockDispositions[S];
11820   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
11821     if (V.getPointer() == BB) {
11822       V.setInt(D);
11823       break;
11824     }
11825   }
11826   return D;
11827 }
11828 
11829 ScalarEvolution::BlockDisposition
11830 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
11831   switch (static_cast<SCEVTypes>(S->getSCEVType())) {
11832   case scConstant:
11833     return ProperlyDominatesBlock;
11834   case scTruncate:
11835   case scZeroExtend:
11836   case scSignExtend:
11837     return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
11838   case scAddRecExpr: {
11839     // This uses a "dominates" query instead of "properly dominates" query
11840     // to test for proper dominance too, because the instruction which
11841     // produces the addrec's value is a PHI, and a PHI effectively properly
11842     // dominates its entire containing block.
11843     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
11844     if (!DT.dominates(AR->getLoop()->getHeader(), BB))
11845       return DoesNotDominateBlock;
11846 
11847     // Fall through into SCEVNAryExpr handling.
11848     LLVM_FALLTHROUGH;
11849   }
11850   case scAddExpr:
11851   case scMulExpr:
11852   case scUMaxExpr:
11853   case scSMaxExpr:
11854   case scUMinExpr:
11855   case scSMinExpr: {
11856     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
11857     bool Proper = true;
11858     for (const SCEV *NAryOp : NAry->operands()) {
11859       BlockDisposition D = getBlockDisposition(NAryOp, BB);
11860       if (D == DoesNotDominateBlock)
11861         return DoesNotDominateBlock;
11862       if (D == DominatesBlock)
11863         Proper = false;
11864     }
11865     return Proper ? ProperlyDominatesBlock : DominatesBlock;
11866   }
11867   case scUDivExpr: {
11868     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
11869     const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
11870     BlockDisposition LD = getBlockDisposition(LHS, BB);
11871     if (LD == DoesNotDominateBlock)
11872       return DoesNotDominateBlock;
11873     BlockDisposition RD = getBlockDisposition(RHS, BB);
11874     if (RD == DoesNotDominateBlock)
11875       return DoesNotDominateBlock;
11876     return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
11877       ProperlyDominatesBlock : DominatesBlock;
11878   }
11879   case scUnknown:
11880     if (Instruction *I =
11881           dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
11882       if (I->getParent() == BB)
11883         return DominatesBlock;
11884       if (DT.properlyDominates(I->getParent(), BB))
11885         return ProperlyDominatesBlock;
11886       return DoesNotDominateBlock;
11887     }
11888     return ProperlyDominatesBlock;
11889   case scCouldNotCompute:
11890     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
11891   }
11892   llvm_unreachable("Unknown SCEV kind!");
11893 }
11894 
11895 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
11896   return getBlockDisposition(S, BB) >= DominatesBlock;
11897 }
11898 
11899 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
11900   return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
11901 }
11902 
11903 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
11904   return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; });
11905 }
11906 
11907 bool ScalarEvolution::ExitLimit::hasOperand(const SCEV *S) const {
11908   auto IsS = [&](const SCEV *X) { return S == X; };
11909   auto ContainsS = [&](const SCEV *X) {
11910     return !isa<SCEVCouldNotCompute>(X) && SCEVExprContains(X, IsS);
11911   };
11912   return ContainsS(ExactNotTaken) || ContainsS(MaxNotTaken);
11913 }
11914 
11915 void
11916 ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
11917   ValuesAtScopes.erase(S);
11918   LoopDispositions.erase(S);
11919   BlockDispositions.erase(S);
11920   UnsignedRanges.erase(S);
11921   SignedRanges.erase(S);
11922   ExprValueMap.erase(S);
11923   HasRecMap.erase(S);
11924   MinTrailingZerosCache.erase(S);
11925 
11926   for (auto I = PredicatedSCEVRewrites.begin();
11927        I != PredicatedSCEVRewrites.end();) {
11928     std::pair<const SCEV *, const Loop *> Entry = I->first;
11929     if (Entry.first == S)
11930       PredicatedSCEVRewrites.erase(I++);
11931     else
11932       ++I;
11933   }
11934 
11935   auto RemoveSCEVFromBackedgeMap =
11936       [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
11937         for (auto I = Map.begin(), E = Map.end(); I != E;) {
11938           BackedgeTakenInfo &BEInfo = I->second;
11939           if (BEInfo.hasOperand(S, this)) {
11940             BEInfo.clear();
11941             Map.erase(I++);
11942           } else
11943             ++I;
11944         }
11945       };
11946 
11947   RemoveSCEVFromBackedgeMap(BackedgeTakenCounts);
11948   RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts);
11949 }
11950 
11951 void
11952 ScalarEvolution::getUsedLoops(const SCEV *S,
11953                               SmallPtrSetImpl<const Loop *> &LoopsUsed) {
11954   struct FindUsedLoops {
11955     FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed)
11956         : LoopsUsed(LoopsUsed) {}
11957     SmallPtrSetImpl<const Loop *> &LoopsUsed;
11958     bool follow(const SCEV *S) {
11959       if (auto *AR = dyn_cast<SCEVAddRecExpr>(S))
11960         LoopsUsed.insert(AR->getLoop());
11961       return true;
11962     }
11963 
11964     bool isDone() const { return false; }
11965   };
11966 
11967   FindUsedLoops F(LoopsUsed);
11968   SCEVTraversal<FindUsedLoops>(F).visitAll(S);
11969 }
11970 
11971 void ScalarEvolution::addToLoopUseLists(const SCEV *S) {
11972   SmallPtrSet<const Loop *, 8> LoopsUsed;
11973   getUsedLoops(S, LoopsUsed);
11974   for (auto *L : LoopsUsed)
11975     LoopUsers[L].push_back(S);
11976 }
11977 
11978 void ScalarEvolution::verify() const {
11979   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
11980   ScalarEvolution SE2(F, TLI, AC, DT, LI);
11981 
11982   SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end());
11983 
11984   // Map's SCEV expressions from one ScalarEvolution "universe" to another.
11985   struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> {
11986     SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {}
11987 
11988     const SCEV *visitConstant(const SCEVConstant *Constant) {
11989       return SE.getConstant(Constant->getAPInt());
11990     }
11991 
11992     const SCEV *visitUnknown(const SCEVUnknown *Expr) {
11993       return SE.getUnknown(Expr->getValue());
11994     }
11995 
11996     const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
11997       return SE.getCouldNotCompute();
11998     }
11999   };
12000 
12001   SCEVMapper SCM(SE2);
12002 
12003   while (!LoopStack.empty()) {
12004     auto *L = LoopStack.pop_back_val();
12005     LoopStack.insert(LoopStack.end(), L->begin(), L->end());
12006 
12007     auto *CurBECount = SCM.visit(
12008         const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L));
12009     auto *NewBECount = SE2.getBackedgeTakenCount(L);
12010 
12011     if (CurBECount == SE2.getCouldNotCompute() ||
12012         NewBECount == SE2.getCouldNotCompute()) {
12013       // NB! This situation is legal, but is very suspicious -- whatever pass
12014       // change the loop to make a trip count go from could not compute to
12015       // computable or vice-versa *should have* invalidated SCEV.  However, we
12016       // choose not to assert here (for now) since we don't want false
12017       // positives.
12018       continue;
12019     }
12020 
12021     if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) {
12022       // SCEV treats "undef" as an unknown but consistent value (i.e. it does
12023       // not propagate undef aggressively).  This means we can (and do) fail
12024       // verification in cases where a transform makes the trip count of a loop
12025       // go from "undef" to "undef+1" (say).  The transform is fine, since in
12026       // both cases the loop iterates "undef" times, but SCEV thinks we
12027       // increased the trip count of the loop by 1 incorrectly.
12028       continue;
12029     }
12030 
12031     if (SE.getTypeSizeInBits(CurBECount->getType()) >
12032         SE.getTypeSizeInBits(NewBECount->getType()))
12033       NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType());
12034     else if (SE.getTypeSizeInBits(CurBECount->getType()) <
12035              SE.getTypeSizeInBits(NewBECount->getType()))
12036       CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType());
12037 
12038     const SCEV *Delta = SE2.getMinusSCEV(CurBECount, NewBECount);
12039 
12040     // Unless VerifySCEVStrict is set, we only compare constant deltas.
12041     if ((VerifySCEVStrict || isa<SCEVConstant>(Delta)) && !Delta->isZero()) {
12042       dbgs() << "Trip Count for " << *L << " Changed!\n";
12043       dbgs() << "Old: " << *CurBECount << "\n";
12044       dbgs() << "New: " << *NewBECount << "\n";
12045       dbgs() << "Delta: " << *Delta << "\n";
12046       std::abort();
12047     }
12048   }
12049 }
12050 
12051 bool ScalarEvolution::invalidate(
12052     Function &F, const PreservedAnalyses &PA,
12053     FunctionAnalysisManager::Invalidator &Inv) {
12054   // Invalidate the ScalarEvolution object whenever it isn't preserved or one
12055   // of its dependencies is invalidated.
12056   auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
12057   return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
12058          Inv.invalidate<AssumptionAnalysis>(F, PA) ||
12059          Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
12060          Inv.invalidate<LoopAnalysis>(F, PA);
12061 }
12062 
12063 AnalysisKey ScalarEvolutionAnalysis::Key;
12064 
12065 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
12066                                              FunctionAnalysisManager &AM) {
12067   return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F),
12068                          AM.getResult<AssumptionAnalysis>(F),
12069                          AM.getResult<DominatorTreeAnalysis>(F),
12070                          AM.getResult<LoopAnalysis>(F));
12071 }
12072 
12073 PreservedAnalyses
12074 ScalarEvolutionVerifierPass::run(Function &F, FunctionAnalysisManager &AM) {
12075   AM.getResult<ScalarEvolutionAnalysis>(F).verify();
12076   return PreservedAnalyses::all();
12077 }
12078 
12079 PreservedAnalyses
12080 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
12081   AM.getResult<ScalarEvolutionAnalysis>(F).print(OS);
12082   return PreservedAnalyses::all();
12083 }
12084 
12085 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
12086                       "Scalar Evolution Analysis", false, true)
12087 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
12088 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
12089 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
12090 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
12091 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
12092                     "Scalar Evolution Analysis", false, true)
12093 
12094 char ScalarEvolutionWrapperPass::ID = 0;
12095 
12096 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
12097   initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
12098 }
12099 
12100 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
12101   SE.reset(new ScalarEvolution(
12102       F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F),
12103       getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
12104       getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
12105       getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
12106   return false;
12107 }
12108 
12109 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
12110 
12111 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
12112   SE->print(OS);
12113 }
12114 
12115 void ScalarEvolutionWrapperPass::verifyAnalysis() const {
12116   if (!VerifySCEV)
12117     return;
12118 
12119   SE->verify();
12120 }
12121 
12122 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
12123   AU.setPreservesAll();
12124   AU.addRequiredTransitive<AssumptionCacheTracker>();
12125   AU.addRequiredTransitive<LoopInfoWrapperPass>();
12126   AU.addRequiredTransitive<DominatorTreeWrapperPass>();
12127   AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
12128 }
12129 
12130 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS,
12131                                                         const SCEV *RHS) {
12132   FoldingSetNodeID ID;
12133   assert(LHS->getType() == RHS->getType() &&
12134          "Type mismatch between LHS and RHS");
12135   // Unique this node based on the arguments
12136   ID.AddInteger(SCEVPredicate::P_Equal);
12137   ID.AddPointer(LHS);
12138   ID.AddPointer(RHS);
12139   void *IP = nullptr;
12140   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
12141     return S;
12142   SCEVEqualPredicate *Eq = new (SCEVAllocator)
12143       SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS);
12144   UniquePreds.InsertNode(Eq, IP);
12145   return Eq;
12146 }
12147 
12148 const SCEVPredicate *ScalarEvolution::getWrapPredicate(
12149     const SCEVAddRecExpr *AR,
12150     SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
12151   FoldingSetNodeID ID;
12152   // Unique this node based on the arguments
12153   ID.AddInteger(SCEVPredicate::P_Wrap);
12154   ID.AddPointer(AR);
12155   ID.AddInteger(AddedFlags);
12156   void *IP = nullptr;
12157   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
12158     return S;
12159   auto *OF = new (SCEVAllocator)
12160       SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
12161   UniquePreds.InsertNode(OF, IP);
12162   return OF;
12163 }
12164 
12165 namespace {
12166 
12167 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
12168 public:
12169 
12170   /// Rewrites \p S in the context of a loop L and the SCEV predication
12171   /// infrastructure.
12172   ///
12173   /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
12174   /// equivalences present in \p Pred.
12175   ///
12176   /// If \p NewPreds is non-null, rewrite is free to add further predicates to
12177   /// \p NewPreds such that the result will be an AddRecExpr.
12178   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
12179                              SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
12180                              SCEVUnionPredicate *Pred) {
12181     SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
12182     return Rewriter.visit(S);
12183   }
12184 
12185   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
12186     if (Pred) {
12187       auto ExprPreds = Pred->getPredicatesForExpr(Expr);
12188       for (auto *Pred : ExprPreds)
12189         if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred))
12190           if (IPred->getLHS() == Expr)
12191             return IPred->getRHS();
12192     }
12193     return convertToAddRecWithPreds(Expr);
12194   }
12195 
12196   const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
12197     const SCEV *Operand = visit(Expr->getOperand());
12198     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
12199     if (AR && AR->getLoop() == L && AR->isAffine()) {
12200       // This couldn't be folded because the operand didn't have the nuw
12201       // flag. Add the nusw flag as an assumption that we could make.
12202       const SCEV *Step = AR->getStepRecurrence(SE);
12203       Type *Ty = Expr->getType();
12204       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
12205         return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
12206                                 SE.getSignExtendExpr(Step, Ty), L,
12207                                 AR->getNoWrapFlags());
12208     }
12209     return SE.getZeroExtendExpr(Operand, Expr->getType());
12210   }
12211 
12212   const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
12213     const SCEV *Operand = visit(Expr->getOperand());
12214     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
12215     if (AR && AR->getLoop() == L && AR->isAffine()) {
12216       // This couldn't be folded because the operand didn't have the nsw
12217       // flag. Add the nssw flag as an assumption that we could make.
12218       const SCEV *Step = AR->getStepRecurrence(SE);
12219       Type *Ty = Expr->getType();
12220       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
12221         return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
12222                                 SE.getSignExtendExpr(Step, Ty), L,
12223                                 AR->getNoWrapFlags());
12224     }
12225     return SE.getSignExtendExpr(Operand, Expr->getType());
12226   }
12227 
12228 private:
12229   explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE,
12230                         SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
12231                         SCEVUnionPredicate *Pred)
12232       : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
12233 
12234   bool addOverflowAssumption(const SCEVPredicate *P) {
12235     if (!NewPreds) {
12236       // Check if we've already made this assumption.
12237       return Pred && Pred->implies(P);
12238     }
12239     NewPreds->insert(P);
12240     return true;
12241   }
12242 
12243   bool addOverflowAssumption(const SCEVAddRecExpr *AR,
12244                              SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
12245     auto *A = SE.getWrapPredicate(AR, AddedFlags);
12246     return addOverflowAssumption(A);
12247   }
12248 
12249   // If \p Expr represents a PHINode, we try to see if it can be represented
12250   // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible
12251   // to add this predicate as a runtime overflow check, we return the AddRec.
12252   // If \p Expr does not meet these conditions (is not a PHI node, or we
12253   // couldn't create an AddRec for it, or couldn't add the predicate), we just
12254   // return \p Expr.
12255   const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) {
12256     if (!isa<PHINode>(Expr->getValue()))
12257       return Expr;
12258     Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
12259     PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr);
12260     if (!PredicatedRewrite)
12261       return Expr;
12262     for (auto *P : PredicatedRewrite->second){
12263       // Wrap predicates from outer loops are not supported.
12264       if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) {
12265         auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr());
12266         if (L != AR->getLoop())
12267           return Expr;
12268       }
12269       if (!addOverflowAssumption(P))
12270         return Expr;
12271     }
12272     return PredicatedRewrite->first;
12273   }
12274 
12275   SmallPtrSetImpl<const SCEVPredicate *> *NewPreds;
12276   SCEVUnionPredicate *Pred;
12277   const Loop *L;
12278 };
12279 
12280 } // end anonymous namespace
12281 
12282 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
12283                                                    SCEVUnionPredicate &Preds) {
12284   return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
12285 }
12286 
12287 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates(
12288     const SCEV *S, const Loop *L,
12289     SmallPtrSetImpl<const SCEVPredicate *> &Preds) {
12290   SmallPtrSet<const SCEVPredicate *, 4> TransformPreds;
12291   S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
12292   auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
12293 
12294   if (!AddRec)
12295     return nullptr;
12296 
12297   // Since the transformation was successful, we can now transfer the SCEV
12298   // predicates.
12299   for (auto *P : TransformPreds)
12300     Preds.insert(P);
12301 
12302   return AddRec;
12303 }
12304 
12305 /// SCEV predicates
12306 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
12307                              SCEVPredicateKind Kind)
12308     : FastID(ID), Kind(Kind) {}
12309 
12310 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID,
12311                                        const SCEV *LHS, const SCEV *RHS)
12312     : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {
12313   assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match");
12314   assert(LHS != RHS && "LHS and RHS are the same SCEV");
12315 }
12316 
12317 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const {
12318   const auto *Op = dyn_cast<SCEVEqualPredicate>(N);
12319 
12320   if (!Op)
12321     return false;
12322 
12323   return Op->LHS == LHS && Op->RHS == RHS;
12324 }
12325 
12326 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; }
12327 
12328 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; }
12329 
12330 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const {
12331   OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
12332 }
12333 
12334 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
12335                                      const SCEVAddRecExpr *AR,
12336                                      IncrementWrapFlags Flags)
12337     : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
12338 
12339 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; }
12340 
12341 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const {
12342   const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
12343 
12344   return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags;
12345 }
12346 
12347 bool SCEVWrapPredicate::isAlwaysTrue() const {
12348   SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
12349   IncrementWrapFlags IFlags = Flags;
12350 
12351   if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
12352     IFlags = clearFlags(IFlags, IncrementNSSW);
12353 
12354   return IFlags == IncrementAnyWrap;
12355 }
12356 
12357 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
12358   OS.indent(Depth) << *getExpr() << " Added Flags: ";
12359   if (SCEVWrapPredicate::IncrementNUSW & getFlags())
12360     OS << "<nusw>";
12361   if (SCEVWrapPredicate::IncrementNSSW & getFlags())
12362     OS << "<nssw>";
12363   OS << "\n";
12364 }
12365 
12366 SCEVWrapPredicate::IncrementWrapFlags
12367 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR,
12368                                    ScalarEvolution &SE) {
12369   IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
12370   SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
12371 
12372   // We can safely transfer the NSW flag as NSSW.
12373   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
12374     ImpliedFlags = IncrementNSSW;
12375 
12376   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
12377     // If the increment is positive, the SCEV NUW flag will also imply the
12378     // WrapPredicate NUSW flag.
12379     if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
12380       if (Step->getValue()->getValue().isNonNegative())
12381         ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
12382   }
12383 
12384   return ImpliedFlags;
12385 }
12386 
12387 /// Union predicates don't get cached so create a dummy set ID for it.
12388 SCEVUnionPredicate::SCEVUnionPredicate()
12389     : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {}
12390 
12391 bool SCEVUnionPredicate::isAlwaysTrue() const {
12392   return all_of(Preds,
12393                 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
12394 }
12395 
12396 ArrayRef<const SCEVPredicate *>
12397 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) {
12398   auto I = SCEVToPreds.find(Expr);
12399   if (I == SCEVToPreds.end())
12400     return ArrayRef<const SCEVPredicate *>();
12401   return I->second;
12402 }
12403 
12404 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
12405   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
12406     return all_of(Set->Preds,
12407                   [this](const SCEVPredicate *I) { return this->implies(I); });
12408 
12409   auto ScevPredsIt = SCEVToPreds.find(N->getExpr());
12410   if (ScevPredsIt == SCEVToPreds.end())
12411     return false;
12412   auto &SCEVPreds = ScevPredsIt->second;
12413 
12414   return any_of(SCEVPreds,
12415                 [N](const SCEVPredicate *I) { return I->implies(N); });
12416 }
12417 
12418 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; }
12419 
12420 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
12421   for (auto Pred : Preds)
12422     Pred->print(OS, Depth);
12423 }
12424 
12425 void SCEVUnionPredicate::add(const SCEVPredicate *N) {
12426   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
12427     for (auto Pred : Set->Preds)
12428       add(Pred);
12429     return;
12430   }
12431 
12432   if (implies(N))
12433     return;
12434 
12435   const SCEV *Key = N->getExpr();
12436   assert(Key && "Only SCEVUnionPredicate doesn't have an "
12437                 " associated expression!");
12438 
12439   SCEVToPreds[Key].push_back(N);
12440   Preds.push_back(N);
12441 }
12442 
12443 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
12444                                                      Loop &L)
12445     : SE(SE), L(L) {}
12446 
12447 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
12448   const SCEV *Expr = SE.getSCEV(V);
12449   RewriteEntry &Entry = RewriteMap[Expr];
12450 
12451   // If we already have an entry and the version matches, return it.
12452   if (Entry.second && Generation == Entry.first)
12453     return Entry.second;
12454 
12455   // We found an entry but it's stale. Rewrite the stale entry
12456   // according to the current predicate.
12457   if (Entry.second)
12458     Expr = Entry.second;
12459 
12460   const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds);
12461   Entry = {Generation, NewSCEV};
12462 
12463   return NewSCEV;
12464 }
12465 
12466 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() {
12467   if (!BackedgeCount) {
12468     SCEVUnionPredicate BackedgePred;
12469     BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred);
12470     addPredicate(BackedgePred);
12471   }
12472   return BackedgeCount;
12473 }
12474 
12475 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
12476   if (Preds.implies(&Pred))
12477     return;
12478   Preds.add(&Pred);
12479   updateGeneration();
12480 }
12481 
12482 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const {
12483   return Preds;
12484 }
12485 
12486 void PredicatedScalarEvolution::updateGeneration() {
12487   // If the generation number wrapped recompute everything.
12488   if (++Generation == 0) {
12489     for (auto &II : RewriteMap) {
12490       const SCEV *Rewritten = II.second.second;
12491       II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)};
12492     }
12493   }
12494 }
12495 
12496 void PredicatedScalarEvolution::setNoOverflow(
12497     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
12498   const SCEV *Expr = getSCEV(V);
12499   const auto *AR = cast<SCEVAddRecExpr>(Expr);
12500 
12501   auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE);
12502 
12503   // Clear the statically implied flags.
12504   Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags);
12505   addPredicate(*SE.getWrapPredicate(AR, Flags));
12506 
12507   auto II = FlagsMap.insert({V, Flags});
12508   if (!II.second)
12509     II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second);
12510 }
12511 
12512 bool PredicatedScalarEvolution::hasNoOverflow(
12513     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
12514   const SCEV *Expr = getSCEV(V);
12515   const auto *AR = cast<SCEVAddRecExpr>(Expr);
12516 
12517   Flags = SCEVWrapPredicate::clearFlags(
12518       Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
12519 
12520   auto II = FlagsMap.find(V);
12521 
12522   if (II != FlagsMap.end())
12523     Flags = SCEVWrapPredicate::clearFlags(Flags, II->second);
12524 
12525   return Flags == SCEVWrapPredicate::IncrementAnyWrap;
12526 }
12527 
12528 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) {
12529   const SCEV *Expr = this->getSCEV(V);
12530   SmallPtrSet<const SCEVPredicate *, 4> NewPreds;
12531   auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
12532 
12533   if (!New)
12534     return nullptr;
12535 
12536   for (auto *P : NewPreds)
12537     Preds.add(P);
12538 
12539   updateGeneration();
12540   RewriteMap[SE.getSCEV(V)] = {Generation, New};
12541   return New;
12542 }
12543 
12544 PredicatedScalarEvolution::PredicatedScalarEvolution(
12545     const PredicatedScalarEvolution &Init)
12546     : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds),
12547       Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
12548   for (auto I : Init.FlagsMap)
12549     FlagsMap.insert(I);
12550 }
12551 
12552 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const {
12553   // For each block.
12554   for (auto *BB : L.getBlocks())
12555     for (auto &I : *BB) {
12556       if (!SE.isSCEVable(I.getType()))
12557         continue;
12558 
12559       auto *Expr = SE.getSCEV(&I);
12560       auto II = RewriteMap.find(Expr);
12561 
12562       if (II == RewriteMap.end())
12563         continue;
12564 
12565       // Don't print things that are not interesting.
12566       if (II->second.second == Expr)
12567         continue;
12568 
12569       OS.indent(Depth) << "[PSE]" << I << ":\n";
12570       OS.indent(Depth + 2) << *Expr << "\n";
12571       OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
12572     }
12573 }
12574 
12575 // Match the mathematical pattern A - (A / B) * B, where A and B can be
12576 // arbitrary expressions.
12577 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is
12578 // 4, A / B becomes X / 8).
12579 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS,
12580                                 const SCEV *&RHS) {
12581   const auto *Add = dyn_cast<SCEVAddExpr>(Expr);
12582   if (Add == nullptr || Add->getNumOperands() != 2)
12583     return false;
12584 
12585   const SCEV *A = Add->getOperand(1);
12586   const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0));
12587 
12588   if (Mul == nullptr)
12589     return false;
12590 
12591   const auto MatchURemWithDivisor = [&](const SCEV *B) {
12592     // (SomeExpr + (-(SomeExpr / B) * B)).
12593     if (Expr == getURemExpr(A, B)) {
12594       LHS = A;
12595       RHS = B;
12596       return true;
12597     }
12598     return false;
12599   };
12600 
12601   // (SomeExpr + (-1 * (SomeExpr / B) * B)).
12602   if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0)))
12603     return MatchURemWithDivisor(Mul->getOperand(1)) ||
12604            MatchURemWithDivisor(Mul->getOperand(2));
12605 
12606   // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)).
12607   if (Mul->getNumOperands() == 2)
12608     return MatchURemWithDivisor(Mul->getOperand(1)) ||
12609            MatchURemWithDivisor(Mul->getOperand(0)) ||
12610            MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) ||
12611            MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0)));
12612   return false;
12613 }
12614