xref: /freebsd/contrib/llvm-project/llvm/lib/Analysis/ScalarEvolution.cpp (revision 0bf56da32d83fbd3b5db8d6c72cd1e7cc26fbc66)
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   // Implementation detail: all the cleverness here should happen without
4511   // creating new SCEV expressions -- our caller knowns tricks to avoid creating
4512   // SCEV expressions when possible, and we should not break that.
4513 
4514   switch (Op->getOpcode()) {
4515   case Instruction::Add:
4516   case Instruction::Sub:
4517   case Instruction::Mul:
4518   case Instruction::UDiv:
4519   case Instruction::URem:
4520   case Instruction::And:
4521   case Instruction::Or:
4522   case Instruction::AShr:
4523   case Instruction::Shl:
4524     return BinaryOp(Op);
4525 
4526   case Instruction::Xor:
4527     if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
4528       // If the RHS of the xor is a signmask, then this is just an add.
4529       // Instcombine turns add of signmask into xor as a strength reduction step.
4530       if (RHSC->getValue().isSignMask())
4531         return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
4532     return BinaryOp(Op);
4533 
4534   case Instruction::LShr:
4535     // Turn logical shift right of a constant into a unsigned divide.
4536     if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
4537       uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
4538 
4539       // If the shift count is not less than the bitwidth, the result of
4540       // the shift is undefined. Don't try to analyze it, because the
4541       // resolution chosen here may differ from the resolution chosen in
4542       // other parts of the compiler.
4543       if (SA->getValue().ult(BitWidth)) {
4544         Constant *X =
4545             ConstantInt::get(SA->getContext(),
4546                              APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
4547         return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
4548       }
4549     }
4550     return BinaryOp(Op);
4551 
4552   case Instruction::ExtractValue: {
4553     auto *EVI = cast<ExtractValueInst>(Op);
4554     if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
4555       break;
4556 
4557     auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand());
4558     if (!WO)
4559       break;
4560 
4561     Instruction::BinaryOps BinOp = WO->getBinaryOp();
4562     bool Signed = WO->isSigned();
4563     // TODO: Should add nuw/nsw flags for mul as well.
4564     if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT))
4565       return BinaryOp(BinOp, WO->getLHS(), WO->getRHS());
4566 
4567     // Now that we know that all uses of the arithmetic-result component of
4568     // CI are guarded by the overflow check, we can go ahead and pretend
4569     // that the arithmetic is non-overflowing.
4570     return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(),
4571                     /* IsNSW = */ Signed, /* IsNUW = */ !Signed);
4572   }
4573 
4574   default:
4575     break;
4576   }
4577 
4578   // Recognise intrinsic loop.decrement.reg, and as this has exactly the same
4579   // semantics as a Sub, return a binary sub expression.
4580   if (auto *II = dyn_cast<IntrinsicInst>(V))
4581     if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg)
4582       return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1));
4583 
4584   return None;
4585 }
4586 
4587 /// Helper function to createAddRecFromPHIWithCasts. We have a phi
4588 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
4589 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
4590 /// way. This function checks if \p Op, an operand of this SCEVAddExpr,
4591 /// follows one of the following patterns:
4592 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4593 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4594 /// If the SCEV expression of \p Op conforms with one of the expected patterns
4595 /// we return the type of the truncation operation, and indicate whether the
4596 /// truncated type should be treated as signed/unsigned by setting
4597 /// \p Signed to true/false, respectively.
4598 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
4599                                bool &Signed, ScalarEvolution &SE) {
4600   // The case where Op == SymbolicPHI (that is, with no type conversions on
4601   // the way) is handled by the regular add recurrence creating logic and
4602   // would have already been triggered in createAddRecForPHI. Reaching it here
4603   // means that createAddRecFromPHI had failed for this PHI before (e.g.,
4604   // because one of the other operands of the SCEVAddExpr updating this PHI is
4605   // not invariant).
4606   //
4607   // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
4608   // this case predicates that allow us to prove that Op == SymbolicPHI will
4609   // be added.
4610   if (Op == SymbolicPHI)
4611     return nullptr;
4612 
4613   unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
4614   unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
4615   if (SourceBits != NewBits)
4616     return nullptr;
4617 
4618   const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op);
4619   const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op);
4620   if (!SExt && !ZExt)
4621     return nullptr;
4622   const SCEVTruncateExpr *Trunc =
4623       SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand())
4624            : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand());
4625   if (!Trunc)
4626     return nullptr;
4627   const SCEV *X = Trunc->getOperand();
4628   if (X != SymbolicPHI)
4629     return nullptr;
4630   Signed = SExt != nullptr;
4631   return Trunc->getType();
4632 }
4633 
4634 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
4635   if (!PN->getType()->isIntegerTy())
4636     return nullptr;
4637   const Loop *L = LI.getLoopFor(PN->getParent());
4638   if (!L || L->getHeader() != PN->getParent())
4639     return nullptr;
4640   return L;
4641 }
4642 
4643 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
4644 // computation that updates the phi follows the following pattern:
4645 //   (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
4646 // which correspond to a phi->trunc->sext/zext->add->phi update chain.
4647 // If so, try to see if it can be rewritten as an AddRecExpr under some
4648 // Predicates. If successful, return them as a pair. Also cache the results
4649 // of the analysis.
4650 //
4651 // Example usage scenario:
4652 //    Say the Rewriter is called for the following SCEV:
4653 //         8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4654 //    where:
4655 //         %X = phi i64 (%Start, %BEValue)
4656 //    It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
4657 //    and call this function with %SymbolicPHI = %X.
4658 //
4659 //    The analysis will find that the value coming around the backedge has
4660 //    the following SCEV:
4661 //         BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4662 //    Upon concluding that this matches the desired pattern, the function
4663 //    will return the pair {NewAddRec, SmallPredsVec} where:
4664 //         NewAddRec = {%Start,+,%Step}
4665 //         SmallPredsVec = {P1, P2, P3} as follows:
4666 //           P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
4667 //           P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
4668 //           P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
4669 //    The returned pair means that SymbolicPHI can be rewritten into NewAddRec
4670 //    under the predicates {P1,P2,P3}.
4671 //    This predicated rewrite will be cached in PredicatedSCEVRewrites:
4672 //         PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
4673 //
4674 // TODO's:
4675 //
4676 // 1) Extend the Induction descriptor to also support inductions that involve
4677 //    casts: When needed (namely, when we are called in the context of the
4678 //    vectorizer induction analysis), a Set of cast instructions will be
4679 //    populated by this method, and provided back to isInductionPHI. This is
4680 //    needed to allow the vectorizer to properly record them to be ignored by
4681 //    the cost model and to avoid vectorizing them (otherwise these casts,
4682 //    which are redundant under the runtime overflow checks, will be
4683 //    vectorized, which can be costly).
4684 //
4685 // 2) Support additional induction/PHISCEV patterns: We also want to support
4686 //    inductions where the sext-trunc / zext-trunc operations (partly) occur
4687 //    after the induction update operation (the induction increment):
4688 //
4689 //      (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
4690 //    which correspond to a phi->add->trunc->sext/zext->phi update chain.
4691 //
4692 //      (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
4693 //    which correspond to a phi->trunc->add->sext/zext->phi update chain.
4694 //
4695 // 3) Outline common code with createAddRecFromPHI to avoid duplication.
4696 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4697 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
4698   SmallVector<const SCEVPredicate *, 3> Predicates;
4699 
4700   // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
4701   // return an AddRec expression under some predicate.
4702 
4703   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
4704   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
4705   assert(L && "Expecting an integer loop header phi");
4706 
4707   // The loop may have multiple entrances or multiple exits; we can analyze
4708   // this phi as an addrec if it has a unique entry value and a unique
4709   // backedge value.
4710   Value *BEValueV = nullptr, *StartValueV = nullptr;
4711   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4712     Value *V = PN->getIncomingValue(i);
4713     if (L->contains(PN->getIncomingBlock(i))) {
4714       if (!BEValueV) {
4715         BEValueV = V;
4716       } else if (BEValueV != V) {
4717         BEValueV = nullptr;
4718         break;
4719       }
4720     } else if (!StartValueV) {
4721       StartValueV = V;
4722     } else if (StartValueV != V) {
4723       StartValueV = nullptr;
4724       break;
4725     }
4726   }
4727   if (!BEValueV || !StartValueV)
4728     return None;
4729 
4730   const SCEV *BEValue = getSCEV(BEValueV);
4731 
4732   // If the value coming around the backedge is an add with the symbolic
4733   // value we just inserted, possibly with casts that we can ignore under
4734   // an appropriate runtime guard, then we found a simple induction variable!
4735   const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
4736   if (!Add)
4737     return None;
4738 
4739   // If there is a single occurrence of the symbolic value, possibly
4740   // casted, replace it with a recurrence.
4741   unsigned FoundIndex = Add->getNumOperands();
4742   Type *TruncTy = nullptr;
4743   bool Signed;
4744   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4745     if ((TruncTy =
4746              isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
4747       if (FoundIndex == e) {
4748         FoundIndex = i;
4749         break;
4750       }
4751 
4752   if (FoundIndex == Add->getNumOperands())
4753     return None;
4754 
4755   // Create an add with everything but the specified operand.
4756   SmallVector<const SCEV *, 8> Ops;
4757   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4758     if (i != FoundIndex)
4759       Ops.push_back(Add->getOperand(i));
4760   const SCEV *Accum = getAddExpr(Ops);
4761 
4762   // The runtime checks will not be valid if the step amount is
4763   // varying inside the loop.
4764   if (!isLoopInvariant(Accum, L))
4765     return None;
4766 
4767   // *** Part2: Create the predicates
4768 
4769   // Analysis was successful: we have a phi-with-cast pattern for which we
4770   // can return an AddRec expression under the following predicates:
4771   //
4772   // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
4773   //     fits within the truncated type (does not overflow) for i = 0 to n-1.
4774   // P2: An Equal predicate that guarantees that
4775   //     Start = (Ext ix (Trunc iy (Start) to ix) to iy)
4776   // P3: An Equal predicate that guarantees that
4777   //     Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
4778   //
4779   // As we next prove, the above predicates guarantee that:
4780   //     Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
4781   //
4782   //
4783   // More formally, we want to prove that:
4784   //     Expr(i+1) = Start + (i+1) * Accum
4785   //               = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4786   //
4787   // Given that:
4788   // 1) Expr(0) = Start
4789   // 2) Expr(1) = Start + Accum
4790   //            = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
4791   // 3) Induction hypothesis (step i):
4792   //    Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
4793   //
4794   // Proof:
4795   //  Expr(i+1) =
4796   //   = Start + (i+1)*Accum
4797   //   = (Start + i*Accum) + Accum
4798   //   = Expr(i) + Accum
4799   //   = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
4800   //                                                             :: from step i
4801   //
4802   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
4803   //
4804   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
4805   //     + (Ext ix (Trunc iy (Accum) to ix) to iy)
4806   //     + Accum                                                     :: from P3
4807   //
4808   //   = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
4809   //     + Accum                            :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
4810   //
4811   //   = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
4812   //   = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4813   //
4814   // By induction, the same applies to all iterations 1<=i<n:
4815   //
4816 
4817   // Create a truncated addrec for which we will add a no overflow check (P1).
4818   const SCEV *StartVal = getSCEV(StartValueV);
4819   const SCEV *PHISCEV =
4820       getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
4821                     getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap);
4822 
4823   // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
4824   // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
4825   // will be constant.
4826   //
4827   //  If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
4828   // add P1.
4829   if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
4830     SCEVWrapPredicate::IncrementWrapFlags AddedFlags =
4831         Signed ? SCEVWrapPredicate::IncrementNSSW
4832                : SCEVWrapPredicate::IncrementNUSW;
4833     const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
4834     Predicates.push_back(AddRecPred);
4835   }
4836 
4837   // Create the Equal Predicates P2,P3:
4838 
4839   // It is possible that the predicates P2 and/or P3 are computable at
4840   // compile time due to StartVal and/or Accum being constants.
4841   // If either one is, then we can check that now and escape if either P2
4842   // or P3 is false.
4843 
4844   // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
4845   // for each of StartVal and Accum
4846   auto getExtendedExpr = [&](const SCEV *Expr,
4847                              bool CreateSignExtend) -> const SCEV * {
4848     assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant");
4849     const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
4850     const SCEV *ExtendedExpr =
4851         CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType())
4852                          : getZeroExtendExpr(TruncatedExpr, Expr->getType());
4853     return ExtendedExpr;
4854   };
4855 
4856   // Given:
4857   //  ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
4858   //               = getExtendedExpr(Expr)
4859   // Determine whether the predicate P: Expr == ExtendedExpr
4860   // is known to be false at compile time
4861   auto PredIsKnownFalse = [&](const SCEV *Expr,
4862                               const SCEV *ExtendedExpr) -> bool {
4863     return Expr != ExtendedExpr &&
4864            isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr);
4865   };
4866 
4867   const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
4868   if (PredIsKnownFalse(StartVal, StartExtended)) {
4869     LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";);
4870     return None;
4871   }
4872 
4873   // The Step is always Signed (because the overflow checks are either
4874   // NSSW or NUSW)
4875   const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true);
4876   if (PredIsKnownFalse(Accum, AccumExtended)) {
4877     LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";);
4878     return None;
4879   }
4880 
4881   auto AppendPredicate = [&](const SCEV *Expr,
4882                              const SCEV *ExtendedExpr) -> void {
4883     if (Expr != ExtendedExpr &&
4884         !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
4885       const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
4886       LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred);
4887       Predicates.push_back(Pred);
4888     }
4889   };
4890 
4891   AppendPredicate(StartVal, StartExtended);
4892   AppendPredicate(Accum, AccumExtended);
4893 
4894   // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
4895   // which the casts had been folded away. The caller can rewrite SymbolicPHI
4896   // into NewAR if it will also add the runtime overflow checks specified in
4897   // Predicates.
4898   auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap);
4899 
4900   std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
4901       std::make_pair(NewAR, Predicates);
4902   // Remember the result of the analysis for this SCEV at this locayyytion.
4903   PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
4904   return PredRewrite;
4905 }
4906 
4907 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4908 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) {
4909   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
4910   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
4911   if (!L)
4912     return None;
4913 
4914   // Check to see if we already analyzed this PHI.
4915   auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
4916   if (I != PredicatedSCEVRewrites.end()) {
4917     std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
4918         I->second;
4919     // Analysis was done before and failed to create an AddRec:
4920     if (Rewrite.first == SymbolicPHI)
4921       return None;
4922     // Analysis was done before and succeeded to create an AddRec under
4923     // a predicate:
4924     assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec");
4925     assert(!(Rewrite.second).empty() && "Expected to find Predicates");
4926     return Rewrite;
4927   }
4928 
4929   Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4930     Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
4931 
4932   // Record in the cache that the analysis failed
4933   if (!Rewrite) {
4934     SmallVector<const SCEVPredicate *, 3> Predicates;
4935     PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
4936     return None;
4937   }
4938 
4939   return Rewrite;
4940 }
4941 
4942 // FIXME: This utility is currently required because the Rewriter currently
4943 // does not rewrite this expression:
4944 // {0, +, (sext ix (trunc iy to ix) to iy)}
4945 // into {0, +, %step},
4946 // even when the following Equal predicate exists:
4947 // "%step == (sext ix (trunc iy to ix) to iy)".
4948 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds(
4949     const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const {
4950   if (AR1 == AR2)
4951     return true;
4952 
4953   auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool {
4954     if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) &&
4955         !Preds.implies(SE.getEqualPredicate(Expr2, Expr1)))
4956       return false;
4957     return true;
4958   };
4959 
4960   if (!areExprsEqual(AR1->getStart(), AR2->getStart()) ||
4961       !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE)))
4962     return false;
4963   return true;
4964 }
4965 
4966 /// A helper function for createAddRecFromPHI to handle simple cases.
4967 ///
4968 /// This function tries to find an AddRec expression for the simplest (yet most
4969 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
4970 /// If it fails, createAddRecFromPHI will use a more general, but slow,
4971 /// technique for finding the AddRec expression.
4972 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
4973                                                       Value *BEValueV,
4974                                                       Value *StartValueV) {
4975   const Loop *L = LI.getLoopFor(PN->getParent());
4976   assert(L && L->getHeader() == PN->getParent());
4977   assert(BEValueV && StartValueV);
4978 
4979   auto BO = MatchBinaryOp(BEValueV, DT);
4980   if (!BO)
4981     return nullptr;
4982 
4983   if (BO->Opcode != Instruction::Add)
4984     return nullptr;
4985 
4986   const SCEV *Accum = nullptr;
4987   if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
4988     Accum = getSCEV(BO->RHS);
4989   else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
4990     Accum = getSCEV(BO->LHS);
4991 
4992   if (!Accum)
4993     return nullptr;
4994 
4995   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4996   if (BO->IsNUW)
4997     Flags = setFlags(Flags, SCEV::FlagNUW);
4998   if (BO->IsNSW)
4999     Flags = setFlags(Flags, SCEV::FlagNSW);
5000 
5001   const SCEV *StartVal = getSCEV(StartValueV);
5002   const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5003 
5004   ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
5005 
5006   // We can add Flags to the post-inc expression only if we
5007   // know that it is *undefined behavior* for BEValueV to
5008   // overflow.
5009   if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5010     if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5011       (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5012 
5013   return PHISCEV;
5014 }
5015 
5016 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
5017   const Loop *L = LI.getLoopFor(PN->getParent());
5018   if (!L || L->getHeader() != PN->getParent())
5019     return nullptr;
5020 
5021   // The loop may have multiple entrances or multiple exits; we can analyze
5022   // this phi as an addrec if it has a unique entry value and a unique
5023   // backedge value.
5024   Value *BEValueV = nullptr, *StartValueV = nullptr;
5025   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5026     Value *V = PN->getIncomingValue(i);
5027     if (L->contains(PN->getIncomingBlock(i))) {
5028       if (!BEValueV) {
5029         BEValueV = V;
5030       } else if (BEValueV != V) {
5031         BEValueV = nullptr;
5032         break;
5033       }
5034     } else if (!StartValueV) {
5035       StartValueV = V;
5036     } else if (StartValueV != V) {
5037       StartValueV = nullptr;
5038       break;
5039     }
5040   }
5041   if (!BEValueV || !StartValueV)
5042     return nullptr;
5043 
5044   assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
5045          "PHI node already processed?");
5046 
5047   // First, try to find AddRec expression without creating a fictituos symbolic
5048   // value for PN.
5049   if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
5050     return S;
5051 
5052   // Handle PHI node value symbolically.
5053   const SCEV *SymbolicName = getUnknown(PN);
5054   ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName});
5055 
5056   // Using this symbolic name for the PHI, analyze the value coming around
5057   // the back-edge.
5058   const SCEV *BEValue = getSCEV(BEValueV);
5059 
5060   // NOTE: If BEValue is loop invariant, we know that the PHI node just
5061   // has a special value for the first iteration of the loop.
5062 
5063   // If the value coming around the backedge is an add with the symbolic
5064   // value we just inserted, then we found a simple induction variable!
5065   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
5066     // If there is a single occurrence of the symbolic value, replace it
5067     // with a recurrence.
5068     unsigned FoundIndex = Add->getNumOperands();
5069     for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5070       if (Add->getOperand(i) == SymbolicName)
5071         if (FoundIndex == e) {
5072           FoundIndex = i;
5073           break;
5074         }
5075 
5076     if (FoundIndex != Add->getNumOperands()) {
5077       // Create an add with everything but the specified operand.
5078       SmallVector<const SCEV *, 8> Ops;
5079       for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5080         if (i != FoundIndex)
5081           Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i),
5082                                                              L, *this));
5083       const SCEV *Accum = getAddExpr(Ops);
5084 
5085       // This is not a valid addrec if the step amount is varying each
5086       // loop iteration, but is not itself an addrec in this loop.
5087       if (isLoopInvariant(Accum, L) ||
5088           (isa<SCEVAddRecExpr>(Accum) &&
5089            cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
5090         SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5091 
5092         if (auto BO = MatchBinaryOp(BEValueV, DT)) {
5093           if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
5094             if (BO->IsNUW)
5095               Flags = setFlags(Flags, SCEV::FlagNUW);
5096             if (BO->IsNSW)
5097               Flags = setFlags(Flags, SCEV::FlagNSW);
5098           }
5099         } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
5100           // If the increment is an inbounds GEP, then we know the address
5101           // space cannot be wrapped around. We cannot make any guarantee
5102           // about signed or unsigned overflow because pointers are
5103           // unsigned but we may have a negative index from the base
5104           // pointer. We can guarantee that no unsigned wrap occurs if the
5105           // indices form a positive value.
5106           if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
5107             Flags = setFlags(Flags, SCEV::FlagNW);
5108 
5109             const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
5110             if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
5111               Flags = setFlags(Flags, SCEV::FlagNUW);
5112           }
5113 
5114           // We cannot transfer nuw and nsw flags from subtraction
5115           // operations -- sub nuw X, Y is not the same as add nuw X, -Y
5116           // for instance.
5117         }
5118 
5119         const SCEV *StartVal = getSCEV(StartValueV);
5120         const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5121 
5122         // Okay, for the entire analysis of this edge we assumed the PHI
5123         // to be symbolic.  We now need to go back and purge all of the
5124         // entries for the scalars that use the symbolic expression.
5125         forgetSymbolicName(PN, SymbolicName);
5126         ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
5127 
5128         // We can add Flags to the post-inc expression only if we
5129         // know that it is *undefined behavior* for BEValueV to
5130         // overflow.
5131         if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5132           if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5133             (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5134 
5135         return PHISCEV;
5136       }
5137     }
5138   } else {
5139     // Otherwise, this could be a loop like this:
5140     //     i = 0;  for (j = 1; ..; ++j) { ....  i = j; }
5141     // In this case, j = {1,+,1}  and BEValue is j.
5142     // Because the other in-value of i (0) fits the evolution of BEValue
5143     // i really is an addrec evolution.
5144     //
5145     // We can generalize this saying that i is the shifted value of BEValue
5146     // by one iteration:
5147     //   PHI(f(0), f({1,+,1})) --> f({0,+,1})
5148     const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
5149     const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false);
5150     if (Shifted != getCouldNotCompute() &&
5151         Start != getCouldNotCompute()) {
5152       const SCEV *StartVal = getSCEV(StartValueV);
5153       if (Start == StartVal) {
5154         // Okay, for the entire analysis of this edge we assumed the PHI
5155         // to be symbolic.  We now need to go back and purge all of the
5156         // entries for the scalars that use the symbolic expression.
5157         forgetSymbolicName(PN, SymbolicName);
5158         ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted;
5159         return Shifted;
5160       }
5161     }
5162   }
5163 
5164   // Remove the temporary PHI node SCEV that has been inserted while intending
5165   // to create an AddRecExpr for this PHI node. We can not keep this temporary
5166   // as it will prevent later (possibly simpler) SCEV expressions to be added
5167   // to the ValueExprMap.
5168   eraseValueFromMap(PN);
5169 
5170   return nullptr;
5171 }
5172 
5173 // Checks if the SCEV S is available at BB.  S is considered available at BB
5174 // if S can be materialized at BB without introducing a fault.
5175 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
5176                                BasicBlock *BB) {
5177   struct CheckAvailable {
5178     bool TraversalDone = false;
5179     bool Available = true;
5180 
5181     const Loop *L = nullptr;  // The loop BB is in (can be nullptr)
5182     BasicBlock *BB = nullptr;
5183     DominatorTree &DT;
5184 
5185     CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
5186       : L(L), BB(BB), DT(DT) {}
5187 
5188     bool setUnavailable() {
5189       TraversalDone = true;
5190       Available = false;
5191       return false;
5192     }
5193 
5194     bool follow(const SCEV *S) {
5195       switch (S->getSCEVType()) {
5196       case scConstant: case scTruncate: case scZeroExtend: case scSignExtend:
5197       case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr:
5198       case scUMinExpr:
5199       case scSMinExpr:
5200         // These expressions are available if their operand(s) is/are.
5201         return true;
5202 
5203       case scAddRecExpr: {
5204         // We allow add recurrences that are on the loop BB is in, or some
5205         // outer loop.  This guarantees availability because the value of the
5206         // add recurrence at BB is simply the "current" value of the induction
5207         // variable.  We can relax this in the future; for instance an add
5208         // recurrence on a sibling dominating loop is also available at BB.
5209         const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
5210         if (L && (ARLoop == L || ARLoop->contains(L)))
5211           return true;
5212 
5213         return setUnavailable();
5214       }
5215 
5216       case scUnknown: {
5217         // For SCEVUnknown, we check for simple dominance.
5218         const auto *SU = cast<SCEVUnknown>(S);
5219         Value *V = SU->getValue();
5220 
5221         if (isa<Argument>(V))
5222           return false;
5223 
5224         if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
5225           return false;
5226 
5227         return setUnavailable();
5228       }
5229 
5230       case scUDivExpr:
5231       case scCouldNotCompute:
5232         // We do not try to smart about these at all.
5233         return setUnavailable();
5234       }
5235       llvm_unreachable("switch should be fully covered!");
5236     }
5237 
5238     bool isDone() { return TraversalDone; }
5239   };
5240 
5241   CheckAvailable CA(L, BB, DT);
5242   SCEVTraversal<CheckAvailable> ST(CA);
5243 
5244   ST.visitAll(S);
5245   return CA.Available;
5246 }
5247 
5248 // Try to match a control flow sequence that branches out at BI and merges back
5249 // at Merge into a "C ? LHS : RHS" select pattern.  Return true on a successful
5250 // match.
5251 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
5252                           Value *&C, Value *&LHS, Value *&RHS) {
5253   C = BI->getCondition();
5254 
5255   BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
5256   BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
5257 
5258   if (!LeftEdge.isSingleEdge())
5259     return false;
5260 
5261   assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
5262 
5263   Use &LeftUse = Merge->getOperandUse(0);
5264   Use &RightUse = Merge->getOperandUse(1);
5265 
5266   if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
5267     LHS = LeftUse;
5268     RHS = RightUse;
5269     return true;
5270   }
5271 
5272   if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
5273     LHS = RightUse;
5274     RHS = LeftUse;
5275     return true;
5276   }
5277 
5278   return false;
5279 }
5280 
5281 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
5282   auto IsReachable =
5283       [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
5284   if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
5285     const Loop *L = LI.getLoopFor(PN->getParent());
5286 
5287     // We don't want to break LCSSA, even in a SCEV expression tree.
5288     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
5289       if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
5290         return nullptr;
5291 
5292     // Try to match
5293     //
5294     //  br %cond, label %left, label %right
5295     // left:
5296     //  br label %merge
5297     // right:
5298     //  br label %merge
5299     // merge:
5300     //  V = phi [ %x, %left ], [ %y, %right ]
5301     //
5302     // as "select %cond, %x, %y"
5303 
5304     BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
5305     assert(IDom && "At least the entry block should dominate PN");
5306 
5307     auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
5308     Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
5309 
5310     if (BI && BI->isConditional() &&
5311         BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
5312         IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
5313         IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
5314       return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
5315   }
5316 
5317   return nullptr;
5318 }
5319 
5320 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
5321   if (const SCEV *S = createAddRecFromPHI(PN))
5322     return S;
5323 
5324   if (const SCEV *S = createNodeFromSelectLikePHI(PN))
5325     return S;
5326 
5327   // If the PHI has a single incoming value, follow that value, unless the
5328   // PHI's incoming blocks are in a different loop, in which case doing so
5329   // risks breaking LCSSA form. Instcombine would normally zap these, but
5330   // it doesn't have DominatorTree information, so it may miss cases.
5331   if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC}))
5332     if (LI.replacementPreservesLCSSAForm(PN, V))
5333       return getSCEV(V);
5334 
5335   // If it's not a loop phi, we can't handle it yet.
5336   return getUnknown(PN);
5337 }
5338 
5339 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I,
5340                                                       Value *Cond,
5341                                                       Value *TrueVal,
5342                                                       Value *FalseVal) {
5343   // Handle "constant" branch or select. This can occur for instance when a
5344   // loop pass transforms an inner loop and moves on to process the outer loop.
5345   if (auto *CI = dyn_cast<ConstantInt>(Cond))
5346     return getSCEV(CI->isOne() ? TrueVal : FalseVal);
5347 
5348   // Try to match some simple smax or umax patterns.
5349   auto *ICI = dyn_cast<ICmpInst>(Cond);
5350   if (!ICI)
5351     return getUnknown(I);
5352 
5353   Value *LHS = ICI->getOperand(0);
5354   Value *RHS = ICI->getOperand(1);
5355 
5356   switch (ICI->getPredicate()) {
5357   case ICmpInst::ICMP_SLT:
5358   case ICmpInst::ICMP_SLE:
5359     std::swap(LHS, RHS);
5360     LLVM_FALLTHROUGH;
5361   case ICmpInst::ICMP_SGT:
5362   case ICmpInst::ICMP_SGE:
5363     // a >s b ? a+x : b+x  ->  smax(a, b)+x
5364     // a >s b ? b+x : a+x  ->  smin(a, b)+x
5365     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5366       const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType());
5367       const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType());
5368       const SCEV *LA = getSCEV(TrueVal);
5369       const SCEV *RA = getSCEV(FalseVal);
5370       const SCEV *LDiff = getMinusSCEV(LA, LS);
5371       const SCEV *RDiff = getMinusSCEV(RA, RS);
5372       if (LDiff == RDiff)
5373         return getAddExpr(getSMaxExpr(LS, RS), LDiff);
5374       LDiff = getMinusSCEV(LA, RS);
5375       RDiff = getMinusSCEV(RA, LS);
5376       if (LDiff == RDiff)
5377         return getAddExpr(getSMinExpr(LS, RS), LDiff);
5378     }
5379     break;
5380   case ICmpInst::ICMP_ULT:
5381   case ICmpInst::ICMP_ULE:
5382     std::swap(LHS, RHS);
5383     LLVM_FALLTHROUGH;
5384   case ICmpInst::ICMP_UGT:
5385   case ICmpInst::ICMP_UGE:
5386     // a >u b ? a+x : b+x  ->  umax(a, b)+x
5387     // a >u b ? b+x : a+x  ->  umin(a, b)+x
5388     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5389       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5390       const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType());
5391       const SCEV *LA = getSCEV(TrueVal);
5392       const SCEV *RA = getSCEV(FalseVal);
5393       const SCEV *LDiff = getMinusSCEV(LA, LS);
5394       const SCEV *RDiff = getMinusSCEV(RA, RS);
5395       if (LDiff == RDiff)
5396         return getAddExpr(getUMaxExpr(LS, RS), LDiff);
5397       LDiff = getMinusSCEV(LA, RS);
5398       RDiff = getMinusSCEV(RA, LS);
5399       if (LDiff == RDiff)
5400         return getAddExpr(getUMinExpr(LS, RS), LDiff);
5401     }
5402     break;
5403   case ICmpInst::ICMP_NE:
5404     // n != 0 ? n+x : 1+x  ->  umax(n, 1)+x
5405     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5406         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5407       const SCEV *One = getOne(I->getType());
5408       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5409       const SCEV *LA = getSCEV(TrueVal);
5410       const SCEV *RA = getSCEV(FalseVal);
5411       const SCEV *LDiff = getMinusSCEV(LA, LS);
5412       const SCEV *RDiff = getMinusSCEV(RA, One);
5413       if (LDiff == RDiff)
5414         return getAddExpr(getUMaxExpr(One, LS), LDiff);
5415     }
5416     break;
5417   case ICmpInst::ICMP_EQ:
5418     // n == 0 ? 1+x : n+x  ->  umax(n, 1)+x
5419     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5420         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5421       const SCEV *One = getOne(I->getType());
5422       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5423       const SCEV *LA = getSCEV(TrueVal);
5424       const SCEV *RA = getSCEV(FalseVal);
5425       const SCEV *LDiff = getMinusSCEV(LA, One);
5426       const SCEV *RDiff = getMinusSCEV(RA, LS);
5427       if (LDiff == RDiff)
5428         return getAddExpr(getUMaxExpr(One, LS), LDiff);
5429     }
5430     break;
5431   default:
5432     break;
5433   }
5434 
5435   return getUnknown(I);
5436 }
5437 
5438 /// Expand GEP instructions into add and multiply operations. This allows them
5439 /// to be analyzed by regular SCEV code.
5440 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
5441   // Don't attempt to analyze GEPs over unsized objects.
5442   if (!GEP->getSourceElementType()->isSized())
5443     return getUnknown(GEP);
5444 
5445   SmallVector<const SCEV *, 4> IndexExprs;
5446   for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
5447     IndexExprs.push_back(getSCEV(*Index));
5448   return getGEPExpr(GEP, IndexExprs);
5449 }
5450 
5451 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) {
5452   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5453     return C->getAPInt().countTrailingZeros();
5454 
5455   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
5456     return std::min(GetMinTrailingZeros(T->getOperand()),
5457                     (uint32_t)getTypeSizeInBits(T->getType()));
5458 
5459   if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
5460     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5461     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5462                ? getTypeSizeInBits(E->getType())
5463                : OpRes;
5464   }
5465 
5466   if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
5467     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5468     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5469                ? getTypeSizeInBits(E->getType())
5470                : OpRes;
5471   }
5472 
5473   if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
5474     // The result is the min of all operands results.
5475     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5476     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5477       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5478     return MinOpRes;
5479   }
5480 
5481   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
5482     // The result is the sum of all operands results.
5483     uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
5484     uint32_t BitWidth = getTypeSizeInBits(M->getType());
5485     for (unsigned i = 1, e = M->getNumOperands();
5486          SumOpRes != BitWidth && i != e; ++i)
5487       SumOpRes =
5488           std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth);
5489     return SumOpRes;
5490   }
5491 
5492   if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
5493     // The result is the min of all operands results.
5494     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5495     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5496       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5497     return MinOpRes;
5498   }
5499 
5500   if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
5501     // The result is the min of all operands results.
5502     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5503     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5504       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5505     return MinOpRes;
5506   }
5507 
5508   if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
5509     // The result is the min of all operands results.
5510     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5511     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5512       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5513     return MinOpRes;
5514   }
5515 
5516   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5517     // For a SCEVUnknown, ask ValueTracking.
5518     KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT);
5519     return Known.countMinTrailingZeros();
5520   }
5521 
5522   // SCEVUDivExpr
5523   return 0;
5524 }
5525 
5526 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
5527   auto I = MinTrailingZerosCache.find(S);
5528   if (I != MinTrailingZerosCache.end())
5529     return I->second;
5530 
5531   uint32_t Result = GetMinTrailingZerosImpl(S);
5532   auto InsertPair = MinTrailingZerosCache.insert({S, Result});
5533   assert(InsertPair.second && "Should insert a new key");
5534   return InsertPair.first->second;
5535 }
5536 
5537 /// Helper method to assign a range to V from metadata present in the IR.
5538 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
5539   if (Instruction *I = dyn_cast<Instruction>(V))
5540     if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
5541       return getConstantRangeFromMetadata(*MD);
5542 
5543   return None;
5544 }
5545 
5546 /// Determine the range for a particular SCEV.  If SignHint is
5547 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
5548 /// with a "cleaner" unsigned (resp. signed) representation.
5549 const ConstantRange &
5550 ScalarEvolution::getRangeRef(const SCEV *S,
5551                              ScalarEvolution::RangeSignHint SignHint) {
5552   DenseMap<const SCEV *, ConstantRange> &Cache =
5553       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
5554                                                        : SignedRanges;
5555   ConstantRange::PreferredRangeType RangeType =
5556       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED
5557           ? ConstantRange::Unsigned : ConstantRange::Signed;
5558 
5559   // See if we've computed this range already.
5560   DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
5561   if (I != Cache.end())
5562     return I->second;
5563 
5564   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5565     return setRange(C, SignHint, ConstantRange(C->getAPInt()));
5566 
5567   unsigned BitWidth = getTypeSizeInBits(S->getType());
5568   ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
5569   using OBO = OverflowingBinaryOperator;
5570 
5571   // If the value has known zeros, the maximum value will have those known zeros
5572   // as well.
5573   uint32_t TZ = GetMinTrailingZeros(S);
5574   if (TZ != 0) {
5575     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
5576       ConservativeResult =
5577           ConstantRange(APInt::getMinValue(BitWidth),
5578                         APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
5579     else
5580       ConservativeResult = ConstantRange(
5581           APInt::getSignedMinValue(BitWidth),
5582           APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
5583   }
5584 
5585   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
5586     ConstantRange X = getRangeRef(Add->getOperand(0), SignHint);
5587     unsigned WrapType = OBO::AnyWrap;
5588     if (Add->hasNoSignedWrap())
5589       WrapType |= OBO::NoSignedWrap;
5590     if (Add->hasNoUnsignedWrap())
5591       WrapType |= OBO::NoUnsignedWrap;
5592     for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
5593       X = X.addWithNoWrap(getRangeRef(Add->getOperand(i), SignHint),
5594                           WrapType, RangeType);
5595     return setRange(Add, SignHint,
5596                     ConservativeResult.intersectWith(X, RangeType));
5597   }
5598 
5599   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
5600     ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint);
5601     for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
5602       X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint));
5603     return setRange(Mul, SignHint,
5604                     ConservativeResult.intersectWith(X, RangeType));
5605   }
5606 
5607   if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
5608     ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint);
5609     for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
5610       X = X.smax(getRangeRef(SMax->getOperand(i), SignHint));
5611     return setRange(SMax, SignHint,
5612                     ConservativeResult.intersectWith(X, RangeType));
5613   }
5614 
5615   if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
5616     ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint);
5617     for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
5618       X = X.umax(getRangeRef(UMax->getOperand(i), SignHint));
5619     return setRange(UMax, SignHint,
5620                     ConservativeResult.intersectWith(X, RangeType));
5621   }
5622 
5623   if (const SCEVSMinExpr *SMin = dyn_cast<SCEVSMinExpr>(S)) {
5624     ConstantRange X = getRangeRef(SMin->getOperand(0), SignHint);
5625     for (unsigned i = 1, e = SMin->getNumOperands(); i != e; ++i)
5626       X = X.smin(getRangeRef(SMin->getOperand(i), SignHint));
5627     return setRange(SMin, SignHint,
5628                     ConservativeResult.intersectWith(X, RangeType));
5629   }
5630 
5631   if (const SCEVUMinExpr *UMin = dyn_cast<SCEVUMinExpr>(S)) {
5632     ConstantRange X = getRangeRef(UMin->getOperand(0), SignHint);
5633     for (unsigned i = 1, e = UMin->getNumOperands(); i != e; ++i)
5634       X = X.umin(getRangeRef(UMin->getOperand(i), SignHint));
5635     return setRange(UMin, SignHint,
5636                     ConservativeResult.intersectWith(X, RangeType));
5637   }
5638 
5639   if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
5640     ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint);
5641     ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint);
5642     return setRange(UDiv, SignHint,
5643                     ConservativeResult.intersectWith(X.udiv(Y), RangeType));
5644   }
5645 
5646   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
5647     ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint);
5648     return setRange(ZExt, SignHint,
5649                     ConservativeResult.intersectWith(X.zeroExtend(BitWidth),
5650                                                      RangeType));
5651   }
5652 
5653   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
5654     ConstantRange X = getRangeRef(SExt->getOperand(), SignHint);
5655     return setRange(SExt, SignHint,
5656                     ConservativeResult.intersectWith(X.signExtend(BitWidth),
5657                                                      RangeType));
5658   }
5659 
5660   if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
5661     ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint);
5662     return setRange(Trunc, SignHint,
5663                     ConservativeResult.intersectWith(X.truncate(BitWidth),
5664                                                      RangeType));
5665   }
5666 
5667   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
5668     // If there's no unsigned wrap, the value will never be less than its
5669     // initial value.
5670     if (AddRec->hasNoUnsignedWrap()) {
5671       APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart());
5672       if (!UnsignedMinValue.isNullValue())
5673         ConservativeResult = ConservativeResult.intersectWith(
5674             ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType);
5675     }
5676 
5677     // If there's no signed wrap, and all the operands except initial value have
5678     // the same sign or zero, the value won't ever be:
5679     // 1: smaller than initial value if operands are non negative,
5680     // 2: bigger than initial value if operands are non positive.
5681     // For both cases, value can not cross signed min/max boundary.
5682     if (AddRec->hasNoSignedWrap()) {
5683       bool AllNonNeg = true;
5684       bool AllNonPos = true;
5685       for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) {
5686         if (!isKnownNonNegative(AddRec->getOperand(i)))
5687           AllNonNeg = false;
5688         if (!isKnownNonPositive(AddRec->getOperand(i)))
5689           AllNonPos = false;
5690       }
5691       if (AllNonNeg)
5692         ConservativeResult = ConservativeResult.intersectWith(
5693             ConstantRange::getNonEmpty(getSignedRangeMin(AddRec->getStart()),
5694                                        APInt::getSignedMinValue(BitWidth)),
5695             RangeType);
5696       else if (AllNonPos)
5697         ConservativeResult = ConservativeResult.intersectWith(
5698             ConstantRange::getNonEmpty(
5699                 APInt::getSignedMinValue(BitWidth),
5700                 getSignedRangeMax(AddRec->getStart()) + 1),
5701             RangeType);
5702     }
5703 
5704     // TODO: non-affine addrec
5705     if (AddRec->isAffine()) {
5706       const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(AddRec->getLoop());
5707       if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
5708           getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
5709         auto RangeFromAffine = getRangeForAffineAR(
5710             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
5711             BitWidth);
5712         if (!RangeFromAffine.isFullSet())
5713           ConservativeResult =
5714               ConservativeResult.intersectWith(RangeFromAffine, RangeType);
5715 
5716         auto RangeFromFactoring = getRangeViaFactoring(
5717             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
5718             BitWidth);
5719         if (!RangeFromFactoring.isFullSet())
5720           ConservativeResult =
5721               ConservativeResult.intersectWith(RangeFromFactoring, RangeType);
5722       }
5723     }
5724 
5725     return setRange(AddRec, SignHint, std::move(ConservativeResult));
5726   }
5727 
5728   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5729     // Check if the IR explicitly contains !range metadata.
5730     Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
5731     if (MDRange.hasValue())
5732       ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue(),
5733                                                             RangeType);
5734 
5735     // Split here to avoid paying the compile-time cost of calling both
5736     // computeKnownBits and ComputeNumSignBits.  This restriction can be lifted
5737     // if needed.
5738     const DataLayout &DL = getDataLayout();
5739     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
5740       // For a SCEVUnknown, ask ValueTracking.
5741       KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
5742       if (Known.getBitWidth() != BitWidth)
5743         Known = Known.zextOrTrunc(BitWidth, true);
5744       // If Known does not result in full-set, intersect with it.
5745       if (Known.getMinValue() != Known.getMaxValue() + 1)
5746         ConservativeResult = ConservativeResult.intersectWith(
5747             ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1),
5748             RangeType);
5749     } else {
5750       assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED &&
5751              "generalize as needed!");
5752       unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
5753       // If the pointer size is larger than the index size type, this can cause
5754       // NS to be larger than BitWidth. So compensate for this.
5755       if (U->getType()->isPointerTy()) {
5756         unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType());
5757         int ptrIdxDiff = ptrSize - BitWidth;
5758         if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff)
5759           NS -= ptrIdxDiff;
5760       }
5761 
5762       if (NS > 1)
5763         ConservativeResult = ConservativeResult.intersectWith(
5764             ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
5765                           APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1),
5766             RangeType);
5767     }
5768 
5769     // A range of Phi is a subset of union of all ranges of its input.
5770     if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) {
5771       // Make sure that we do not run over cycled Phis.
5772       if (PendingPhiRanges.insert(Phi).second) {
5773         ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false);
5774         for (auto &Op : Phi->operands()) {
5775           auto OpRange = getRangeRef(getSCEV(Op), SignHint);
5776           RangeFromOps = RangeFromOps.unionWith(OpRange);
5777           // No point to continue if we already have a full set.
5778           if (RangeFromOps.isFullSet())
5779             break;
5780         }
5781         ConservativeResult =
5782             ConservativeResult.intersectWith(RangeFromOps, RangeType);
5783         bool Erased = PendingPhiRanges.erase(Phi);
5784         assert(Erased && "Failed to erase Phi properly?");
5785         (void) Erased;
5786       }
5787     }
5788 
5789     return setRange(U, SignHint, std::move(ConservativeResult));
5790   }
5791 
5792   return setRange(S, SignHint, std::move(ConservativeResult));
5793 }
5794 
5795 // Given a StartRange, Step and MaxBECount for an expression compute a range of
5796 // values that the expression can take. Initially, the expression has a value
5797 // from StartRange and then is changed by Step up to MaxBECount times. Signed
5798 // argument defines if we treat Step as signed or unsigned.
5799 static ConstantRange getRangeForAffineARHelper(APInt Step,
5800                                                const ConstantRange &StartRange,
5801                                                const APInt &MaxBECount,
5802                                                unsigned BitWidth, bool Signed) {
5803   // If either Step or MaxBECount is 0, then the expression won't change, and we
5804   // just need to return the initial range.
5805   if (Step == 0 || MaxBECount == 0)
5806     return StartRange;
5807 
5808   // If we don't know anything about the initial value (i.e. StartRange is
5809   // FullRange), then we don't know anything about the final range either.
5810   // Return FullRange.
5811   if (StartRange.isFullSet())
5812     return ConstantRange::getFull(BitWidth);
5813 
5814   // If Step is signed and negative, then we use its absolute value, but we also
5815   // note that we're moving in the opposite direction.
5816   bool Descending = Signed && Step.isNegative();
5817 
5818   if (Signed)
5819     // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
5820     // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
5821     // This equations hold true due to the well-defined wrap-around behavior of
5822     // APInt.
5823     Step = Step.abs();
5824 
5825   // Check if Offset is more than full span of BitWidth. If it is, the
5826   // expression is guaranteed to overflow.
5827   if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
5828     return ConstantRange::getFull(BitWidth);
5829 
5830   // Offset is by how much the expression can change. Checks above guarantee no
5831   // overflow here.
5832   APInt Offset = Step * MaxBECount;
5833 
5834   // Minimum value of the final range will match the minimal value of StartRange
5835   // if the expression is increasing and will be decreased by Offset otherwise.
5836   // Maximum value of the final range will match the maximal value of StartRange
5837   // if the expression is decreasing and will be increased by Offset otherwise.
5838   APInt StartLower = StartRange.getLower();
5839   APInt StartUpper = StartRange.getUpper() - 1;
5840   APInt MovedBoundary = Descending ? (StartLower - std::move(Offset))
5841                                    : (StartUpper + std::move(Offset));
5842 
5843   // It's possible that the new minimum/maximum value will fall into the initial
5844   // range (due to wrap around). This means that the expression can take any
5845   // value in this bitwidth, and we have to return full range.
5846   if (StartRange.contains(MovedBoundary))
5847     return ConstantRange::getFull(BitWidth);
5848 
5849   APInt NewLower =
5850       Descending ? std::move(MovedBoundary) : std::move(StartLower);
5851   APInt NewUpper =
5852       Descending ? std::move(StartUpper) : std::move(MovedBoundary);
5853   NewUpper += 1;
5854 
5855   // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
5856   return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper));
5857 }
5858 
5859 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
5860                                                    const SCEV *Step,
5861                                                    const SCEV *MaxBECount,
5862                                                    unsigned BitWidth) {
5863   assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&
5864          getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
5865          "Precondition!");
5866 
5867   MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType());
5868   APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount);
5869 
5870   // First, consider step signed.
5871   ConstantRange StartSRange = getSignedRange(Start);
5872   ConstantRange StepSRange = getSignedRange(Step);
5873 
5874   // If Step can be both positive and negative, we need to find ranges for the
5875   // maximum absolute step values in both directions and union them.
5876   ConstantRange SR =
5877       getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange,
5878                                 MaxBECountValue, BitWidth, /* Signed = */ true);
5879   SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(),
5880                                               StartSRange, MaxBECountValue,
5881                                               BitWidth, /* Signed = */ true));
5882 
5883   // Next, consider step unsigned.
5884   ConstantRange UR = getRangeForAffineARHelper(
5885       getUnsignedRangeMax(Step), getUnsignedRange(Start),
5886       MaxBECountValue, BitWidth, /* Signed = */ false);
5887 
5888   // Finally, intersect signed and unsigned ranges.
5889   return SR.intersectWith(UR, ConstantRange::Smallest);
5890 }
5891 
5892 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
5893                                                     const SCEV *Step,
5894                                                     const SCEV *MaxBECount,
5895                                                     unsigned BitWidth) {
5896   //    RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
5897   // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
5898 
5899   struct SelectPattern {
5900     Value *Condition = nullptr;
5901     APInt TrueValue;
5902     APInt FalseValue;
5903 
5904     explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
5905                            const SCEV *S) {
5906       Optional<unsigned> CastOp;
5907       APInt Offset(BitWidth, 0);
5908 
5909       assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&
5910              "Should be!");
5911 
5912       // Peel off a constant offset:
5913       if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
5914         // In the future we could consider being smarter here and handle
5915         // {Start+Step,+,Step} too.
5916         if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
5917           return;
5918 
5919         Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
5920         S = SA->getOperand(1);
5921       }
5922 
5923       // Peel off a cast operation
5924       if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) {
5925         CastOp = SCast->getSCEVType();
5926         S = SCast->getOperand();
5927       }
5928 
5929       using namespace llvm::PatternMatch;
5930 
5931       auto *SU = dyn_cast<SCEVUnknown>(S);
5932       const APInt *TrueVal, *FalseVal;
5933       if (!SU ||
5934           !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
5935                                           m_APInt(FalseVal)))) {
5936         Condition = nullptr;
5937         return;
5938       }
5939 
5940       TrueValue = *TrueVal;
5941       FalseValue = *FalseVal;
5942 
5943       // Re-apply the cast we peeled off earlier
5944       if (CastOp.hasValue())
5945         switch (*CastOp) {
5946         default:
5947           llvm_unreachable("Unknown SCEV cast type!");
5948 
5949         case scTruncate:
5950           TrueValue = TrueValue.trunc(BitWidth);
5951           FalseValue = FalseValue.trunc(BitWidth);
5952           break;
5953         case scZeroExtend:
5954           TrueValue = TrueValue.zext(BitWidth);
5955           FalseValue = FalseValue.zext(BitWidth);
5956           break;
5957         case scSignExtend:
5958           TrueValue = TrueValue.sext(BitWidth);
5959           FalseValue = FalseValue.sext(BitWidth);
5960           break;
5961         }
5962 
5963       // Re-apply the constant offset we peeled off earlier
5964       TrueValue += Offset;
5965       FalseValue += Offset;
5966     }
5967 
5968     bool isRecognized() { return Condition != nullptr; }
5969   };
5970 
5971   SelectPattern StartPattern(*this, BitWidth, Start);
5972   if (!StartPattern.isRecognized())
5973     return ConstantRange::getFull(BitWidth);
5974 
5975   SelectPattern StepPattern(*this, BitWidth, Step);
5976   if (!StepPattern.isRecognized())
5977     return ConstantRange::getFull(BitWidth);
5978 
5979   if (StartPattern.Condition != StepPattern.Condition) {
5980     // We don't handle this case today; but we could, by considering four
5981     // possibilities below instead of two. I'm not sure if there are cases where
5982     // that will help over what getRange already does, though.
5983     return ConstantRange::getFull(BitWidth);
5984   }
5985 
5986   // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
5987   // construct arbitrary general SCEV expressions here.  This function is called
5988   // from deep in the call stack, and calling getSCEV (on a sext instruction,
5989   // say) can end up caching a suboptimal value.
5990 
5991   // FIXME: without the explicit `this` receiver below, MSVC errors out with
5992   // C2352 and C2512 (otherwise it isn't needed).
5993 
5994   const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
5995   const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
5996   const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
5997   const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
5998 
5999   ConstantRange TrueRange =
6000       this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
6001   ConstantRange FalseRange =
6002       this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
6003 
6004   return TrueRange.unionWith(FalseRange);
6005 }
6006 
6007 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
6008   if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
6009   const BinaryOperator *BinOp = cast<BinaryOperator>(V);
6010 
6011   // Return early if there are no flags to propagate to the SCEV.
6012   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
6013   if (BinOp->hasNoUnsignedWrap())
6014     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
6015   if (BinOp->hasNoSignedWrap())
6016     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
6017   if (Flags == SCEV::FlagAnyWrap)
6018     return SCEV::FlagAnyWrap;
6019 
6020   return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
6021 }
6022 
6023 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
6024   // Here we check that I is in the header of the innermost loop containing I,
6025   // since we only deal with instructions in the loop header. The actual loop we
6026   // need to check later will come from an add recurrence, but getting that
6027   // requires computing the SCEV of the operands, which can be expensive. This
6028   // check we can do cheaply to rule out some cases early.
6029   Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent());
6030   if (InnermostContainingLoop == nullptr ||
6031       InnermostContainingLoop->getHeader() != I->getParent())
6032     return false;
6033 
6034   // Only proceed if we can prove that I does not yield poison.
6035   if (!programUndefinedIfFullPoison(I))
6036     return false;
6037 
6038   // At this point we know that if I is executed, then it does not wrap
6039   // according to at least one of NSW or NUW. If I is not executed, then we do
6040   // not know if the calculation that I represents would wrap. Multiple
6041   // instructions can map to the same SCEV. If we apply NSW or NUW from I to
6042   // the SCEV, we must guarantee no wrapping for that SCEV also when it is
6043   // derived from other instructions that map to the same SCEV. We cannot make
6044   // that guarantee for cases where I is not executed. So we need to find the
6045   // loop that I is considered in relation to and prove that I is executed for
6046   // every iteration of that loop. That implies that the value that I
6047   // calculates does not wrap anywhere in the loop, so then we can apply the
6048   // flags to the SCEV.
6049   //
6050   // We check isLoopInvariant to disambiguate in case we are adding recurrences
6051   // from different loops, so that we know which loop to prove that I is
6052   // executed in.
6053   for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) {
6054     // I could be an extractvalue from a call to an overflow intrinsic.
6055     // TODO: We can do better here in some cases.
6056     if (!isSCEVable(I->getOperand(OpIndex)->getType()))
6057       return false;
6058     const SCEV *Op = getSCEV(I->getOperand(OpIndex));
6059     if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
6060       bool AllOtherOpsLoopInvariant = true;
6061       for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands();
6062            ++OtherOpIndex) {
6063         if (OtherOpIndex != OpIndex) {
6064           const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex));
6065           if (!isLoopInvariant(OtherOp, AddRec->getLoop())) {
6066             AllOtherOpsLoopInvariant = false;
6067             break;
6068           }
6069         }
6070       }
6071       if (AllOtherOpsLoopInvariant &&
6072           isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop()))
6073         return true;
6074     }
6075   }
6076   return false;
6077 }
6078 
6079 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
6080   // If we know that \c I can never be poison period, then that's enough.
6081   if (isSCEVExprNeverPoison(I))
6082     return true;
6083 
6084   // For an add recurrence specifically, we assume that infinite loops without
6085   // side effects are undefined behavior, and then reason as follows:
6086   //
6087   // If the add recurrence is poison in any iteration, it is poison on all
6088   // future iterations (since incrementing poison yields poison). If the result
6089   // of the add recurrence is fed into the loop latch condition and the loop
6090   // does not contain any throws or exiting blocks other than the latch, we now
6091   // have the ability to "choose" whether the backedge is taken or not (by
6092   // choosing a sufficiently evil value for the poison feeding into the branch)
6093   // for every iteration including and after the one in which \p I first became
6094   // poison.  There are two possibilities (let's call the iteration in which \p
6095   // I first became poison as K):
6096   //
6097   //  1. In the set of iterations including and after K, the loop body executes
6098   //     no side effects.  In this case executing the backege an infinte number
6099   //     of times will yield undefined behavior.
6100   //
6101   //  2. In the set of iterations including and after K, the loop body executes
6102   //     at least one side effect.  In this case, that specific instance of side
6103   //     effect is control dependent on poison, which also yields undefined
6104   //     behavior.
6105 
6106   auto *ExitingBB = L->getExitingBlock();
6107   auto *LatchBB = L->getLoopLatch();
6108   if (!ExitingBB || !LatchBB || ExitingBB != LatchBB)
6109     return false;
6110 
6111   SmallPtrSet<const Instruction *, 16> Pushed;
6112   SmallVector<const Instruction *, 8> PoisonStack;
6113 
6114   // We start by assuming \c I, the post-inc add recurrence, is poison.  Only
6115   // things that are known to be fully poison under that assumption go on the
6116   // PoisonStack.
6117   Pushed.insert(I);
6118   PoisonStack.push_back(I);
6119 
6120   bool LatchControlDependentOnPoison = false;
6121   while (!PoisonStack.empty() && !LatchControlDependentOnPoison) {
6122     const Instruction *Poison = PoisonStack.pop_back_val();
6123 
6124     for (auto *PoisonUser : Poison->users()) {
6125       if (propagatesFullPoison(cast<Instruction>(PoisonUser))) {
6126         if (Pushed.insert(cast<Instruction>(PoisonUser)).second)
6127           PoisonStack.push_back(cast<Instruction>(PoisonUser));
6128       } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) {
6129         assert(BI->isConditional() && "Only possibility!");
6130         if (BI->getParent() == LatchBB) {
6131           LatchControlDependentOnPoison = true;
6132           break;
6133         }
6134       }
6135     }
6136   }
6137 
6138   return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L);
6139 }
6140 
6141 ScalarEvolution::LoopProperties
6142 ScalarEvolution::getLoopProperties(const Loop *L) {
6143   using LoopProperties = ScalarEvolution::LoopProperties;
6144 
6145   auto Itr = LoopPropertiesCache.find(L);
6146   if (Itr == LoopPropertiesCache.end()) {
6147     auto HasSideEffects = [](Instruction *I) {
6148       if (auto *SI = dyn_cast<StoreInst>(I))
6149         return !SI->isSimple();
6150 
6151       return I->mayHaveSideEffects();
6152     };
6153 
6154     LoopProperties LP = {/* HasNoAbnormalExits */ true,
6155                          /*HasNoSideEffects*/ true};
6156 
6157     for (auto *BB : L->getBlocks())
6158       for (auto &I : *BB) {
6159         if (!isGuaranteedToTransferExecutionToSuccessor(&I))
6160           LP.HasNoAbnormalExits = false;
6161         if (HasSideEffects(&I))
6162           LP.HasNoSideEffects = false;
6163         if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
6164           break; // We're already as pessimistic as we can get.
6165       }
6166 
6167     auto InsertPair = LoopPropertiesCache.insert({L, LP});
6168     assert(InsertPair.second && "We just checked!");
6169     Itr = InsertPair.first;
6170   }
6171 
6172   return Itr->second;
6173 }
6174 
6175 const SCEV *ScalarEvolution::createSCEV(Value *V) {
6176   if (!isSCEVable(V->getType()))
6177     return getUnknown(V);
6178 
6179   if (Instruction *I = dyn_cast<Instruction>(V)) {
6180     // Don't attempt to analyze instructions in blocks that aren't
6181     // reachable. Such instructions don't matter, and they aren't required
6182     // to obey basic rules for definitions dominating uses which this
6183     // analysis depends on.
6184     if (!DT.isReachableFromEntry(I->getParent()))
6185       return getUnknown(UndefValue::get(V->getType()));
6186   } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
6187     return getConstant(CI);
6188   else if (isa<ConstantPointerNull>(V))
6189     return getZero(V->getType());
6190   else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
6191     return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee());
6192   else if (!isa<ConstantExpr>(V))
6193     return getUnknown(V);
6194 
6195   Operator *U = cast<Operator>(V);
6196   if (auto BO = MatchBinaryOp(U, DT)) {
6197     switch (BO->Opcode) {
6198     case Instruction::Add: {
6199       // The simple thing to do would be to just call getSCEV on both operands
6200       // and call getAddExpr with the result. However if we're looking at a
6201       // bunch of things all added together, this can be quite inefficient,
6202       // because it leads to N-1 getAddExpr calls for N ultimate operands.
6203       // Instead, gather up all the operands and make a single getAddExpr call.
6204       // LLVM IR canonical form means we need only traverse the left operands.
6205       SmallVector<const SCEV *, 4> AddOps;
6206       do {
6207         if (BO->Op) {
6208           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
6209             AddOps.push_back(OpSCEV);
6210             break;
6211           }
6212 
6213           // If a NUW or NSW flag can be applied to the SCEV for this
6214           // addition, then compute the SCEV for this addition by itself
6215           // with a separate call to getAddExpr. We need to do that
6216           // instead of pushing the operands of the addition onto AddOps,
6217           // since the flags are only known to apply to this particular
6218           // addition - they may not apply to other additions that can be
6219           // formed with operands from AddOps.
6220           const SCEV *RHS = getSCEV(BO->RHS);
6221           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
6222           if (Flags != SCEV::FlagAnyWrap) {
6223             const SCEV *LHS = getSCEV(BO->LHS);
6224             if (BO->Opcode == Instruction::Sub)
6225               AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
6226             else
6227               AddOps.push_back(getAddExpr(LHS, RHS, Flags));
6228             break;
6229           }
6230         }
6231 
6232         if (BO->Opcode == Instruction::Sub)
6233           AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
6234         else
6235           AddOps.push_back(getSCEV(BO->RHS));
6236 
6237         auto NewBO = MatchBinaryOp(BO->LHS, DT);
6238         if (!NewBO || (NewBO->Opcode != Instruction::Add &&
6239                        NewBO->Opcode != Instruction::Sub)) {
6240           AddOps.push_back(getSCEV(BO->LHS));
6241           break;
6242         }
6243         BO = NewBO;
6244       } while (true);
6245 
6246       return getAddExpr(AddOps);
6247     }
6248 
6249     case Instruction::Mul: {
6250       SmallVector<const SCEV *, 4> MulOps;
6251       do {
6252         if (BO->Op) {
6253           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
6254             MulOps.push_back(OpSCEV);
6255             break;
6256           }
6257 
6258           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
6259           if (Flags != SCEV::FlagAnyWrap) {
6260             MulOps.push_back(
6261                 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags));
6262             break;
6263           }
6264         }
6265 
6266         MulOps.push_back(getSCEV(BO->RHS));
6267         auto NewBO = MatchBinaryOp(BO->LHS, DT);
6268         if (!NewBO || NewBO->Opcode != Instruction::Mul) {
6269           MulOps.push_back(getSCEV(BO->LHS));
6270           break;
6271         }
6272         BO = NewBO;
6273       } while (true);
6274 
6275       return getMulExpr(MulOps);
6276     }
6277     case Instruction::UDiv:
6278       return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
6279     case Instruction::URem:
6280       return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
6281     case Instruction::Sub: {
6282       SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
6283       if (BO->Op)
6284         Flags = getNoWrapFlagsFromUB(BO->Op);
6285       return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags);
6286     }
6287     case Instruction::And:
6288       // For an expression like x&255 that merely masks off the high bits,
6289       // use zext(trunc(x)) as the SCEV expression.
6290       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6291         if (CI->isZero())
6292           return getSCEV(BO->RHS);
6293         if (CI->isMinusOne())
6294           return getSCEV(BO->LHS);
6295         const APInt &A = CI->getValue();
6296 
6297         // Instcombine's ShrinkDemandedConstant may strip bits out of
6298         // constants, obscuring what would otherwise be a low-bits mask.
6299         // Use computeKnownBits to compute what ShrinkDemandedConstant
6300         // knew about to reconstruct a low-bits mask value.
6301         unsigned LZ = A.countLeadingZeros();
6302         unsigned TZ = A.countTrailingZeros();
6303         unsigned BitWidth = A.getBitWidth();
6304         KnownBits Known(BitWidth);
6305         computeKnownBits(BO->LHS, Known, getDataLayout(),
6306                          0, &AC, nullptr, &DT);
6307 
6308         APInt EffectiveMask =
6309             APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
6310         if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
6311           const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
6312           const SCEV *LHS = getSCEV(BO->LHS);
6313           const SCEV *ShiftedLHS = nullptr;
6314           if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
6315             if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
6316               // For an expression like (x * 8) & 8, simplify the multiply.
6317               unsigned MulZeros = OpC->getAPInt().countTrailingZeros();
6318               unsigned GCD = std::min(MulZeros, TZ);
6319               APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
6320               SmallVector<const SCEV*, 4> MulOps;
6321               MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD)));
6322               MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end());
6323               auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
6324               ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
6325             }
6326           }
6327           if (!ShiftedLHS)
6328             ShiftedLHS = getUDivExpr(LHS, MulCount);
6329           return getMulExpr(
6330               getZeroExtendExpr(
6331                   getTruncateExpr(ShiftedLHS,
6332                       IntegerType::get(getContext(), BitWidth - LZ - TZ)),
6333                   BO->LHS->getType()),
6334               MulCount);
6335         }
6336       }
6337       break;
6338 
6339     case Instruction::Or:
6340       // If the RHS of the Or is a constant, we may have something like:
6341       // X*4+1 which got turned into X*4|1.  Handle this as an Add so loop
6342       // optimizations will transparently handle this case.
6343       //
6344       // In order for this transformation to be safe, the LHS must be of the
6345       // form X*(2^n) and the Or constant must be less than 2^n.
6346       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6347         const SCEV *LHS = getSCEV(BO->LHS);
6348         const APInt &CIVal = CI->getValue();
6349         if (GetMinTrailingZeros(LHS) >=
6350             (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
6351           // Build a plain add SCEV.
6352           const SCEV *S = getAddExpr(LHS, getSCEV(CI));
6353           // If the LHS of the add was an addrec and it has no-wrap flags,
6354           // transfer the no-wrap flags, since an or won't introduce a wrap.
6355           if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
6356             const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
6357             const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags(
6358                 OldAR->getNoWrapFlags());
6359           }
6360           return S;
6361         }
6362       }
6363       break;
6364 
6365     case Instruction::Xor:
6366       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6367         // If the RHS of xor is -1, then this is a not operation.
6368         if (CI->isMinusOne())
6369           return getNotSCEV(getSCEV(BO->LHS));
6370 
6371         // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
6372         // This is a variant of the check for xor with -1, and it handles
6373         // the case where instcombine has trimmed non-demanded bits out
6374         // of an xor with -1.
6375         if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
6376           if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
6377             if (LBO->getOpcode() == Instruction::And &&
6378                 LCI->getValue() == CI->getValue())
6379               if (const SCEVZeroExtendExpr *Z =
6380                       dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
6381                 Type *UTy = BO->LHS->getType();
6382                 const SCEV *Z0 = Z->getOperand();
6383                 Type *Z0Ty = Z0->getType();
6384                 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
6385 
6386                 // If C is a low-bits mask, the zero extend is serving to
6387                 // mask off the high bits. Complement the operand and
6388                 // re-apply the zext.
6389                 if (CI->getValue().isMask(Z0TySize))
6390                   return getZeroExtendExpr(getNotSCEV(Z0), UTy);
6391 
6392                 // If C is a single bit, it may be in the sign-bit position
6393                 // before the zero-extend. In this case, represent the xor
6394                 // using an add, which is equivalent, and re-apply the zext.
6395                 APInt Trunc = CI->getValue().trunc(Z0TySize);
6396                 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
6397                     Trunc.isSignMask())
6398                   return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
6399                                            UTy);
6400               }
6401       }
6402       break;
6403 
6404     case Instruction::Shl:
6405       // Turn shift left of a constant amount into a multiply.
6406       if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
6407         uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
6408 
6409         // If the shift count is not less than the bitwidth, the result of
6410         // the shift is undefined. Don't try to analyze it, because the
6411         // resolution chosen here may differ from the resolution chosen in
6412         // other parts of the compiler.
6413         if (SA->getValue().uge(BitWidth))
6414           break;
6415 
6416         // It is currently not resolved how to interpret NSW for left
6417         // shift by BitWidth - 1, so we avoid applying flags in that
6418         // case. Remove this check (or this comment) once the situation
6419         // is resolved. See
6420         // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html
6421         // and http://reviews.llvm.org/D8890 .
6422         auto Flags = SCEV::FlagAnyWrap;
6423         if (BO->Op && SA->getValue().ult(BitWidth - 1))
6424           Flags = getNoWrapFlagsFromUB(BO->Op);
6425 
6426         Constant *X = ConstantInt::get(
6427             getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
6428         return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags);
6429       }
6430       break;
6431 
6432     case Instruction::AShr: {
6433       // AShr X, C, where C is a constant.
6434       ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
6435       if (!CI)
6436         break;
6437 
6438       Type *OuterTy = BO->LHS->getType();
6439       uint64_t BitWidth = getTypeSizeInBits(OuterTy);
6440       // If the shift count is not less than the bitwidth, the result of
6441       // the shift is undefined. Don't try to analyze it, because the
6442       // resolution chosen here may differ from the resolution chosen in
6443       // other parts of the compiler.
6444       if (CI->getValue().uge(BitWidth))
6445         break;
6446 
6447       if (CI->isZero())
6448         return getSCEV(BO->LHS); // shift by zero --> noop
6449 
6450       uint64_t AShrAmt = CI->getZExtValue();
6451       Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
6452 
6453       Operator *L = dyn_cast<Operator>(BO->LHS);
6454       if (L && L->getOpcode() == Instruction::Shl) {
6455         // X = Shl A, n
6456         // Y = AShr X, m
6457         // Both n and m are constant.
6458 
6459         const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
6460         if (L->getOperand(1) == BO->RHS)
6461           // For a two-shift sext-inreg, i.e. n = m,
6462           // use sext(trunc(x)) as the SCEV expression.
6463           return getSignExtendExpr(
6464               getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy);
6465 
6466         ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
6467         if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) {
6468           uint64_t ShlAmt = ShlAmtCI->getZExtValue();
6469           if (ShlAmt > AShrAmt) {
6470             // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
6471             // expression. We already checked that ShlAmt < BitWidth, so
6472             // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
6473             // ShlAmt - AShrAmt < Amt.
6474             APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
6475                                             ShlAmt - AShrAmt);
6476             return getSignExtendExpr(
6477                 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy),
6478                 getConstant(Mul)), OuterTy);
6479           }
6480         }
6481       }
6482       break;
6483     }
6484     }
6485   }
6486 
6487   switch (U->getOpcode()) {
6488   case Instruction::Trunc:
6489     return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
6490 
6491   case Instruction::ZExt:
6492     return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
6493 
6494   case Instruction::SExt:
6495     if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) {
6496       // The NSW flag of a subtract does not always survive the conversion to
6497       // A + (-1)*B.  By pushing sign extension onto its operands we are much
6498       // more likely to preserve NSW and allow later AddRec optimisations.
6499       //
6500       // NOTE: This is effectively duplicating this logic from getSignExtend:
6501       //   sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
6502       // but by that point the NSW information has potentially been lost.
6503       if (BO->Opcode == Instruction::Sub && BO->IsNSW) {
6504         Type *Ty = U->getType();
6505         auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty);
6506         auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty);
6507         return getMinusSCEV(V1, V2, SCEV::FlagNSW);
6508       }
6509     }
6510     return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
6511 
6512   case Instruction::BitCast:
6513     // BitCasts are no-op casts so we just eliminate the cast.
6514     if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
6515       return getSCEV(U->getOperand(0));
6516     break;
6517 
6518   // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
6519   // lead to pointer expressions which cannot safely be expanded to GEPs,
6520   // because ScalarEvolution doesn't respect the GEP aliasing rules when
6521   // simplifying integer expressions.
6522 
6523   case Instruction::GetElementPtr:
6524     return createNodeForGEP(cast<GEPOperator>(U));
6525 
6526   case Instruction::PHI:
6527     return createNodeForPHI(cast<PHINode>(U));
6528 
6529   case Instruction::Select:
6530     // U can also be a select constant expr, which let fall through.  Since
6531     // createNodeForSelect only works for a condition that is an `ICmpInst`, and
6532     // constant expressions cannot have instructions as operands, we'd have
6533     // returned getUnknown for a select constant expressions anyway.
6534     if (isa<Instruction>(U))
6535       return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0),
6536                                       U->getOperand(1), U->getOperand(2));
6537     break;
6538 
6539   case Instruction::Call:
6540   case Instruction::Invoke:
6541     if (Value *RV = CallSite(U).getReturnedArgOperand())
6542       return getSCEV(RV);
6543     break;
6544   }
6545 
6546   return getUnknown(V);
6547 }
6548 
6549 //===----------------------------------------------------------------------===//
6550 //                   Iteration Count Computation Code
6551 //
6552 
6553 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
6554   if (!ExitCount)
6555     return 0;
6556 
6557   ConstantInt *ExitConst = ExitCount->getValue();
6558 
6559   // Guard against huge trip counts.
6560   if (ExitConst->getValue().getActiveBits() > 32)
6561     return 0;
6562 
6563   // In case of integer overflow, this returns 0, which is correct.
6564   return ((unsigned)ExitConst->getZExtValue()) + 1;
6565 }
6566 
6567 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) {
6568   if (BasicBlock *ExitingBB = L->getExitingBlock())
6569     return getSmallConstantTripCount(L, ExitingBB);
6570 
6571   // No trip count information for multiple exits.
6572   return 0;
6573 }
6574 
6575 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L,
6576                                                     BasicBlock *ExitingBlock) {
6577   assert(ExitingBlock && "Must pass a non-null exiting block!");
6578   assert(L->isLoopExiting(ExitingBlock) &&
6579          "Exiting block must actually branch out of the loop!");
6580   const SCEVConstant *ExitCount =
6581       dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
6582   return getConstantTripCount(ExitCount);
6583 }
6584 
6585 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) {
6586   const auto *MaxExitCount =
6587       dyn_cast<SCEVConstant>(getConstantMaxBackedgeTakenCount(L));
6588   return getConstantTripCount(MaxExitCount);
6589 }
6590 
6591 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) {
6592   if (BasicBlock *ExitingBB = L->getExitingBlock())
6593     return getSmallConstantTripMultiple(L, ExitingBB);
6594 
6595   // No trip multiple information for multiple exits.
6596   return 0;
6597 }
6598 
6599 /// Returns the largest constant divisor of the trip count of this loop as a
6600 /// normal unsigned value, if possible. This means that the actual trip count is
6601 /// always a multiple of the returned value (don't forget the trip count could
6602 /// very well be zero as well!).
6603 ///
6604 /// Returns 1 if the trip count is unknown or not guaranteed to be the
6605 /// multiple of a constant (which is also the case if the trip count is simply
6606 /// constant, use getSmallConstantTripCount for that case), Will also return 1
6607 /// if the trip count is very large (>= 2^32).
6608 ///
6609 /// As explained in the comments for getSmallConstantTripCount, this assumes
6610 /// that control exits the loop via ExitingBlock.
6611 unsigned
6612 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
6613                                               BasicBlock *ExitingBlock) {
6614   assert(ExitingBlock && "Must pass a non-null exiting block!");
6615   assert(L->isLoopExiting(ExitingBlock) &&
6616          "Exiting block must actually branch out of the loop!");
6617   const SCEV *ExitCount = getExitCount(L, ExitingBlock);
6618   if (ExitCount == getCouldNotCompute())
6619     return 1;
6620 
6621   // Get the trip count from the BE count by adding 1.
6622   const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType()));
6623 
6624   const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr);
6625   if (!TC)
6626     // Attempt to factor more general cases. Returns the greatest power of
6627     // two divisor. If overflow happens, the trip count expression is still
6628     // divisible by the greatest power of 2 divisor returned.
6629     return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr));
6630 
6631   ConstantInt *Result = TC->getValue();
6632 
6633   // Guard against huge trip counts (this requires checking
6634   // for zero to handle the case where the trip count == -1 and the
6635   // addition wraps).
6636   if (!Result || Result->getValue().getActiveBits() > 32 ||
6637       Result->getValue().getActiveBits() == 0)
6638     return 1;
6639 
6640   return (unsigned)Result->getZExtValue();
6641 }
6642 
6643 const SCEV *ScalarEvolution::getExitCount(const Loop *L,
6644                                           BasicBlock *ExitingBlock,
6645                                           ExitCountKind Kind) {
6646   switch (Kind) {
6647   case Exact:
6648     return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
6649   case ConstantMaximum:
6650     return getBackedgeTakenInfo(L).getMax(ExitingBlock, this);
6651   };
6652   llvm_unreachable("Invalid ExitCountKind!");
6653 }
6654 
6655 const SCEV *
6656 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
6657                                                  SCEVUnionPredicate &Preds) {
6658   return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds);
6659 }
6660 
6661 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L,
6662                                                    ExitCountKind Kind) {
6663   switch (Kind) {
6664   case Exact:
6665     return getBackedgeTakenInfo(L).getExact(L, this);
6666   case ConstantMaximum:
6667     return getBackedgeTakenInfo(L).getMax(this);
6668   };
6669   llvm_unreachable("Invalid ExitCountKind!");
6670 }
6671 
6672 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) {
6673   return getBackedgeTakenInfo(L).isMaxOrZero(this);
6674 }
6675 
6676 /// Push PHI nodes in the header of the given loop onto the given Worklist.
6677 static void
6678 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
6679   BasicBlock *Header = L->getHeader();
6680 
6681   // Push all Loop-header PHIs onto the Worklist stack.
6682   for (PHINode &PN : Header->phis())
6683     Worklist.push_back(&PN);
6684 }
6685 
6686 const ScalarEvolution::BackedgeTakenInfo &
6687 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
6688   auto &BTI = getBackedgeTakenInfo(L);
6689   if (BTI.hasFullInfo())
6690     return BTI;
6691 
6692   auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
6693 
6694   if (!Pair.second)
6695     return Pair.first->second;
6696 
6697   BackedgeTakenInfo Result =
6698       computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
6699 
6700   return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
6701 }
6702 
6703 const ScalarEvolution::BackedgeTakenInfo &
6704 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
6705   // Initially insert an invalid entry for this loop. If the insertion
6706   // succeeds, proceed to actually compute a backedge-taken count and
6707   // update the value. The temporary CouldNotCompute value tells SCEV
6708   // code elsewhere that it shouldn't attempt to request a new
6709   // backedge-taken count, which could result in infinite recursion.
6710   std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
6711       BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
6712   if (!Pair.second)
6713     return Pair.first->second;
6714 
6715   // computeBackedgeTakenCount may allocate memory for its result. Inserting it
6716   // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
6717   // must be cleared in this scope.
6718   BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
6719 
6720   // In product build, there are no usage of statistic.
6721   (void)NumTripCountsComputed;
6722   (void)NumTripCountsNotComputed;
6723 #if LLVM_ENABLE_STATS || !defined(NDEBUG)
6724   const SCEV *BEExact = Result.getExact(L, this);
6725   if (BEExact != getCouldNotCompute()) {
6726     assert(isLoopInvariant(BEExact, L) &&
6727            isLoopInvariant(Result.getMax(this), L) &&
6728            "Computed backedge-taken count isn't loop invariant for loop!");
6729     ++NumTripCountsComputed;
6730   }
6731   else if (Result.getMax(this) == getCouldNotCompute() &&
6732            isa<PHINode>(L->getHeader()->begin())) {
6733     // Only count loops that have phi nodes as not being computable.
6734     ++NumTripCountsNotComputed;
6735   }
6736 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG)
6737 
6738   // Now that we know more about the trip count for this loop, forget any
6739   // existing SCEV values for PHI nodes in this loop since they are only
6740   // conservative estimates made without the benefit of trip count
6741   // information. This is similar to the code in forgetLoop, except that
6742   // it handles SCEVUnknown PHI nodes specially.
6743   if (Result.hasAnyInfo()) {
6744     SmallVector<Instruction *, 16> Worklist;
6745     PushLoopPHIs(L, Worklist);
6746 
6747     SmallPtrSet<Instruction *, 8> Discovered;
6748     while (!Worklist.empty()) {
6749       Instruction *I = Worklist.pop_back_val();
6750 
6751       ValueExprMapType::iterator It =
6752         ValueExprMap.find_as(static_cast<Value *>(I));
6753       if (It != ValueExprMap.end()) {
6754         const SCEV *Old = It->second;
6755 
6756         // SCEVUnknown for a PHI either means that it has an unrecognized
6757         // structure, or it's a PHI that's in the progress of being computed
6758         // by createNodeForPHI.  In the former case, additional loop trip
6759         // count information isn't going to change anything. In the later
6760         // case, createNodeForPHI will perform the necessary updates on its
6761         // own when it gets to that point.
6762         if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
6763           eraseValueFromMap(It->first);
6764           forgetMemoizedResults(Old);
6765         }
6766         if (PHINode *PN = dyn_cast<PHINode>(I))
6767           ConstantEvolutionLoopExitValue.erase(PN);
6768       }
6769 
6770       // Since we don't need to invalidate anything for correctness and we're
6771       // only invalidating to make SCEV's results more precise, we get to stop
6772       // early to avoid invalidating too much.  This is especially important in
6773       // cases like:
6774       //
6775       //   %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node
6776       // loop0:
6777       //   %pn0 = phi
6778       //   ...
6779       // loop1:
6780       //   %pn1 = phi
6781       //   ...
6782       //
6783       // where both loop0 and loop1's backedge taken count uses the SCEV
6784       // expression for %v.  If we don't have the early stop below then in cases
6785       // like the above, getBackedgeTakenInfo(loop1) will clear out the trip
6786       // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip
6787       // count for loop1, effectively nullifying SCEV's trip count cache.
6788       for (auto *U : I->users())
6789         if (auto *I = dyn_cast<Instruction>(U)) {
6790           auto *LoopForUser = LI.getLoopFor(I->getParent());
6791           if (LoopForUser && L->contains(LoopForUser) &&
6792               Discovered.insert(I).second)
6793             Worklist.push_back(I);
6794         }
6795     }
6796   }
6797 
6798   // Re-lookup the insert position, since the call to
6799   // computeBackedgeTakenCount above could result in a
6800   // recusive call to getBackedgeTakenInfo (on a different
6801   // loop), which would invalidate the iterator computed
6802   // earlier.
6803   return BackedgeTakenCounts.find(L)->second = std::move(Result);
6804 }
6805 
6806 void ScalarEvolution::forgetAllLoops() {
6807   // This method is intended to forget all info about loops. It should
6808   // invalidate caches as if the following happened:
6809   // - The trip counts of all loops have changed arbitrarily
6810   // - Every llvm::Value has been updated in place to produce a different
6811   // result.
6812   BackedgeTakenCounts.clear();
6813   PredicatedBackedgeTakenCounts.clear();
6814   LoopPropertiesCache.clear();
6815   ConstantEvolutionLoopExitValue.clear();
6816   ValueExprMap.clear();
6817   ValuesAtScopes.clear();
6818   LoopDispositions.clear();
6819   BlockDispositions.clear();
6820   UnsignedRanges.clear();
6821   SignedRanges.clear();
6822   ExprValueMap.clear();
6823   HasRecMap.clear();
6824   MinTrailingZerosCache.clear();
6825   PredicatedSCEVRewrites.clear();
6826 }
6827 
6828 void ScalarEvolution::forgetLoop(const Loop *L) {
6829   // Drop any stored trip count value.
6830   auto RemoveLoopFromBackedgeMap =
6831       [](DenseMap<const Loop *, BackedgeTakenInfo> &Map, const Loop *L) {
6832         auto BTCPos = Map.find(L);
6833         if (BTCPos != Map.end()) {
6834           BTCPos->second.clear();
6835           Map.erase(BTCPos);
6836         }
6837       };
6838 
6839   SmallVector<const Loop *, 16> LoopWorklist(1, L);
6840   SmallVector<Instruction *, 32> Worklist;
6841   SmallPtrSet<Instruction *, 16> Visited;
6842 
6843   // Iterate over all the loops and sub-loops to drop SCEV information.
6844   while (!LoopWorklist.empty()) {
6845     auto *CurrL = LoopWorklist.pop_back_val();
6846 
6847     RemoveLoopFromBackedgeMap(BackedgeTakenCounts, CurrL);
6848     RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts, CurrL);
6849 
6850     // Drop information about predicated SCEV rewrites for this loop.
6851     for (auto I = PredicatedSCEVRewrites.begin();
6852          I != PredicatedSCEVRewrites.end();) {
6853       std::pair<const SCEV *, const Loop *> Entry = I->first;
6854       if (Entry.second == CurrL)
6855         PredicatedSCEVRewrites.erase(I++);
6856       else
6857         ++I;
6858     }
6859 
6860     auto LoopUsersItr = LoopUsers.find(CurrL);
6861     if (LoopUsersItr != LoopUsers.end()) {
6862       for (auto *S : LoopUsersItr->second)
6863         forgetMemoizedResults(S);
6864       LoopUsers.erase(LoopUsersItr);
6865     }
6866 
6867     // Drop information about expressions based on loop-header PHIs.
6868     PushLoopPHIs(CurrL, Worklist);
6869 
6870     while (!Worklist.empty()) {
6871       Instruction *I = Worklist.pop_back_val();
6872       if (!Visited.insert(I).second)
6873         continue;
6874 
6875       ValueExprMapType::iterator It =
6876           ValueExprMap.find_as(static_cast<Value *>(I));
6877       if (It != ValueExprMap.end()) {
6878         eraseValueFromMap(It->first);
6879         forgetMemoizedResults(It->second);
6880         if (PHINode *PN = dyn_cast<PHINode>(I))
6881           ConstantEvolutionLoopExitValue.erase(PN);
6882       }
6883 
6884       PushDefUseChildren(I, Worklist);
6885     }
6886 
6887     LoopPropertiesCache.erase(CurrL);
6888     // Forget all contained loops too, to avoid dangling entries in the
6889     // ValuesAtScopes map.
6890     LoopWorklist.append(CurrL->begin(), CurrL->end());
6891   }
6892 }
6893 
6894 void ScalarEvolution::forgetTopmostLoop(const Loop *L) {
6895   while (Loop *Parent = L->getParentLoop())
6896     L = Parent;
6897   forgetLoop(L);
6898 }
6899 
6900 void ScalarEvolution::forgetValue(Value *V) {
6901   Instruction *I = dyn_cast<Instruction>(V);
6902   if (!I) return;
6903 
6904   // Drop information about expressions based on loop-header PHIs.
6905   SmallVector<Instruction *, 16> Worklist;
6906   Worklist.push_back(I);
6907 
6908   SmallPtrSet<Instruction *, 8> Visited;
6909   while (!Worklist.empty()) {
6910     I = Worklist.pop_back_val();
6911     if (!Visited.insert(I).second)
6912       continue;
6913 
6914     ValueExprMapType::iterator It =
6915       ValueExprMap.find_as(static_cast<Value *>(I));
6916     if (It != ValueExprMap.end()) {
6917       eraseValueFromMap(It->first);
6918       forgetMemoizedResults(It->second);
6919       if (PHINode *PN = dyn_cast<PHINode>(I))
6920         ConstantEvolutionLoopExitValue.erase(PN);
6921     }
6922 
6923     PushDefUseChildren(I, Worklist);
6924   }
6925 }
6926 
6927 /// Get the exact loop backedge taken count considering all loop exits. A
6928 /// computable result can only be returned for loops with all exiting blocks
6929 /// dominating the latch. howFarToZero assumes that the limit of each loop test
6930 /// is never skipped. This is a valid assumption as long as the loop exits via
6931 /// that test. For precise results, it is the caller's responsibility to specify
6932 /// the relevant loop exiting block using getExact(ExitingBlock, SE).
6933 const SCEV *
6934 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE,
6935                                              SCEVUnionPredicate *Preds) const {
6936   // If any exits were not computable, the loop is not computable.
6937   if (!isComplete() || ExitNotTaken.empty())
6938     return SE->getCouldNotCompute();
6939 
6940   const BasicBlock *Latch = L->getLoopLatch();
6941   // All exiting blocks we have collected must dominate the only backedge.
6942   if (!Latch)
6943     return SE->getCouldNotCompute();
6944 
6945   // All exiting blocks we have gathered dominate loop's latch, so exact trip
6946   // count is simply a minimum out of all these calculated exit counts.
6947   SmallVector<const SCEV *, 2> Ops;
6948   for (auto &ENT : ExitNotTaken) {
6949     const SCEV *BECount = ENT.ExactNotTaken;
6950     assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!");
6951     assert(SE->DT.dominates(ENT.ExitingBlock, Latch) &&
6952            "We should only have known counts for exiting blocks that dominate "
6953            "latch!");
6954 
6955     Ops.push_back(BECount);
6956 
6957     if (Preds && !ENT.hasAlwaysTruePredicate())
6958       Preds->add(ENT.Predicate.get());
6959 
6960     assert((Preds || ENT.hasAlwaysTruePredicate()) &&
6961            "Predicate should be always true!");
6962   }
6963 
6964   return SE->getUMinFromMismatchedTypes(Ops);
6965 }
6966 
6967 /// Get the exact not taken count for this loop exit.
6968 const SCEV *
6969 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock,
6970                                              ScalarEvolution *SE) const {
6971   for (auto &ENT : ExitNotTaken)
6972     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
6973       return ENT.ExactNotTaken;
6974 
6975   return SE->getCouldNotCompute();
6976 }
6977 
6978 const SCEV *
6979 ScalarEvolution::BackedgeTakenInfo::getMax(BasicBlock *ExitingBlock,
6980                                            ScalarEvolution *SE) const {
6981   for (auto &ENT : ExitNotTaken)
6982     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
6983       return ENT.MaxNotTaken;
6984 
6985   return SE->getCouldNotCompute();
6986 }
6987 
6988 /// getMax - Get the max backedge taken count for the loop.
6989 const SCEV *
6990 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const {
6991   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
6992     return !ENT.hasAlwaysTruePredicate();
6993   };
6994 
6995   if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax())
6996     return SE->getCouldNotCompute();
6997 
6998   assert((isa<SCEVCouldNotCompute>(getMax()) || isa<SCEVConstant>(getMax())) &&
6999          "No point in having a non-constant max backedge taken count!");
7000   return getMax();
7001 }
7002 
7003 bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const {
7004   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
7005     return !ENT.hasAlwaysTruePredicate();
7006   };
7007   return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
7008 }
7009 
7010 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S,
7011                                                     ScalarEvolution *SE) const {
7012   if (getMax() && getMax() != SE->getCouldNotCompute() &&
7013       SE->hasOperand(getMax(), S))
7014     return true;
7015 
7016   for (auto &ENT : ExitNotTaken)
7017     if (ENT.ExactNotTaken != SE->getCouldNotCompute() &&
7018         SE->hasOperand(ENT.ExactNotTaken, S))
7019       return true;
7020 
7021   return false;
7022 }
7023 
7024 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E)
7025     : ExactNotTaken(E), MaxNotTaken(E) {
7026   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
7027           isa<SCEVConstant>(MaxNotTaken)) &&
7028          "No point in having a non-constant max backedge taken count!");
7029 }
7030 
7031 ScalarEvolution::ExitLimit::ExitLimit(
7032     const SCEV *E, const SCEV *M, bool MaxOrZero,
7033     ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList)
7034     : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) {
7035   assert((isa<SCEVCouldNotCompute>(ExactNotTaken) ||
7036           !isa<SCEVCouldNotCompute>(MaxNotTaken)) &&
7037          "Exact is not allowed to be less precise than Max");
7038   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
7039           isa<SCEVConstant>(MaxNotTaken)) &&
7040          "No point in having a non-constant max backedge taken count!");
7041   for (auto *PredSet : PredSetList)
7042     for (auto *P : *PredSet)
7043       addPredicate(P);
7044 }
7045 
7046 ScalarEvolution::ExitLimit::ExitLimit(
7047     const SCEV *E, const SCEV *M, bool MaxOrZero,
7048     const SmallPtrSetImpl<const SCEVPredicate *> &PredSet)
7049     : ExitLimit(E, M, MaxOrZero, {&PredSet}) {
7050   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
7051           isa<SCEVConstant>(MaxNotTaken)) &&
7052          "No point in having a non-constant max backedge taken count!");
7053 }
7054 
7055 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M,
7056                                       bool MaxOrZero)
7057     : ExitLimit(E, M, MaxOrZero, None) {
7058   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
7059           isa<SCEVConstant>(MaxNotTaken)) &&
7060          "No point in having a non-constant max backedge taken count!");
7061 }
7062 
7063 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
7064 /// computable exit into a persistent ExitNotTakenInfo array.
7065 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
7066     ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo>
7067         ExitCounts,
7068     bool Complete, const SCEV *MaxCount, bool MaxOrZero)
7069     : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) {
7070   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
7071 
7072   ExitNotTaken.reserve(ExitCounts.size());
7073   std::transform(
7074       ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken),
7075       [&](const EdgeExitInfo &EEI) {
7076         BasicBlock *ExitBB = EEI.first;
7077         const ExitLimit &EL = EEI.second;
7078         if (EL.Predicates.empty())
7079           return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken,
7080                                   nullptr);
7081 
7082         std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate);
7083         for (auto *Pred : EL.Predicates)
7084           Predicate->add(Pred);
7085 
7086         return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken,
7087                                 std::move(Predicate));
7088       });
7089   assert((isa<SCEVCouldNotCompute>(MaxCount) || isa<SCEVConstant>(MaxCount)) &&
7090          "No point in having a non-constant max backedge taken count!");
7091 }
7092 
7093 /// Invalidate this result and free the ExitNotTakenInfo array.
7094 void ScalarEvolution::BackedgeTakenInfo::clear() {
7095   ExitNotTaken.clear();
7096 }
7097 
7098 /// Compute the number of times the backedge of the specified loop will execute.
7099 ScalarEvolution::BackedgeTakenInfo
7100 ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
7101                                            bool AllowPredicates) {
7102   SmallVector<BasicBlock *, 8> ExitingBlocks;
7103   L->getExitingBlocks(ExitingBlocks);
7104 
7105   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
7106 
7107   SmallVector<EdgeExitInfo, 4> ExitCounts;
7108   bool CouldComputeBECount = true;
7109   BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
7110   const SCEV *MustExitMaxBECount = nullptr;
7111   const SCEV *MayExitMaxBECount = nullptr;
7112   bool MustExitMaxOrZero = false;
7113 
7114   // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
7115   // and compute maxBECount.
7116   // Do a union of all the predicates here.
7117   for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
7118     BasicBlock *ExitBB = ExitingBlocks[i];
7119 
7120     // We canonicalize untaken exits to br (constant), ignore them so that
7121     // proving an exit untaken doesn't negatively impact our ability to reason
7122     // about the loop as whole.
7123     if (auto *BI = dyn_cast<BranchInst>(ExitBB->getTerminator()))
7124       if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
7125         bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
7126         if ((ExitIfTrue && CI->isZero()) || (!ExitIfTrue && CI->isOne()))
7127           continue;
7128       }
7129 
7130     ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
7131 
7132     assert((AllowPredicates || EL.Predicates.empty()) &&
7133            "Predicated exit limit when predicates are not allowed!");
7134 
7135     // 1. For each exit that can be computed, add an entry to ExitCounts.
7136     // CouldComputeBECount is true only if all exits can be computed.
7137     if (EL.ExactNotTaken == getCouldNotCompute())
7138       // We couldn't compute an exact value for this exit, so
7139       // we won't be able to compute an exact value for the loop.
7140       CouldComputeBECount = false;
7141     else
7142       ExitCounts.emplace_back(ExitBB, EL);
7143 
7144     // 2. Derive the loop's MaxBECount from each exit's max number of
7145     // non-exiting iterations. Partition the loop exits into two kinds:
7146     // LoopMustExits and LoopMayExits.
7147     //
7148     // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
7149     // is a LoopMayExit.  If any computable LoopMustExit is found, then
7150     // MaxBECount is the minimum EL.MaxNotTaken of computable
7151     // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
7152     // EL.MaxNotTaken, where CouldNotCompute is considered greater than any
7153     // computable EL.MaxNotTaken.
7154     if (EL.MaxNotTaken != getCouldNotCompute() && Latch &&
7155         DT.dominates(ExitBB, Latch)) {
7156       if (!MustExitMaxBECount) {
7157         MustExitMaxBECount = EL.MaxNotTaken;
7158         MustExitMaxOrZero = EL.MaxOrZero;
7159       } else {
7160         MustExitMaxBECount =
7161             getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken);
7162       }
7163     } else if (MayExitMaxBECount != getCouldNotCompute()) {
7164       if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute())
7165         MayExitMaxBECount = EL.MaxNotTaken;
7166       else {
7167         MayExitMaxBECount =
7168             getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken);
7169       }
7170     }
7171   }
7172   const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
7173     (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
7174   // The loop backedge will be taken the maximum or zero times if there's
7175   // a single exit that must be taken the maximum or zero times.
7176   bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
7177   return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
7178                            MaxBECount, MaxOrZero);
7179 }
7180 
7181 ScalarEvolution::ExitLimit
7182 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
7183                                       bool AllowPredicates) {
7184   assert(L->contains(ExitingBlock) && "Exit count for non-loop block?");
7185   // If our exiting block does not dominate the latch, then its connection with
7186   // loop's exit limit may be far from trivial.
7187   const BasicBlock *Latch = L->getLoopLatch();
7188   if (!Latch || !DT.dominates(ExitingBlock, Latch))
7189     return getCouldNotCompute();
7190 
7191   bool IsOnlyExit = (L->getExitingBlock() != nullptr);
7192   Instruction *Term = ExitingBlock->getTerminator();
7193   if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
7194     assert(BI->isConditional() && "If unconditional, it can't be in loop!");
7195     bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
7196     assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) &&
7197            "It should have one successor in loop and one exit block!");
7198     // Proceed to the next level to examine the exit condition expression.
7199     return computeExitLimitFromCond(
7200         L, BI->getCondition(), ExitIfTrue,
7201         /*ControlsExit=*/IsOnlyExit, AllowPredicates);
7202   }
7203 
7204   if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) {
7205     // For switch, make sure that there is a single exit from the loop.
7206     BasicBlock *Exit = nullptr;
7207     for (auto *SBB : successors(ExitingBlock))
7208       if (!L->contains(SBB)) {
7209         if (Exit) // Multiple exit successors.
7210           return getCouldNotCompute();
7211         Exit = SBB;
7212       }
7213     assert(Exit && "Exiting block must have at least one exit");
7214     return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
7215                                                 /*ControlsExit=*/IsOnlyExit);
7216   }
7217 
7218   return getCouldNotCompute();
7219 }
7220 
7221 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond(
7222     const Loop *L, Value *ExitCond, bool ExitIfTrue,
7223     bool ControlsExit, bool AllowPredicates) {
7224   ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates);
7225   return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue,
7226                                         ControlsExit, AllowPredicates);
7227 }
7228 
7229 Optional<ScalarEvolution::ExitLimit>
7230 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
7231                                       bool ExitIfTrue, bool ControlsExit,
7232                                       bool AllowPredicates) {
7233   (void)this->L;
7234   (void)this->ExitIfTrue;
7235   (void)this->AllowPredicates;
7236 
7237   assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
7238          this->AllowPredicates == AllowPredicates &&
7239          "Variance in assumed invariant key components!");
7240   auto Itr = TripCountMap.find({ExitCond, ControlsExit});
7241   if (Itr == TripCountMap.end())
7242     return None;
7243   return Itr->second;
7244 }
7245 
7246 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
7247                                              bool ExitIfTrue,
7248                                              bool ControlsExit,
7249                                              bool AllowPredicates,
7250                                              const ExitLimit &EL) {
7251   assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
7252          this->AllowPredicates == AllowPredicates &&
7253          "Variance in assumed invariant key components!");
7254 
7255   auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL});
7256   assert(InsertResult.second && "Expected successful insertion!");
7257   (void)InsertResult;
7258   (void)ExitIfTrue;
7259 }
7260 
7261 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
7262     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
7263     bool ControlsExit, bool AllowPredicates) {
7264 
7265   if (auto MaybeEL =
7266           Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates))
7267     return *MaybeEL;
7268 
7269   ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue,
7270                                               ControlsExit, AllowPredicates);
7271   Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL);
7272   return EL;
7273 }
7274 
7275 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
7276     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
7277     bool ControlsExit, bool AllowPredicates) {
7278   // Check if the controlling expression for this loop is an And or Or.
7279   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
7280     if (BO->getOpcode() == Instruction::And) {
7281       // Recurse on the operands of the and.
7282       bool EitherMayExit = !ExitIfTrue;
7283       ExitLimit EL0 = computeExitLimitFromCondCached(
7284           Cache, L, BO->getOperand(0), ExitIfTrue,
7285           ControlsExit && !EitherMayExit, AllowPredicates);
7286       ExitLimit EL1 = computeExitLimitFromCondCached(
7287           Cache, L, BO->getOperand(1), ExitIfTrue,
7288           ControlsExit && !EitherMayExit, AllowPredicates);
7289       // Be robust against unsimplified IR for the form "and i1 X, true"
7290       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1)))
7291         return CI->isOne() ? EL0 : EL1;
7292       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(0)))
7293         return CI->isOne() ? EL1 : EL0;
7294       const SCEV *BECount = getCouldNotCompute();
7295       const SCEV *MaxBECount = getCouldNotCompute();
7296       if (EitherMayExit) {
7297         // Both conditions must be true for the loop to continue executing.
7298         // Choose the less conservative count.
7299         if (EL0.ExactNotTaken == getCouldNotCompute() ||
7300             EL1.ExactNotTaken == getCouldNotCompute())
7301           BECount = getCouldNotCompute();
7302         else
7303           BECount =
7304               getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
7305         if (EL0.MaxNotTaken == getCouldNotCompute())
7306           MaxBECount = EL1.MaxNotTaken;
7307         else if (EL1.MaxNotTaken == getCouldNotCompute())
7308           MaxBECount = EL0.MaxNotTaken;
7309         else
7310           MaxBECount =
7311               getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
7312       } else {
7313         // Both conditions must be true at the same time for the loop to exit.
7314         // For now, be conservative.
7315         if (EL0.MaxNotTaken == EL1.MaxNotTaken)
7316           MaxBECount = EL0.MaxNotTaken;
7317         if (EL0.ExactNotTaken == EL1.ExactNotTaken)
7318           BECount = EL0.ExactNotTaken;
7319       }
7320 
7321       // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
7322       // to be more aggressive when computing BECount than when computing
7323       // MaxBECount.  In these cases it is possible for EL0.ExactNotTaken and
7324       // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
7325       // to not.
7326       if (isa<SCEVCouldNotCompute>(MaxBECount) &&
7327           !isa<SCEVCouldNotCompute>(BECount))
7328         MaxBECount = getConstant(getUnsignedRangeMax(BECount));
7329 
7330       return ExitLimit(BECount, MaxBECount, false,
7331                        {&EL0.Predicates, &EL1.Predicates});
7332     }
7333     if (BO->getOpcode() == Instruction::Or) {
7334       // Recurse on the operands of the or.
7335       bool EitherMayExit = ExitIfTrue;
7336       ExitLimit EL0 = computeExitLimitFromCondCached(
7337           Cache, L, BO->getOperand(0), ExitIfTrue,
7338           ControlsExit && !EitherMayExit, AllowPredicates);
7339       ExitLimit EL1 = computeExitLimitFromCondCached(
7340           Cache, L, BO->getOperand(1), ExitIfTrue,
7341           ControlsExit && !EitherMayExit, AllowPredicates);
7342       // Be robust against unsimplified IR for the form "or i1 X, true"
7343       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1)))
7344         return CI->isZero() ? EL0 : EL1;
7345       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(0)))
7346         return CI->isZero() ? EL1 : EL0;
7347       const SCEV *BECount = getCouldNotCompute();
7348       const SCEV *MaxBECount = getCouldNotCompute();
7349       if (EitherMayExit) {
7350         // Both conditions must be false for the loop to continue executing.
7351         // Choose the less conservative count.
7352         if (EL0.ExactNotTaken == getCouldNotCompute() ||
7353             EL1.ExactNotTaken == getCouldNotCompute())
7354           BECount = getCouldNotCompute();
7355         else
7356           BECount =
7357               getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
7358         if (EL0.MaxNotTaken == getCouldNotCompute())
7359           MaxBECount = EL1.MaxNotTaken;
7360         else if (EL1.MaxNotTaken == getCouldNotCompute())
7361           MaxBECount = EL0.MaxNotTaken;
7362         else
7363           MaxBECount =
7364               getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
7365       } else {
7366         // Both conditions must be false at the same time for the loop to exit.
7367         // For now, be conservative.
7368         if (EL0.MaxNotTaken == EL1.MaxNotTaken)
7369           MaxBECount = EL0.MaxNotTaken;
7370         if (EL0.ExactNotTaken == EL1.ExactNotTaken)
7371           BECount = EL0.ExactNotTaken;
7372       }
7373       // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
7374       // to be more aggressive when computing BECount than when computing
7375       // MaxBECount.  In these cases it is possible for EL0.ExactNotTaken and
7376       // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
7377       // to not.
7378       if (isa<SCEVCouldNotCompute>(MaxBECount) &&
7379           !isa<SCEVCouldNotCompute>(BECount))
7380         MaxBECount = getConstant(getUnsignedRangeMax(BECount));
7381 
7382       return ExitLimit(BECount, MaxBECount, false,
7383                        {&EL0.Predicates, &EL1.Predicates});
7384     }
7385   }
7386 
7387   // With an icmp, it may be feasible to compute an exact backedge-taken count.
7388   // Proceed to the next level to examine the icmp.
7389   if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
7390     ExitLimit EL =
7391         computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit);
7392     if (EL.hasFullInfo() || !AllowPredicates)
7393       return EL;
7394 
7395     // Try again, but use SCEV predicates this time.
7396     return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit,
7397                                     /*AllowPredicates=*/true);
7398   }
7399 
7400   // Check for a constant condition. These are normally stripped out by
7401   // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
7402   // preserve the CFG and is temporarily leaving constant conditions
7403   // in place.
7404   if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
7405     if (ExitIfTrue == !CI->getZExtValue())
7406       // The backedge is always taken.
7407       return getCouldNotCompute();
7408     else
7409       // The backedge is never taken.
7410       return getZero(CI->getType());
7411   }
7412 
7413   // If it's not an integer or pointer comparison then compute it the hard way.
7414   return computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
7415 }
7416 
7417 ScalarEvolution::ExitLimit
7418 ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
7419                                           ICmpInst *ExitCond,
7420                                           bool ExitIfTrue,
7421                                           bool ControlsExit,
7422                                           bool AllowPredicates) {
7423   // If the condition was exit on true, convert the condition to exit on false
7424   ICmpInst::Predicate Pred;
7425   if (!ExitIfTrue)
7426     Pred = ExitCond->getPredicate();
7427   else
7428     Pred = ExitCond->getInversePredicate();
7429   const ICmpInst::Predicate OriginalPred = Pred;
7430 
7431   // Handle common loops like: for (X = "string"; *X; ++X)
7432   if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
7433     if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
7434       ExitLimit ItCnt =
7435         computeLoadConstantCompareExitLimit(LI, RHS, L, Pred);
7436       if (ItCnt.hasAnyInfo())
7437         return ItCnt;
7438     }
7439 
7440   const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
7441   const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
7442 
7443   // Try to evaluate any dependencies out of the loop.
7444   LHS = getSCEVAtScope(LHS, L);
7445   RHS = getSCEVAtScope(RHS, L);
7446 
7447   // At this point, we would like to compute how many iterations of the
7448   // loop the predicate will return true for these inputs.
7449   if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
7450     // If there is a loop-invariant, force it into the RHS.
7451     std::swap(LHS, RHS);
7452     Pred = ICmpInst::getSwappedPredicate(Pred);
7453   }
7454 
7455   // Simplify the operands before analyzing them.
7456   (void)SimplifyICmpOperands(Pred, LHS, RHS);
7457 
7458   // If we have a comparison of a chrec against a constant, try to use value
7459   // ranges to answer this query.
7460   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
7461     if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
7462       if (AddRec->getLoop() == L) {
7463         // Form the constant range.
7464         ConstantRange CompRange =
7465             ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt());
7466 
7467         const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
7468         if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
7469       }
7470 
7471   switch (Pred) {
7472   case ICmpInst::ICMP_NE: {                     // while (X != Y)
7473     // Convert to: while (X-Y != 0)
7474     ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit,
7475                                 AllowPredicates);
7476     if (EL.hasAnyInfo()) return EL;
7477     break;
7478   }
7479   case ICmpInst::ICMP_EQ: {                     // while (X == Y)
7480     // Convert to: while (X-Y == 0)
7481     ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
7482     if (EL.hasAnyInfo()) return EL;
7483     break;
7484   }
7485   case ICmpInst::ICMP_SLT:
7486   case ICmpInst::ICMP_ULT: {                    // while (X < Y)
7487     bool IsSigned = Pred == ICmpInst::ICMP_SLT;
7488     ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit,
7489                                     AllowPredicates);
7490     if (EL.hasAnyInfo()) return EL;
7491     break;
7492   }
7493   case ICmpInst::ICMP_SGT:
7494   case ICmpInst::ICMP_UGT: {                    // while (X > Y)
7495     bool IsSigned = Pred == ICmpInst::ICMP_SGT;
7496     ExitLimit EL =
7497         howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
7498                             AllowPredicates);
7499     if (EL.hasAnyInfo()) return EL;
7500     break;
7501   }
7502   default:
7503     break;
7504   }
7505 
7506   auto *ExhaustiveCount =
7507       computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
7508 
7509   if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
7510     return ExhaustiveCount;
7511 
7512   return computeShiftCompareExitLimit(ExitCond->getOperand(0),
7513                                       ExitCond->getOperand(1), L, OriginalPred);
7514 }
7515 
7516 ScalarEvolution::ExitLimit
7517 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
7518                                                       SwitchInst *Switch,
7519                                                       BasicBlock *ExitingBlock,
7520                                                       bool ControlsExit) {
7521   assert(!L->contains(ExitingBlock) && "Not an exiting block!");
7522 
7523   // Give up if the exit is the default dest of a switch.
7524   if (Switch->getDefaultDest() == ExitingBlock)
7525     return getCouldNotCompute();
7526 
7527   assert(L->contains(Switch->getDefaultDest()) &&
7528          "Default case must not exit the loop!");
7529   const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
7530   const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
7531 
7532   // while (X != Y) --> while (X-Y != 0)
7533   ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
7534   if (EL.hasAnyInfo())
7535     return EL;
7536 
7537   return getCouldNotCompute();
7538 }
7539 
7540 static ConstantInt *
7541 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
7542                                 ScalarEvolution &SE) {
7543   const SCEV *InVal = SE.getConstant(C);
7544   const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
7545   assert(isa<SCEVConstant>(Val) &&
7546          "Evaluation of SCEV at constant didn't fold correctly?");
7547   return cast<SCEVConstant>(Val)->getValue();
7548 }
7549 
7550 /// Given an exit condition of 'icmp op load X, cst', try to see if we can
7551 /// compute the backedge execution count.
7552 ScalarEvolution::ExitLimit
7553 ScalarEvolution::computeLoadConstantCompareExitLimit(
7554   LoadInst *LI,
7555   Constant *RHS,
7556   const Loop *L,
7557   ICmpInst::Predicate predicate) {
7558   if (LI->isVolatile()) return getCouldNotCompute();
7559 
7560   // Check to see if the loaded pointer is a getelementptr of a global.
7561   // TODO: Use SCEV instead of manually grubbing with GEPs.
7562   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
7563   if (!GEP) return getCouldNotCompute();
7564 
7565   // Make sure that it is really a constant global we are gepping, with an
7566   // initializer, and make sure the first IDX is really 0.
7567   GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
7568   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
7569       GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
7570       !cast<Constant>(GEP->getOperand(1))->isNullValue())
7571     return getCouldNotCompute();
7572 
7573   // Okay, we allow one non-constant index into the GEP instruction.
7574   Value *VarIdx = nullptr;
7575   std::vector<Constant*> Indexes;
7576   unsigned VarIdxNum = 0;
7577   for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
7578     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
7579       Indexes.push_back(CI);
7580     } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
7581       if (VarIdx) return getCouldNotCompute();  // Multiple non-constant idx's.
7582       VarIdx = GEP->getOperand(i);
7583       VarIdxNum = i-2;
7584       Indexes.push_back(nullptr);
7585     }
7586 
7587   // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
7588   if (!VarIdx)
7589     return getCouldNotCompute();
7590 
7591   // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
7592   // Check to see if X is a loop variant variable value now.
7593   const SCEV *Idx = getSCEV(VarIdx);
7594   Idx = getSCEVAtScope(Idx, L);
7595 
7596   // We can only recognize very limited forms of loop index expressions, in
7597   // particular, only affine AddRec's like {C1,+,C2}.
7598   const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
7599   if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
7600       !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
7601       !isa<SCEVConstant>(IdxExpr->getOperand(1)))
7602     return getCouldNotCompute();
7603 
7604   unsigned MaxSteps = MaxBruteForceIterations;
7605   for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
7606     ConstantInt *ItCst = ConstantInt::get(
7607                            cast<IntegerType>(IdxExpr->getType()), IterationNum);
7608     ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
7609 
7610     // Form the GEP offset.
7611     Indexes[VarIdxNum] = Val;
7612 
7613     Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
7614                                                          Indexes);
7615     if (!Result) break;  // Cannot compute!
7616 
7617     // Evaluate the condition for this iteration.
7618     Result = ConstantExpr::getICmp(predicate, Result, RHS);
7619     if (!isa<ConstantInt>(Result)) break;  // Couldn't decide for sure
7620     if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
7621       ++NumArrayLenItCounts;
7622       return getConstant(ItCst);   // Found terminating iteration!
7623     }
7624   }
7625   return getCouldNotCompute();
7626 }
7627 
7628 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
7629     Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
7630   ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
7631   if (!RHS)
7632     return getCouldNotCompute();
7633 
7634   const BasicBlock *Latch = L->getLoopLatch();
7635   if (!Latch)
7636     return getCouldNotCompute();
7637 
7638   const BasicBlock *Predecessor = L->getLoopPredecessor();
7639   if (!Predecessor)
7640     return getCouldNotCompute();
7641 
7642   // Return true if V is of the form "LHS `shift_op` <positive constant>".
7643   // Return LHS in OutLHS and shift_opt in OutOpCode.
7644   auto MatchPositiveShift =
7645       [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
7646 
7647     using namespace PatternMatch;
7648 
7649     ConstantInt *ShiftAmt;
7650     if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7651       OutOpCode = Instruction::LShr;
7652     else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7653       OutOpCode = Instruction::AShr;
7654     else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7655       OutOpCode = Instruction::Shl;
7656     else
7657       return false;
7658 
7659     return ShiftAmt->getValue().isStrictlyPositive();
7660   };
7661 
7662   // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
7663   //
7664   // loop:
7665   //   %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
7666   //   %iv.shifted = lshr i32 %iv, <positive constant>
7667   //
7668   // Return true on a successful match.  Return the corresponding PHI node (%iv
7669   // above) in PNOut and the opcode of the shift operation in OpCodeOut.
7670   auto MatchShiftRecurrence =
7671       [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
7672     Optional<Instruction::BinaryOps> PostShiftOpCode;
7673 
7674     {
7675       Instruction::BinaryOps OpC;
7676       Value *V;
7677 
7678       // If we encounter a shift instruction, "peel off" the shift operation,
7679       // and remember that we did so.  Later when we inspect %iv's backedge
7680       // value, we will make sure that the backedge value uses the same
7681       // operation.
7682       //
7683       // Note: the peeled shift operation does not have to be the same
7684       // instruction as the one feeding into the PHI's backedge value.  We only
7685       // really care about it being the same *kind* of shift instruction --
7686       // that's all that is required for our later inferences to hold.
7687       if (MatchPositiveShift(LHS, V, OpC)) {
7688         PostShiftOpCode = OpC;
7689         LHS = V;
7690       }
7691     }
7692 
7693     PNOut = dyn_cast<PHINode>(LHS);
7694     if (!PNOut || PNOut->getParent() != L->getHeader())
7695       return false;
7696 
7697     Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
7698     Value *OpLHS;
7699 
7700     return
7701         // The backedge value for the PHI node must be a shift by a positive
7702         // amount
7703         MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
7704 
7705         // of the PHI node itself
7706         OpLHS == PNOut &&
7707 
7708         // and the kind of shift should be match the kind of shift we peeled
7709         // off, if any.
7710         (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut);
7711   };
7712 
7713   PHINode *PN;
7714   Instruction::BinaryOps OpCode;
7715   if (!MatchShiftRecurrence(LHS, PN, OpCode))
7716     return getCouldNotCompute();
7717 
7718   const DataLayout &DL = getDataLayout();
7719 
7720   // The key rationale for this optimization is that for some kinds of shift
7721   // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
7722   // within a finite number of iterations.  If the condition guarding the
7723   // backedge (in the sense that the backedge is taken if the condition is true)
7724   // is false for the value the shift recurrence stabilizes to, then we know
7725   // that the backedge is taken only a finite number of times.
7726 
7727   ConstantInt *StableValue = nullptr;
7728   switch (OpCode) {
7729   default:
7730     llvm_unreachable("Impossible case!");
7731 
7732   case Instruction::AShr: {
7733     // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
7734     // bitwidth(K) iterations.
7735     Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
7736     KnownBits Known = computeKnownBits(FirstValue, DL, 0, nullptr,
7737                                        Predecessor->getTerminator(), &DT);
7738     auto *Ty = cast<IntegerType>(RHS->getType());
7739     if (Known.isNonNegative())
7740       StableValue = ConstantInt::get(Ty, 0);
7741     else if (Known.isNegative())
7742       StableValue = ConstantInt::get(Ty, -1, true);
7743     else
7744       return getCouldNotCompute();
7745 
7746     break;
7747   }
7748   case Instruction::LShr:
7749   case Instruction::Shl:
7750     // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
7751     // stabilize to 0 in at most bitwidth(K) iterations.
7752     StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
7753     break;
7754   }
7755 
7756   auto *Result =
7757       ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
7758   assert(Result->getType()->isIntegerTy(1) &&
7759          "Otherwise cannot be an operand to a branch instruction");
7760 
7761   if (Result->isZeroValue()) {
7762     unsigned BitWidth = getTypeSizeInBits(RHS->getType());
7763     const SCEV *UpperBound =
7764         getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
7765     return ExitLimit(getCouldNotCompute(), UpperBound, false);
7766   }
7767 
7768   return getCouldNotCompute();
7769 }
7770 
7771 /// Return true if we can constant fold an instruction of the specified type,
7772 /// assuming that all operands were constants.
7773 static bool CanConstantFold(const Instruction *I) {
7774   if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
7775       isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
7776       isa<LoadInst>(I) || isa<ExtractValueInst>(I))
7777     return true;
7778 
7779   if (const CallInst *CI = dyn_cast<CallInst>(I))
7780     if (const Function *F = CI->getCalledFunction())
7781       return canConstantFoldCallTo(CI, F);
7782   return false;
7783 }
7784 
7785 /// Determine whether this instruction can constant evolve within this loop
7786 /// assuming its operands can all constant evolve.
7787 static bool canConstantEvolve(Instruction *I, const Loop *L) {
7788   // An instruction outside of the loop can't be derived from a loop PHI.
7789   if (!L->contains(I)) return false;
7790 
7791   if (isa<PHINode>(I)) {
7792     // We don't currently keep track of the control flow needed to evaluate
7793     // PHIs, so we cannot handle PHIs inside of loops.
7794     return L->getHeader() == I->getParent();
7795   }
7796 
7797   // If we won't be able to constant fold this expression even if the operands
7798   // are constants, bail early.
7799   return CanConstantFold(I);
7800 }
7801 
7802 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
7803 /// recursing through each instruction operand until reaching a loop header phi.
7804 static PHINode *
7805 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
7806                                DenseMap<Instruction *, PHINode *> &PHIMap,
7807                                unsigned Depth) {
7808   if (Depth > MaxConstantEvolvingDepth)
7809     return nullptr;
7810 
7811   // Otherwise, we can evaluate this instruction if all of its operands are
7812   // constant or derived from a PHI node themselves.
7813   PHINode *PHI = nullptr;
7814   for (Value *Op : UseInst->operands()) {
7815     if (isa<Constant>(Op)) continue;
7816 
7817     Instruction *OpInst = dyn_cast<Instruction>(Op);
7818     if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
7819 
7820     PHINode *P = dyn_cast<PHINode>(OpInst);
7821     if (!P)
7822       // If this operand is already visited, reuse the prior result.
7823       // We may have P != PHI if this is the deepest point at which the
7824       // inconsistent paths meet.
7825       P = PHIMap.lookup(OpInst);
7826     if (!P) {
7827       // Recurse and memoize the results, whether a phi is found or not.
7828       // This recursive call invalidates pointers into PHIMap.
7829       P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1);
7830       PHIMap[OpInst] = P;
7831     }
7832     if (!P)
7833       return nullptr;  // Not evolving from PHI
7834     if (PHI && PHI != P)
7835       return nullptr;  // Evolving from multiple different PHIs.
7836     PHI = P;
7837   }
7838   // This is a expression evolving from a constant PHI!
7839   return PHI;
7840 }
7841 
7842 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
7843 /// in the loop that V is derived from.  We allow arbitrary operations along the
7844 /// way, but the operands of an operation must either be constants or a value
7845 /// derived from a constant PHI.  If this expression does not fit with these
7846 /// constraints, return null.
7847 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
7848   Instruction *I = dyn_cast<Instruction>(V);
7849   if (!I || !canConstantEvolve(I, L)) return nullptr;
7850 
7851   if (PHINode *PN = dyn_cast<PHINode>(I))
7852     return PN;
7853 
7854   // Record non-constant instructions contained by the loop.
7855   DenseMap<Instruction *, PHINode *> PHIMap;
7856   return getConstantEvolvingPHIOperands(I, L, PHIMap, 0);
7857 }
7858 
7859 /// EvaluateExpression - Given an expression that passes the
7860 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
7861 /// in the loop has the value PHIVal.  If we can't fold this expression for some
7862 /// reason, return null.
7863 static Constant *EvaluateExpression(Value *V, const Loop *L,
7864                                     DenseMap<Instruction *, Constant *> &Vals,
7865                                     const DataLayout &DL,
7866                                     const TargetLibraryInfo *TLI) {
7867   // Convenient constant check, but redundant for recursive calls.
7868   if (Constant *C = dyn_cast<Constant>(V)) return C;
7869   Instruction *I = dyn_cast<Instruction>(V);
7870   if (!I) return nullptr;
7871 
7872   if (Constant *C = Vals.lookup(I)) return C;
7873 
7874   // An instruction inside the loop depends on a value outside the loop that we
7875   // weren't given a mapping for, or a value such as a call inside the loop.
7876   if (!canConstantEvolve(I, L)) return nullptr;
7877 
7878   // An unmapped PHI can be due to a branch or another loop inside this loop,
7879   // or due to this not being the initial iteration through a loop where we
7880   // couldn't compute the evolution of this particular PHI last time.
7881   if (isa<PHINode>(I)) return nullptr;
7882 
7883   std::vector<Constant*> Operands(I->getNumOperands());
7884 
7885   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
7886     Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
7887     if (!Operand) {
7888       Operands[i] = dyn_cast<Constant>(I->getOperand(i));
7889       if (!Operands[i]) return nullptr;
7890       continue;
7891     }
7892     Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
7893     Vals[Operand] = C;
7894     if (!C) return nullptr;
7895     Operands[i] = C;
7896   }
7897 
7898   if (CmpInst *CI = dyn_cast<CmpInst>(I))
7899     return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
7900                                            Operands[1], DL, TLI);
7901   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
7902     if (!LI->isVolatile())
7903       return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
7904   }
7905   return ConstantFoldInstOperands(I, Operands, DL, TLI);
7906 }
7907 
7908 
7909 // If every incoming value to PN except the one for BB is a specific Constant,
7910 // return that, else return nullptr.
7911 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
7912   Constant *IncomingVal = nullptr;
7913 
7914   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
7915     if (PN->getIncomingBlock(i) == BB)
7916       continue;
7917 
7918     auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
7919     if (!CurrentVal)
7920       return nullptr;
7921 
7922     if (IncomingVal != CurrentVal) {
7923       if (IncomingVal)
7924         return nullptr;
7925       IncomingVal = CurrentVal;
7926     }
7927   }
7928 
7929   return IncomingVal;
7930 }
7931 
7932 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
7933 /// in the header of its containing loop, we know the loop executes a
7934 /// constant number of times, and the PHI node is just a recurrence
7935 /// involving constants, fold it.
7936 Constant *
7937 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
7938                                                    const APInt &BEs,
7939                                                    const Loop *L) {
7940   auto I = ConstantEvolutionLoopExitValue.find(PN);
7941   if (I != ConstantEvolutionLoopExitValue.end())
7942     return I->second;
7943 
7944   if (BEs.ugt(MaxBruteForceIterations))
7945     return ConstantEvolutionLoopExitValue[PN] = nullptr;  // Not going to evaluate it.
7946 
7947   Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
7948 
7949   DenseMap<Instruction *, Constant *> CurrentIterVals;
7950   BasicBlock *Header = L->getHeader();
7951   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
7952 
7953   BasicBlock *Latch = L->getLoopLatch();
7954   if (!Latch)
7955     return nullptr;
7956 
7957   for (PHINode &PHI : Header->phis()) {
7958     if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
7959       CurrentIterVals[&PHI] = StartCST;
7960   }
7961   if (!CurrentIterVals.count(PN))
7962     return RetVal = nullptr;
7963 
7964   Value *BEValue = PN->getIncomingValueForBlock(Latch);
7965 
7966   // Execute the loop symbolically to determine the exit value.
7967   assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) &&
7968          "BEs is <= MaxBruteForceIterations which is an 'unsigned'!");
7969 
7970   unsigned NumIterations = BEs.getZExtValue(); // must be in range
7971   unsigned IterationNum = 0;
7972   const DataLayout &DL = getDataLayout();
7973   for (; ; ++IterationNum) {
7974     if (IterationNum == NumIterations)
7975       return RetVal = CurrentIterVals[PN];  // Got exit value!
7976 
7977     // Compute the value of the PHIs for the next iteration.
7978     // EvaluateExpression adds non-phi values to the CurrentIterVals map.
7979     DenseMap<Instruction *, Constant *> NextIterVals;
7980     Constant *NextPHI =
7981         EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
7982     if (!NextPHI)
7983       return nullptr;        // Couldn't evaluate!
7984     NextIterVals[PN] = NextPHI;
7985 
7986     bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
7987 
7988     // Also evaluate the other PHI nodes.  However, we don't get to stop if we
7989     // cease to be able to evaluate one of them or if they stop evolving,
7990     // because that doesn't necessarily prevent us from computing PN.
7991     SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
7992     for (const auto &I : CurrentIterVals) {
7993       PHINode *PHI = dyn_cast<PHINode>(I.first);
7994       if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
7995       PHIsToCompute.emplace_back(PHI, I.second);
7996     }
7997     // We use two distinct loops because EvaluateExpression may invalidate any
7998     // iterators into CurrentIterVals.
7999     for (const auto &I : PHIsToCompute) {
8000       PHINode *PHI = I.first;
8001       Constant *&NextPHI = NextIterVals[PHI];
8002       if (!NextPHI) {   // Not already computed.
8003         Value *BEValue = PHI->getIncomingValueForBlock(Latch);
8004         NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
8005       }
8006       if (NextPHI != I.second)
8007         StoppedEvolving = false;
8008     }
8009 
8010     // If all entries in CurrentIterVals == NextIterVals then we can stop
8011     // iterating, the loop can't continue to change.
8012     if (StoppedEvolving)
8013       return RetVal = CurrentIterVals[PN];
8014 
8015     CurrentIterVals.swap(NextIterVals);
8016   }
8017 }
8018 
8019 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
8020                                                           Value *Cond,
8021                                                           bool ExitWhen) {
8022   PHINode *PN = getConstantEvolvingPHI(Cond, L);
8023   if (!PN) return getCouldNotCompute();
8024 
8025   // If the loop is canonicalized, the PHI will have exactly two entries.
8026   // That's the only form we support here.
8027   if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
8028 
8029   DenseMap<Instruction *, Constant *> CurrentIterVals;
8030   BasicBlock *Header = L->getHeader();
8031   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
8032 
8033   BasicBlock *Latch = L->getLoopLatch();
8034   assert(Latch && "Should follow from NumIncomingValues == 2!");
8035 
8036   for (PHINode &PHI : Header->phis()) {
8037     if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
8038       CurrentIterVals[&PHI] = StartCST;
8039   }
8040   if (!CurrentIterVals.count(PN))
8041     return getCouldNotCompute();
8042 
8043   // Okay, we find a PHI node that defines the trip count of this loop.  Execute
8044   // the loop symbolically to determine when the condition gets a value of
8045   // "ExitWhen".
8046   unsigned MaxIterations = MaxBruteForceIterations;   // Limit analysis.
8047   const DataLayout &DL = getDataLayout();
8048   for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
8049     auto *CondVal = dyn_cast_or_null<ConstantInt>(
8050         EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
8051 
8052     // Couldn't symbolically evaluate.
8053     if (!CondVal) return getCouldNotCompute();
8054 
8055     if (CondVal->getValue() == uint64_t(ExitWhen)) {
8056       ++NumBruteForceTripCountsComputed;
8057       return getConstant(Type::getInt32Ty(getContext()), IterationNum);
8058     }
8059 
8060     // Update all the PHI nodes for the next iteration.
8061     DenseMap<Instruction *, Constant *> NextIterVals;
8062 
8063     // Create a list of which PHIs we need to compute. We want to do this before
8064     // calling EvaluateExpression on them because that may invalidate iterators
8065     // into CurrentIterVals.
8066     SmallVector<PHINode *, 8> PHIsToCompute;
8067     for (const auto &I : CurrentIterVals) {
8068       PHINode *PHI = dyn_cast<PHINode>(I.first);
8069       if (!PHI || PHI->getParent() != Header) continue;
8070       PHIsToCompute.push_back(PHI);
8071     }
8072     for (PHINode *PHI : PHIsToCompute) {
8073       Constant *&NextPHI = NextIterVals[PHI];
8074       if (NextPHI) continue;    // Already computed!
8075 
8076       Value *BEValue = PHI->getIncomingValueForBlock(Latch);
8077       NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
8078     }
8079     CurrentIterVals.swap(NextIterVals);
8080   }
8081 
8082   // Too many iterations were needed to evaluate.
8083   return getCouldNotCompute();
8084 }
8085 
8086 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
8087   SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
8088       ValuesAtScopes[V];
8089   // Check to see if we've folded this expression at this loop before.
8090   for (auto &LS : Values)
8091     if (LS.first == L)
8092       return LS.second ? LS.second : V;
8093 
8094   Values.emplace_back(L, nullptr);
8095 
8096   // Otherwise compute it.
8097   const SCEV *C = computeSCEVAtScope(V, L);
8098   for (auto &LS : reverse(ValuesAtScopes[V]))
8099     if (LS.first == L) {
8100       LS.second = C;
8101       break;
8102     }
8103   return C;
8104 }
8105 
8106 /// This builds up a Constant using the ConstantExpr interface.  That way, we
8107 /// will return Constants for objects which aren't represented by a
8108 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
8109 /// Returns NULL if the SCEV isn't representable as a Constant.
8110 static Constant *BuildConstantFromSCEV(const SCEV *V) {
8111   switch (static_cast<SCEVTypes>(V->getSCEVType())) {
8112     case scCouldNotCompute:
8113     case scAddRecExpr:
8114       break;
8115     case scConstant:
8116       return cast<SCEVConstant>(V)->getValue();
8117     case scUnknown:
8118       return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
8119     case scSignExtend: {
8120       const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
8121       if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
8122         return ConstantExpr::getSExt(CastOp, SS->getType());
8123       break;
8124     }
8125     case scZeroExtend: {
8126       const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
8127       if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
8128         return ConstantExpr::getZExt(CastOp, SZ->getType());
8129       break;
8130     }
8131     case scTruncate: {
8132       const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
8133       if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
8134         return ConstantExpr::getTrunc(CastOp, ST->getType());
8135       break;
8136     }
8137     case scAddExpr: {
8138       const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
8139       if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
8140         if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
8141           unsigned AS = PTy->getAddressSpace();
8142           Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
8143           C = ConstantExpr::getBitCast(C, DestPtrTy);
8144         }
8145         for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
8146           Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
8147           if (!C2) return nullptr;
8148 
8149           // First pointer!
8150           if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
8151             unsigned AS = C2->getType()->getPointerAddressSpace();
8152             std::swap(C, C2);
8153             Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
8154             // The offsets have been converted to bytes.  We can add bytes to an
8155             // i8* by GEP with the byte count in the first index.
8156             C = ConstantExpr::getBitCast(C, DestPtrTy);
8157           }
8158 
8159           // Don't bother trying to sum two pointers. We probably can't
8160           // statically compute a load that results from it anyway.
8161           if (C2->getType()->isPointerTy())
8162             return nullptr;
8163 
8164           if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
8165             if (PTy->getElementType()->isStructTy())
8166               C2 = ConstantExpr::getIntegerCast(
8167                   C2, Type::getInt32Ty(C->getContext()), true);
8168             C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2);
8169           } else
8170             C = ConstantExpr::getAdd(C, C2);
8171         }
8172         return C;
8173       }
8174       break;
8175     }
8176     case scMulExpr: {
8177       const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
8178       if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
8179         // Don't bother with pointers at all.
8180         if (C->getType()->isPointerTy()) return nullptr;
8181         for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
8182           Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
8183           if (!C2 || C2->getType()->isPointerTy()) return nullptr;
8184           C = ConstantExpr::getMul(C, C2);
8185         }
8186         return C;
8187       }
8188       break;
8189     }
8190     case scUDivExpr: {
8191       const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
8192       if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
8193         if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
8194           if (LHS->getType() == RHS->getType())
8195             return ConstantExpr::getUDiv(LHS, RHS);
8196       break;
8197     }
8198     case scSMaxExpr:
8199     case scUMaxExpr:
8200     case scSMinExpr:
8201     case scUMinExpr:
8202       break; // TODO: smax, umax, smin, umax.
8203   }
8204   return nullptr;
8205 }
8206 
8207 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
8208   if (isa<SCEVConstant>(V)) return V;
8209 
8210   // If this instruction is evolved from a constant-evolving PHI, compute the
8211   // exit value from the loop without using SCEVs.
8212   if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
8213     if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
8214       if (PHINode *PN = dyn_cast<PHINode>(I)) {
8215         const Loop *LI = this->LI[I->getParent()];
8216         // Looking for loop exit value.
8217         if (LI && LI->getParentLoop() == L &&
8218             PN->getParent() == LI->getHeader()) {
8219           // Okay, there is no closed form solution for the PHI node.  Check
8220           // to see if the loop that contains it has a known backedge-taken
8221           // count.  If so, we may be able to force computation of the exit
8222           // value.
8223           const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
8224           // This trivial case can show up in some degenerate cases where
8225           // the incoming IR has not yet been fully simplified.
8226           if (BackedgeTakenCount->isZero()) {
8227             Value *InitValue = nullptr;
8228             bool MultipleInitValues = false;
8229             for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
8230               if (!LI->contains(PN->getIncomingBlock(i))) {
8231                 if (!InitValue)
8232                   InitValue = PN->getIncomingValue(i);
8233                 else if (InitValue != PN->getIncomingValue(i)) {
8234                   MultipleInitValues = true;
8235                   break;
8236                 }
8237               }
8238             }
8239             if (!MultipleInitValues && InitValue)
8240               return getSCEV(InitValue);
8241           }
8242           // Do we have a loop invariant value flowing around the backedge
8243           // for a loop which must execute the backedge?
8244           if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
8245               isKnownPositive(BackedgeTakenCount) &&
8246               PN->getNumIncomingValues() == 2) {
8247             unsigned InLoopPred = LI->contains(PN->getIncomingBlock(0)) ? 0 : 1;
8248             const SCEV *OnBackedge = getSCEV(PN->getIncomingValue(InLoopPred));
8249             if (IsAvailableOnEntry(LI, DT, OnBackedge, PN->getParent()))
8250               return OnBackedge;
8251           }
8252           if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
8253             // Okay, we know how many times the containing loop executes.  If
8254             // this is a constant evolving PHI node, get the final value at
8255             // the specified iteration number.
8256             Constant *RV =
8257                 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI);
8258             if (RV) return getSCEV(RV);
8259           }
8260         }
8261 
8262         // If there is a single-input Phi, evaluate it at our scope. If we can
8263         // prove that this replacement does not break LCSSA form, use new value.
8264         if (PN->getNumOperands() == 1) {
8265           const SCEV *Input = getSCEV(PN->getOperand(0));
8266           const SCEV *InputAtScope = getSCEVAtScope(Input, L);
8267           // TODO: We can generalize it using LI.replacementPreservesLCSSAForm,
8268           // for the simplest case just support constants.
8269           if (isa<SCEVConstant>(InputAtScope)) return InputAtScope;
8270         }
8271       }
8272 
8273       // Okay, this is an expression that we cannot symbolically evaluate
8274       // into a SCEV.  Check to see if it's possible to symbolically evaluate
8275       // the arguments into constants, and if so, try to constant propagate the
8276       // result.  This is particularly useful for computing loop exit values.
8277       if (CanConstantFold(I)) {
8278         SmallVector<Constant *, 4> Operands;
8279         bool MadeImprovement = false;
8280         for (Value *Op : I->operands()) {
8281           if (Constant *C = dyn_cast<Constant>(Op)) {
8282             Operands.push_back(C);
8283             continue;
8284           }
8285 
8286           // If any of the operands is non-constant and if they are
8287           // non-integer and non-pointer, don't even try to analyze them
8288           // with scev techniques.
8289           if (!isSCEVable(Op->getType()))
8290             return V;
8291 
8292           const SCEV *OrigV = getSCEV(Op);
8293           const SCEV *OpV = getSCEVAtScope(OrigV, L);
8294           MadeImprovement |= OrigV != OpV;
8295 
8296           Constant *C = BuildConstantFromSCEV(OpV);
8297           if (!C) return V;
8298           if (C->getType() != Op->getType())
8299             C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
8300                                                               Op->getType(),
8301                                                               false),
8302                                       C, Op->getType());
8303           Operands.push_back(C);
8304         }
8305 
8306         // Check to see if getSCEVAtScope actually made an improvement.
8307         if (MadeImprovement) {
8308           Constant *C = nullptr;
8309           const DataLayout &DL = getDataLayout();
8310           if (const CmpInst *CI = dyn_cast<CmpInst>(I))
8311             C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
8312                                                 Operands[1], DL, &TLI);
8313           else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
8314             if (!LI->isVolatile())
8315               C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
8316           } else
8317             C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
8318           if (!C) return V;
8319           return getSCEV(C);
8320         }
8321       }
8322     }
8323 
8324     // This is some other type of SCEVUnknown, just return it.
8325     return V;
8326   }
8327 
8328   if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
8329     // Avoid performing the look-up in the common case where the specified
8330     // expression has no loop-variant portions.
8331     for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
8332       const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
8333       if (OpAtScope != Comm->getOperand(i)) {
8334         // Okay, at least one of these operands is loop variant but might be
8335         // foldable.  Build a new instance of the folded commutative expression.
8336         SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
8337                                             Comm->op_begin()+i);
8338         NewOps.push_back(OpAtScope);
8339 
8340         for (++i; i != e; ++i) {
8341           OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
8342           NewOps.push_back(OpAtScope);
8343         }
8344         if (isa<SCEVAddExpr>(Comm))
8345           return getAddExpr(NewOps, Comm->getNoWrapFlags());
8346         if (isa<SCEVMulExpr>(Comm))
8347           return getMulExpr(NewOps, Comm->getNoWrapFlags());
8348         if (isa<SCEVMinMaxExpr>(Comm))
8349           return getMinMaxExpr(Comm->getSCEVType(), NewOps);
8350         llvm_unreachable("Unknown commutative SCEV type!");
8351       }
8352     }
8353     // If we got here, all operands are loop invariant.
8354     return Comm;
8355   }
8356 
8357   if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
8358     const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
8359     const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
8360     if (LHS == Div->getLHS() && RHS == Div->getRHS())
8361       return Div;   // must be loop invariant
8362     return getUDivExpr(LHS, RHS);
8363   }
8364 
8365   // If this is a loop recurrence for a loop that does not contain L, then we
8366   // are dealing with the final value computed by the loop.
8367   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
8368     // First, attempt to evaluate each operand.
8369     // Avoid performing the look-up in the common case where the specified
8370     // expression has no loop-variant portions.
8371     for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
8372       const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
8373       if (OpAtScope == AddRec->getOperand(i))
8374         continue;
8375 
8376       // Okay, at least one of these operands is loop variant but might be
8377       // foldable.  Build a new instance of the folded commutative expression.
8378       SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
8379                                           AddRec->op_begin()+i);
8380       NewOps.push_back(OpAtScope);
8381       for (++i; i != e; ++i)
8382         NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
8383 
8384       const SCEV *FoldedRec =
8385         getAddRecExpr(NewOps, AddRec->getLoop(),
8386                       AddRec->getNoWrapFlags(SCEV::FlagNW));
8387       AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
8388       // The addrec may be folded to a nonrecurrence, for example, if the
8389       // induction variable is multiplied by zero after constant folding. Go
8390       // ahead and return the folded value.
8391       if (!AddRec)
8392         return FoldedRec;
8393       break;
8394     }
8395 
8396     // If the scope is outside the addrec's loop, evaluate it by using the
8397     // loop exit value of the addrec.
8398     if (!AddRec->getLoop()->contains(L)) {
8399       // To evaluate this recurrence, we need to know how many times the AddRec
8400       // loop iterates.  Compute this now.
8401       const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
8402       if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
8403 
8404       // Then, evaluate the AddRec.
8405       return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
8406     }
8407 
8408     return AddRec;
8409   }
8410 
8411   if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
8412     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8413     if (Op == Cast->getOperand())
8414       return Cast;  // must be loop invariant
8415     return getZeroExtendExpr(Op, Cast->getType());
8416   }
8417 
8418   if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
8419     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8420     if (Op == Cast->getOperand())
8421       return Cast;  // must be loop invariant
8422     return getSignExtendExpr(Op, Cast->getType());
8423   }
8424 
8425   if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
8426     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8427     if (Op == Cast->getOperand())
8428       return Cast;  // must be loop invariant
8429     return getTruncateExpr(Op, Cast->getType());
8430   }
8431 
8432   llvm_unreachable("Unknown SCEV type!");
8433 }
8434 
8435 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
8436   return getSCEVAtScope(getSCEV(V), L);
8437 }
8438 
8439 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const {
8440   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S))
8441     return stripInjectiveFunctions(ZExt->getOperand());
8442   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S))
8443     return stripInjectiveFunctions(SExt->getOperand());
8444   return S;
8445 }
8446 
8447 /// Finds the minimum unsigned root of the following equation:
8448 ///
8449 ///     A * X = B (mod N)
8450 ///
8451 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
8452 /// A and B isn't important.
8453 ///
8454 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
8455 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B,
8456                                                ScalarEvolution &SE) {
8457   uint32_t BW = A.getBitWidth();
8458   assert(BW == SE.getTypeSizeInBits(B->getType()));
8459   assert(A != 0 && "A must be non-zero.");
8460 
8461   // 1. D = gcd(A, N)
8462   //
8463   // The gcd of A and N may have only one prime factor: 2. The number of
8464   // trailing zeros in A is its multiplicity
8465   uint32_t Mult2 = A.countTrailingZeros();
8466   // D = 2^Mult2
8467 
8468   // 2. Check if B is divisible by D.
8469   //
8470   // B is divisible by D if and only if the multiplicity of prime factor 2 for B
8471   // is not less than multiplicity of this prime factor for D.
8472   if (SE.GetMinTrailingZeros(B) < Mult2)
8473     return SE.getCouldNotCompute();
8474 
8475   // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
8476   // modulo (N / D).
8477   //
8478   // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
8479   // (N / D) in general. The inverse itself always fits into BW bits, though,
8480   // so we immediately truncate it.
8481   APInt AD = A.lshr(Mult2).zext(BW + 1);  // AD = A / D
8482   APInt Mod(BW + 1, 0);
8483   Mod.setBit(BW - Mult2);  // Mod = N / D
8484   APInt I = AD.multiplicativeInverse(Mod).trunc(BW);
8485 
8486   // 4. Compute the minimum unsigned root of the equation:
8487   // I * (B / D) mod (N / D)
8488   // To simplify the computation, we factor out the divide by D:
8489   // (I * B mod N) / D
8490   const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
8491   return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
8492 }
8493 
8494 /// For a given quadratic addrec, generate coefficients of the corresponding
8495 /// quadratic equation, multiplied by a common value to ensure that they are
8496 /// integers.
8497 /// The returned value is a tuple { A, B, C, M, BitWidth }, where
8498 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C
8499 /// were multiplied by, and BitWidth is the bit width of the original addrec
8500 /// coefficients.
8501 /// This function returns None if the addrec coefficients are not compile-
8502 /// time constants.
8503 static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>>
8504 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) {
8505   assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
8506   const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
8507   const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
8508   const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
8509   LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: "
8510                     << *AddRec << '\n');
8511 
8512   // We currently can only solve this if the coefficients are constants.
8513   if (!LC || !MC || !NC) {
8514     LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n");
8515     return None;
8516   }
8517 
8518   APInt L = LC->getAPInt();
8519   APInt M = MC->getAPInt();
8520   APInt N = NC->getAPInt();
8521   assert(!N.isNullValue() && "This is not a quadratic addrec");
8522 
8523   unsigned BitWidth = LC->getAPInt().getBitWidth();
8524   unsigned NewWidth = BitWidth + 1;
8525   LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: "
8526                     << BitWidth << '\n');
8527   // The sign-extension (as opposed to a zero-extension) here matches the
8528   // extension used in SolveQuadraticEquationWrap (with the same motivation).
8529   N = N.sext(NewWidth);
8530   M = M.sext(NewWidth);
8531   L = L.sext(NewWidth);
8532 
8533   // The increments are M, M+N, M+2N, ..., so the accumulated values are
8534   //   L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is,
8535   //   L+M, L+2M+N, L+3M+3N, ...
8536   // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N.
8537   //
8538   // The equation Acc = 0 is then
8539   //   L + nM + n(n-1)/2 N = 0,  or  2L + 2M n + n(n-1) N = 0.
8540   // In a quadratic form it becomes:
8541   //   N n^2 + (2M-N) n + 2L = 0.
8542 
8543   APInt A = N;
8544   APInt B = 2 * M - A;
8545   APInt C = 2 * L;
8546   APInt T = APInt(NewWidth, 2);
8547   LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B
8548                     << "x + " << C << ", coeff bw: " << NewWidth
8549                     << ", multiplied by " << T << '\n');
8550   return std::make_tuple(A, B, C, T, BitWidth);
8551 }
8552 
8553 /// Helper function to compare optional APInts:
8554 /// (a) if X and Y both exist, return min(X, Y),
8555 /// (b) if neither X nor Y exist, return None,
8556 /// (c) if exactly one of X and Y exists, return that value.
8557 static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) {
8558   if (X.hasValue() && Y.hasValue()) {
8559     unsigned W = std::max(X->getBitWidth(), Y->getBitWidth());
8560     APInt XW = X->sextOrSelf(W);
8561     APInt YW = Y->sextOrSelf(W);
8562     return XW.slt(YW) ? *X : *Y;
8563   }
8564   if (!X.hasValue() && !Y.hasValue())
8565     return None;
8566   return X.hasValue() ? *X : *Y;
8567 }
8568 
8569 /// Helper function to truncate an optional APInt to a given BitWidth.
8570 /// When solving addrec-related equations, it is preferable to return a value
8571 /// that has the same bit width as the original addrec's coefficients. If the
8572 /// solution fits in the original bit width, truncate it (except for i1).
8573 /// Returning a value of a different bit width may inhibit some optimizations.
8574 ///
8575 /// In general, a solution to a quadratic equation generated from an addrec
8576 /// may require BW+1 bits, where BW is the bit width of the addrec's
8577 /// coefficients. The reason is that the coefficients of the quadratic
8578 /// equation are BW+1 bits wide (to avoid truncation when converting from
8579 /// the addrec to the equation).
8580 static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) {
8581   if (!X.hasValue())
8582     return None;
8583   unsigned W = X->getBitWidth();
8584   if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth))
8585     return X->trunc(BitWidth);
8586   return X;
8587 }
8588 
8589 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n
8590 /// iterations. The values L, M, N are assumed to be signed, and they
8591 /// should all have the same bit widths.
8592 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW,
8593 /// where BW is the bit width of the addrec's coefficients.
8594 /// If the calculated value is a BW-bit integer (for BW > 1), it will be
8595 /// returned as such, otherwise the bit width of the returned value may
8596 /// be greater than BW.
8597 ///
8598 /// This function returns None if
8599 /// (a) the addrec coefficients are not constant, or
8600 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases
8601 ///     like x^2 = 5, no integer solutions exist, in other cases an integer
8602 ///     solution may exist, but SolveQuadraticEquationWrap may fail to find it.
8603 static Optional<APInt>
8604 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
8605   APInt A, B, C, M;
8606   unsigned BitWidth;
8607   auto T = GetQuadraticEquation(AddRec);
8608   if (!T.hasValue())
8609     return None;
8610 
8611   std::tie(A, B, C, M, BitWidth) = *T;
8612   LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n");
8613   Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1);
8614   if (!X.hasValue())
8615     return None;
8616 
8617   ConstantInt *CX = ConstantInt::get(SE.getContext(), *X);
8618   ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE);
8619   if (!V->isZero())
8620     return None;
8621 
8622   return TruncIfPossible(X, BitWidth);
8623 }
8624 
8625 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n
8626 /// iterations. The values M, N are assumed to be signed, and they
8627 /// should all have the same bit widths.
8628 /// Find the least n such that c(n) does not belong to the given range,
8629 /// while c(n-1) does.
8630 ///
8631 /// This function returns None if
8632 /// (a) the addrec coefficients are not constant, or
8633 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the
8634 ///     bounds of the range.
8635 static Optional<APInt>
8636 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec,
8637                           const ConstantRange &Range, ScalarEvolution &SE) {
8638   assert(AddRec->getOperand(0)->isZero() &&
8639          "Starting value of addrec should be 0");
8640   LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range "
8641                     << Range << ", addrec " << *AddRec << '\n');
8642   // This case is handled in getNumIterationsInRange. Here we can assume that
8643   // we start in the range.
8644   assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) &&
8645          "Addrec's initial value should be in range");
8646 
8647   APInt A, B, C, M;
8648   unsigned BitWidth;
8649   auto T = GetQuadraticEquation(AddRec);
8650   if (!T.hasValue())
8651     return None;
8652 
8653   // Be careful about the return value: there can be two reasons for not
8654   // returning an actual number. First, if no solutions to the equations
8655   // were found, and second, if the solutions don't leave the given range.
8656   // The first case means that the actual solution is "unknown", the second
8657   // means that it's known, but not valid. If the solution is unknown, we
8658   // cannot make any conclusions.
8659   // Return a pair: the optional solution and a flag indicating if the
8660   // solution was found.
8661   auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> {
8662     // Solve for signed overflow and unsigned overflow, pick the lower
8663     // solution.
8664     LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary "
8665                       << Bound << " (before multiplying by " << M << ")\n");
8666     Bound *= M; // The quadratic equation multiplier.
8667 
8668     Optional<APInt> SO = None;
8669     if (BitWidth > 1) {
8670       LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
8671                            "signed overflow\n");
8672       SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth);
8673     }
8674     LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
8675                          "unsigned overflow\n");
8676     Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound,
8677                                                               BitWidth+1);
8678 
8679     auto LeavesRange = [&] (const APInt &X) {
8680       ConstantInt *C0 = ConstantInt::get(SE.getContext(), X);
8681       ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE);
8682       if (Range.contains(V0->getValue()))
8683         return false;
8684       // X should be at least 1, so X-1 is non-negative.
8685       ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1);
8686       ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE);
8687       if (Range.contains(V1->getValue()))
8688         return true;
8689       return false;
8690     };
8691 
8692     // If SolveQuadraticEquationWrap returns None, it means that there can
8693     // be a solution, but the function failed to find it. We cannot treat it
8694     // as "no solution".
8695     if (!SO.hasValue() || !UO.hasValue())
8696       return { None, false };
8697 
8698     // Check the smaller value first to see if it leaves the range.
8699     // At this point, both SO and UO must have values.
8700     Optional<APInt> Min = MinOptional(SO, UO);
8701     if (LeavesRange(*Min))
8702       return { Min, true };
8703     Optional<APInt> Max = Min == SO ? UO : SO;
8704     if (LeavesRange(*Max))
8705       return { Max, true };
8706 
8707     // Solutions were found, but were eliminated, hence the "true".
8708     return { None, true };
8709   };
8710 
8711   std::tie(A, B, C, M, BitWidth) = *T;
8712   // Lower bound is inclusive, subtract 1 to represent the exiting value.
8713   APInt Lower = Range.getLower().sextOrSelf(A.getBitWidth()) - 1;
8714   APInt Upper = Range.getUpper().sextOrSelf(A.getBitWidth());
8715   auto SL = SolveForBoundary(Lower);
8716   auto SU = SolveForBoundary(Upper);
8717   // If any of the solutions was unknown, no meaninigful conclusions can
8718   // be made.
8719   if (!SL.second || !SU.second)
8720     return None;
8721 
8722   // Claim: The correct solution is not some value between Min and Max.
8723   //
8724   // Justification: Assuming that Min and Max are different values, one of
8725   // them is when the first signed overflow happens, the other is when the
8726   // first unsigned overflow happens. Crossing the range boundary is only
8727   // possible via an overflow (treating 0 as a special case of it, modeling
8728   // an overflow as crossing k*2^W for some k).
8729   //
8730   // The interesting case here is when Min was eliminated as an invalid
8731   // solution, but Max was not. The argument is that if there was another
8732   // overflow between Min and Max, it would also have been eliminated if
8733   // it was considered.
8734   //
8735   // For a given boundary, it is possible to have two overflows of the same
8736   // type (signed/unsigned) without having the other type in between: this
8737   // can happen when the vertex of the parabola is between the iterations
8738   // corresponding to the overflows. This is only possible when the two
8739   // overflows cross k*2^W for the same k. In such case, if the second one
8740   // left the range (and was the first one to do so), the first overflow
8741   // would have to enter the range, which would mean that either we had left
8742   // the range before or that we started outside of it. Both of these cases
8743   // are contradictions.
8744   //
8745   // Claim: In the case where SolveForBoundary returns None, the correct
8746   // solution is not some value between the Max for this boundary and the
8747   // Min of the other boundary.
8748   //
8749   // Justification: Assume that we had such Max_A and Min_B corresponding
8750   // to range boundaries A and B and such that Max_A < Min_B. If there was
8751   // a solution between Max_A and Min_B, it would have to be caused by an
8752   // overflow corresponding to either A or B. It cannot correspond to B,
8753   // since Min_B is the first occurrence of such an overflow. If it
8754   // corresponded to A, it would have to be either a signed or an unsigned
8755   // overflow that is larger than both eliminated overflows for A. But
8756   // between the eliminated overflows and this overflow, the values would
8757   // cover the entire value space, thus crossing the other boundary, which
8758   // is a contradiction.
8759 
8760   return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth);
8761 }
8762 
8763 ScalarEvolution::ExitLimit
8764 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit,
8765                               bool AllowPredicates) {
8766 
8767   // This is only used for loops with a "x != y" exit test. The exit condition
8768   // is now expressed as a single expression, V = x-y. So the exit test is
8769   // effectively V != 0.  We know and take advantage of the fact that this
8770   // expression only being used in a comparison by zero context.
8771 
8772   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
8773   // If the value is a constant
8774   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
8775     // If the value is already zero, the branch will execute zero times.
8776     if (C->getValue()->isZero()) return C;
8777     return getCouldNotCompute();  // Otherwise it will loop infinitely.
8778   }
8779 
8780   const SCEVAddRecExpr *AddRec =
8781       dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V));
8782 
8783   if (!AddRec && AllowPredicates)
8784     // Try to make this an AddRec using runtime tests, in the first X
8785     // iterations of this loop, where X is the SCEV expression found by the
8786     // algorithm below.
8787     AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
8788 
8789   if (!AddRec || AddRec->getLoop() != L)
8790     return getCouldNotCompute();
8791 
8792   // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
8793   // the quadratic equation to solve it.
8794   if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
8795     // We can only use this value if the chrec ends up with an exact zero
8796     // value at this index.  When solving for "X*X != 5", for example, we
8797     // should not accept a root of 2.
8798     if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) {
8799       const auto *R = cast<SCEVConstant>(getConstant(S.getValue()));
8800       return ExitLimit(R, R, false, Predicates);
8801     }
8802     return getCouldNotCompute();
8803   }
8804 
8805   // Otherwise we can only handle this if it is affine.
8806   if (!AddRec->isAffine())
8807     return getCouldNotCompute();
8808 
8809   // If this is an affine expression, the execution count of this branch is
8810   // the minimum unsigned root of the following equation:
8811   //
8812   //     Start + Step*N = 0 (mod 2^BW)
8813   //
8814   // equivalent to:
8815   //
8816   //             Step*N = -Start (mod 2^BW)
8817   //
8818   // where BW is the common bit width of Start and Step.
8819 
8820   // Get the initial value for the loop.
8821   const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
8822   const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
8823 
8824   // For now we handle only constant steps.
8825   //
8826   // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
8827   // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
8828   // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
8829   // We have not yet seen any such cases.
8830   const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
8831   if (!StepC || StepC->getValue()->isZero())
8832     return getCouldNotCompute();
8833 
8834   // For positive steps (counting up until unsigned overflow):
8835   //   N = -Start/Step (as unsigned)
8836   // For negative steps (counting down to zero):
8837   //   N = Start/-Step
8838   // First compute the unsigned distance from zero in the direction of Step.
8839   bool CountDown = StepC->getAPInt().isNegative();
8840   const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
8841 
8842   // Handle unitary steps, which cannot wraparound.
8843   // 1*N = -Start; -1*N = Start (mod 2^BW), so:
8844   //   N = Distance (as unsigned)
8845   if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) {
8846     APInt MaxBECount = getUnsignedRangeMax(Distance);
8847 
8848     // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
8849     // we end up with a loop whose backedge-taken count is n - 1.  Detect this
8850     // case, and see if we can improve the bound.
8851     //
8852     // Explicitly handling this here is necessary because getUnsignedRange
8853     // isn't context-sensitive; it doesn't know that we only care about the
8854     // range inside the loop.
8855     const SCEV *Zero = getZero(Distance->getType());
8856     const SCEV *One = getOne(Distance->getType());
8857     const SCEV *DistancePlusOne = getAddExpr(Distance, One);
8858     if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
8859       // If Distance + 1 doesn't overflow, we can compute the maximum distance
8860       // as "unsigned_max(Distance + 1) - 1".
8861       ConstantRange CR = getUnsignedRange(DistancePlusOne);
8862       MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1);
8863     }
8864     return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates);
8865   }
8866 
8867   // If the condition controls loop exit (the loop exits only if the expression
8868   // is true) and the addition is no-wrap we can use unsigned divide to
8869   // compute the backedge count.  In this case, the step may not divide the
8870   // distance, but we don't care because if the condition is "missed" the loop
8871   // will have undefined behavior due to wrapping.
8872   if (ControlsExit && AddRec->hasNoSelfWrap() &&
8873       loopHasNoAbnormalExits(AddRec->getLoop())) {
8874     const SCEV *Exact =
8875         getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
8876     const SCEV *Max =
8877         Exact == getCouldNotCompute()
8878             ? Exact
8879             : getConstant(getUnsignedRangeMax(Exact));
8880     return ExitLimit(Exact, Max, false, Predicates);
8881   }
8882 
8883   // Solve the general equation.
8884   const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(),
8885                                                getNegativeSCEV(Start), *this);
8886   const SCEV *M = E == getCouldNotCompute()
8887                       ? E
8888                       : getConstant(getUnsignedRangeMax(E));
8889   return ExitLimit(E, M, false, Predicates);
8890 }
8891 
8892 ScalarEvolution::ExitLimit
8893 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
8894   // Loops that look like: while (X == 0) are very strange indeed.  We don't
8895   // handle them yet except for the trivial case.  This could be expanded in the
8896   // future as needed.
8897 
8898   // If the value is a constant, check to see if it is known to be non-zero
8899   // already.  If so, the backedge will execute zero times.
8900   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
8901     if (!C->getValue()->isZero())
8902       return getZero(C->getType());
8903     return getCouldNotCompute();  // Otherwise it will loop infinitely.
8904   }
8905 
8906   // We could implement others, but I really doubt anyone writes loops like
8907   // this, and if they did, they would already be constant folded.
8908   return getCouldNotCompute();
8909 }
8910 
8911 std::pair<BasicBlock *, BasicBlock *>
8912 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
8913   // If the block has a unique predecessor, then there is no path from the
8914   // predecessor to the block that does not go through the direct edge
8915   // from the predecessor to the block.
8916   if (BasicBlock *Pred = BB->getSinglePredecessor())
8917     return {Pred, BB};
8918 
8919   // A loop's header is defined to be a block that dominates the loop.
8920   // If the header has a unique predecessor outside the loop, it must be
8921   // a block that has exactly one successor that can reach the loop.
8922   if (Loop *L = LI.getLoopFor(BB))
8923     return {L->getLoopPredecessor(), L->getHeader()};
8924 
8925   return {nullptr, nullptr};
8926 }
8927 
8928 /// SCEV structural equivalence is usually sufficient for testing whether two
8929 /// expressions are equal, however for the purposes of looking for a condition
8930 /// guarding a loop, it can be useful to be a little more general, since a
8931 /// front-end may have replicated the controlling expression.
8932 static bool HasSameValue(const SCEV *A, const SCEV *B) {
8933   // Quick check to see if they are the same SCEV.
8934   if (A == B) return true;
8935 
8936   auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
8937     // Not all instructions that are "identical" compute the same value.  For
8938     // instance, two distinct alloca instructions allocating the same type are
8939     // identical and do not read memory; but compute distinct values.
8940     return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
8941   };
8942 
8943   // Otherwise, if they're both SCEVUnknown, it's possible that they hold
8944   // two different instructions with the same value. Check for this case.
8945   if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
8946     if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
8947       if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
8948         if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
8949           if (ComputesEqualValues(AI, BI))
8950             return true;
8951 
8952   // Otherwise assume they may have a different value.
8953   return false;
8954 }
8955 
8956 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
8957                                            const SCEV *&LHS, const SCEV *&RHS,
8958                                            unsigned Depth) {
8959   bool Changed = false;
8960   // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or
8961   // '0 != 0'.
8962   auto TrivialCase = [&](bool TriviallyTrue) {
8963     LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
8964     Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
8965     return true;
8966   };
8967   // If we hit the max recursion limit bail out.
8968   if (Depth >= 3)
8969     return false;
8970 
8971   // Canonicalize a constant to the right side.
8972   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
8973     // Check for both operands constant.
8974     if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
8975       if (ConstantExpr::getICmp(Pred,
8976                                 LHSC->getValue(),
8977                                 RHSC->getValue())->isNullValue())
8978         return TrivialCase(false);
8979       else
8980         return TrivialCase(true);
8981     }
8982     // Otherwise swap the operands to put the constant on the right.
8983     std::swap(LHS, RHS);
8984     Pred = ICmpInst::getSwappedPredicate(Pred);
8985     Changed = true;
8986   }
8987 
8988   // If we're comparing an addrec with a value which is loop-invariant in the
8989   // addrec's loop, put the addrec on the left. Also make a dominance check,
8990   // as both operands could be addrecs loop-invariant in each other's loop.
8991   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
8992     const Loop *L = AR->getLoop();
8993     if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
8994       std::swap(LHS, RHS);
8995       Pred = ICmpInst::getSwappedPredicate(Pred);
8996       Changed = true;
8997     }
8998   }
8999 
9000   // If there's a constant operand, canonicalize comparisons with boundary
9001   // cases, and canonicalize *-or-equal comparisons to regular comparisons.
9002   if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
9003     const APInt &RA = RC->getAPInt();
9004 
9005     bool SimplifiedByConstantRange = false;
9006 
9007     if (!ICmpInst::isEquality(Pred)) {
9008       ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA);
9009       if (ExactCR.isFullSet())
9010         return TrivialCase(true);
9011       else if (ExactCR.isEmptySet())
9012         return TrivialCase(false);
9013 
9014       APInt NewRHS;
9015       CmpInst::Predicate NewPred;
9016       if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
9017           ICmpInst::isEquality(NewPred)) {
9018         // We were able to convert an inequality to an equality.
9019         Pred = NewPred;
9020         RHS = getConstant(NewRHS);
9021         Changed = SimplifiedByConstantRange = true;
9022       }
9023     }
9024 
9025     if (!SimplifiedByConstantRange) {
9026       switch (Pred) {
9027       default:
9028         break;
9029       case ICmpInst::ICMP_EQ:
9030       case ICmpInst::ICMP_NE:
9031         // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
9032         if (!RA)
9033           if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
9034             if (const SCEVMulExpr *ME =
9035                     dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
9036               if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
9037                   ME->getOperand(0)->isAllOnesValue()) {
9038                 RHS = AE->getOperand(1);
9039                 LHS = ME->getOperand(1);
9040                 Changed = true;
9041               }
9042         break;
9043 
9044 
9045         // The "Should have been caught earlier!" messages refer to the fact
9046         // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
9047         // should have fired on the corresponding cases, and canonicalized the
9048         // check to trivial case.
9049 
9050       case ICmpInst::ICMP_UGE:
9051         assert(!RA.isMinValue() && "Should have been caught earlier!");
9052         Pred = ICmpInst::ICMP_UGT;
9053         RHS = getConstant(RA - 1);
9054         Changed = true;
9055         break;
9056       case ICmpInst::ICMP_ULE:
9057         assert(!RA.isMaxValue() && "Should have been caught earlier!");
9058         Pred = ICmpInst::ICMP_ULT;
9059         RHS = getConstant(RA + 1);
9060         Changed = true;
9061         break;
9062       case ICmpInst::ICMP_SGE:
9063         assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
9064         Pred = ICmpInst::ICMP_SGT;
9065         RHS = getConstant(RA - 1);
9066         Changed = true;
9067         break;
9068       case ICmpInst::ICMP_SLE:
9069         assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
9070         Pred = ICmpInst::ICMP_SLT;
9071         RHS = getConstant(RA + 1);
9072         Changed = true;
9073         break;
9074       }
9075     }
9076   }
9077 
9078   // Check for obvious equality.
9079   if (HasSameValue(LHS, RHS)) {
9080     if (ICmpInst::isTrueWhenEqual(Pred))
9081       return TrivialCase(true);
9082     if (ICmpInst::isFalseWhenEqual(Pred))
9083       return TrivialCase(false);
9084   }
9085 
9086   // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
9087   // adding or subtracting 1 from one of the operands.
9088   switch (Pred) {
9089   case ICmpInst::ICMP_SLE:
9090     if (!getSignedRangeMax(RHS).isMaxSignedValue()) {
9091       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
9092                        SCEV::FlagNSW);
9093       Pred = ICmpInst::ICMP_SLT;
9094       Changed = true;
9095     } else if (!getSignedRangeMin(LHS).isMinSignedValue()) {
9096       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
9097                        SCEV::FlagNSW);
9098       Pred = ICmpInst::ICMP_SLT;
9099       Changed = true;
9100     }
9101     break;
9102   case ICmpInst::ICMP_SGE:
9103     if (!getSignedRangeMin(RHS).isMinSignedValue()) {
9104       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
9105                        SCEV::FlagNSW);
9106       Pred = ICmpInst::ICMP_SGT;
9107       Changed = true;
9108     } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) {
9109       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
9110                        SCEV::FlagNSW);
9111       Pred = ICmpInst::ICMP_SGT;
9112       Changed = true;
9113     }
9114     break;
9115   case ICmpInst::ICMP_ULE:
9116     if (!getUnsignedRangeMax(RHS).isMaxValue()) {
9117       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
9118                        SCEV::FlagNUW);
9119       Pred = ICmpInst::ICMP_ULT;
9120       Changed = true;
9121     } else if (!getUnsignedRangeMin(LHS).isMinValue()) {
9122       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
9123       Pred = ICmpInst::ICMP_ULT;
9124       Changed = true;
9125     }
9126     break;
9127   case ICmpInst::ICMP_UGE:
9128     if (!getUnsignedRangeMin(RHS).isMinValue()) {
9129       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
9130       Pred = ICmpInst::ICMP_UGT;
9131       Changed = true;
9132     } else if (!getUnsignedRangeMax(LHS).isMaxValue()) {
9133       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
9134                        SCEV::FlagNUW);
9135       Pred = ICmpInst::ICMP_UGT;
9136       Changed = true;
9137     }
9138     break;
9139   default:
9140     break;
9141   }
9142 
9143   // TODO: More simplifications are possible here.
9144 
9145   // Recursively simplify until we either hit a recursion limit or nothing
9146   // changes.
9147   if (Changed)
9148     return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
9149 
9150   return Changed;
9151 }
9152 
9153 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
9154   return getSignedRangeMax(S).isNegative();
9155 }
9156 
9157 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
9158   return getSignedRangeMin(S).isStrictlyPositive();
9159 }
9160 
9161 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
9162   return !getSignedRangeMin(S).isNegative();
9163 }
9164 
9165 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
9166   return !getSignedRangeMax(S).isStrictlyPositive();
9167 }
9168 
9169 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
9170   return isKnownNegative(S) || isKnownPositive(S);
9171 }
9172 
9173 std::pair<const SCEV *, const SCEV *>
9174 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) {
9175   // Compute SCEV on entry of loop L.
9176   const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this);
9177   if (Start == getCouldNotCompute())
9178     return { Start, Start };
9179   // Compute post increment SCEV for loop L.
9180   const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this);
9181   assert(PostInc != getCouldNotCompute() && "Unexpected could not compute");
9182   return { Start, PostInc };
9183 }
9184 
9185 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred,
9186                                           const SCEV *LHS, const SCEV *RHS) {
9187   // First collect all loops.
9188   SmallPtrSet<const Loop *, 8> LoopsUsed;
9189   getUsedLoops(LHS, LoopsUsed);
9190   getUsedLoops(RHS, LoopsUsed);
9191 
9192   if (LoopsUsed.empty())
9193     return false;
9194 
9195   // Domination relationship must be a linear order on collected loops.
9196 #ifndef NDEBUG
9197   for (auto *L1 : LoopsUsed)
9198     for (auto *L2 : LoopsUsed)
9199       assert((DT.dominates(L1->getHeader(), L2->getHeader()) ||
9200               DT.dominates(L2->getHeader(), L1->getHeader())) &&
9201              "Domination relationship is not a linear order");
9202 #endif
9203 
9204   const Loop *MDL =
9205       *std::max_element(LoopsUsed.begin(), LoopsUsed.end(),
9206                         [&](const Loop *L1, const Loop *L2) {
9207          return DT.properlyDominates(L1->getHeader(), L2->getHeader());
9208        });
9209 
9210   // Get init and post increment value for LHS.
9211   auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS);
9212   // if LHS contains unknown non-invariant SCEV then bail out.
9213   if (SplitLHS.first == getCouldNotCompute())
9214     return false;
9215   assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC");
9216   // Get init and post increment value for RHS.
9217   auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS);
9218   // if RHS contains unknown non-invariant SCEV then bail out.
9219   if (SplitRHS.first == getCouldNotCompute())
9220     return false;
9221   assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC");
9222   // It is possible that init SCEV contains an invariant load but it does
9223   // not dominate MDL and is not available at MDL loop entry, so we should
9224   // check it here.
9225   if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) ||
9226       !isAvailableAtLoopEntry(SplitRHS.first, MDL))
9227     return false;
9228 
9229   return isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first) &&
9230          isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second,
9231                                      SplitRHS.second);
9232 }
9233 
9234 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
9235                                        const SCEV *LHS, const SCEV *RHS) {
9236   // Canonicalize the inputs first.
9237   (void)SimplifyICmpOperands(Pred, LHS, RHS);
9238 
9239   if (isKnownViaInduction(Pred, LHS, RHS))
9240     return true;
9241 
9242   if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
9243     return true;
9244 
9245   // Otherwise see what can be done with some simple reasoning.
9246   return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS);
9247 }
9248 
9249 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred,
9250                                               const SCEVAddRecExpr *LHS,
9251                                               const SCEV *RHS) {
9252   const Loop *L = LHS->getLoop();
9253   return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) &&
9254          isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS);
9255 }
9256 
9257 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS,
9258                                            ICmpInst::Predicate Pred,
9259                                            bool &Increasing) {
9260   bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing);
9261 
9262 #ifndef NDEBUG
9263   // Verify an invariant: inverting the predicate should turn a monotonically
9264   // increasing change to a monotonically decreasing one, and vice versa.
9265   bool IncreasingSwapped;
9266   bool ResultSwapped = isMonotonicPredicateImpl(
9267       LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped);
9268 
9269   assert(Result == ResultSwapped && "should be able to analyze both!");
9270   if (ResultSwapped)
9271     assert(Increasing == !IncreasingSwapped &&
9272            "monotonicity should flip as we flip the predicate");
9273 #endif
9274 
9275   return Result;
9276 }
9277 
9278 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS,
9279                                                ICmpInst::Predicate Pred,
9280                                                bool &Increasing) {
9281 
9282   // A zero step value for LHS means the induction variable is essentially a
9283   // loop invariant value. We don't really depend on the predicate actually
9284   // flipping from false to true (for increasing predicates, and the other way
9285   // around for decreasing predicates), all we care about is that *if* the
9286   // predicate changes then it only changes from false to true.
9287   //
9288   // A zero step value in itself is not very useful, but there may be places
9289   // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
9290   // as general as possible.
9291 
9292   switch (Pred) {
9293   default:
9294     return false; // Conservative answer
9295 
9296   case ICmpInst::ICMP_UGT:
9297   case ICmpInst::ICMP_UGE:
9298   case ICmpInst::ICMP_ULT:
9299   case ICmpInst::ICMP_ULE:
9300     if (!LHS->hasNoUnsignedWrap())
9301       return false;
9302 
9303     Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE;
9304     return true;
9305 
9306   case ICmpInst::ICMP_SGT:
9307   case ICmpInst::ICMP_SGE:
9308   case ICmpInst::ICMP_SLT:
9309   case ICmpInst::ICMP_SLE: {
9310     if (!LHS->hasNoSignedWrap())
9311       return false;
9312 
9313     const SCEV *Step = LHS->getStepRecurrence(*this);
9314 
9315     if (isKnownNonNegative(Step)) {
9316       Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE;
9317       return true;
9318     }
9319 
9320     if (isKnownNonPositive(Step)) {
9321       Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE;
9322       return true;
9323     }
9324 
9325     return false;
9326   }
9327 
9328   }
9329 
9330   llvm_unreachable("switch has default clause!");
9331 }
9332 
9333 bool ScalarEvolution::isLoopInvariantPredicate(
9334     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
9335     ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS,
9336     const SCEV *&InvariantRHS) {
9337 
9338   // If there is a loop-invariant, force it into the RHS, otherwise bail out.
9339   if (!isLoopInvariant(RHS, L)) {
9340     if (!isLoopInvariant(LHS, L))
9341       return false;
9342 
9343     std::swap(LHS, RHS);
9344     Pred = ICmpInst::getSwappedPredicate(Pred);
9345   }
9346 
9347   const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
9348   if (!ArLHS || ArLHS->getLoop() != L)
9349     return false;
9350 
9351   bool Increasing;
9352   if (!isMonotonicPredicate(ArLHS, Pred, Increasing))
9353     return false;
9354 
9355   // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
9356   // true as the loop iterates, and the backedge is control dependent on
9357   // "ArLHS `Pred` RHS" == true then we can reason as follows:
9358   //
9359   //   * if the predicate was false in the first iteration then the predicate
9360   //     is never evaluated again, since the loop exits without taking the
9361   //     backedge.
9362   //   * if the predicate was true in the first iteration then it will
9363   //     continue to be true for all future iterations since it is
9364   //     monotonically increasing.
9365   //
9366   // For both the above possibilities, we can replace the loop varying
9367   // predicate with its value on the first iteration of the loop (which is
9368   // loop invariant).
9369   //
9370   // A similar reasoning applies for a monotonically decreasing predicate, by
9371   // replacing true with false and false with true in the above two bullets.
9372 
9373   auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
9374 
9375   if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
9376     return false;
9377 
9378   InvariantPred = Pred;
9379   InvariantLHS = ArLHS->getStart();
9380   InvariantRHS = RHS;
9381   return true;
9382 }
9383 
9384 bool ScalarEvolution::isKnownPredicateViaConstantRanges(
9385     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
9386   if (HasSameValue(LHS, RHS))
9387     return ICmpInst::isTrueWhenEqual(Pred);
9388 
9389   // This code is split out from isKnownPredicate because it is called from
9390   // within isLoopEntryGuardedByCond.
9391 
9392   auto CheckRanges =
9393       [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) {
9394     return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS)
9395         .contains(RangeLHS);
9396   };
9397 
9398   // The check at the top of the function catches the case where the values are
9399   // known to be equal.
9400   if (Pred == CmpInst::ICMP_EQ)
9401     return false;
9402 
9403   if (Pred == CmpInst::ICMP_NE)
9404     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) ||
9405            CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) ||
9406            isKnownNonZero(getMinusSCEV(LHS, RHS));
9407 
9408   if (CmpInst::isSigned(Pred))
9409     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS));
9410 
9411   return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS));
9412 }
9413 
9414 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
9415                                                     const SCEV *LHS,
9416                                                     const SCEV *RHS) {
9417   // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer.
9418   // Return Y via OutY.
9419   auto MatchBinaryAddToConst =
9420       [this](const SCEV *Result, const SCEV *X, APInt &OutY,
9421              SCEV::NoWrapFlags ExpectedFlags) {
9422     const SCEV *NonConstOp, *ConstOp;
9423     SCEV::NoWrapFlags FlagsPresent;
9424 
9425     if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) ||
9426         !isa<SCEVConstant>(ConstOp) || NonConstOp != X)
9427       return false;
9428 
9429     OutY = cast<SCEVConstant>(ConstOp)->getAPInt();
9430     return (FlagsPresent & ExpectedFlags) == ExpectedFlags;
9431   };
9432 
9433   APInt C;
9434 
9435   switch (Pred) {
9436   default:
9437     break;
9438 
9439   case ICmpInst::ICMP_SGE:
9440     std::swap(LHS, RHS);
9441     LLVM_FALLTHROUGH;
9442   case ICmpInst::ICMP_SLE:
9443     // X s<= (X + C)<nsw> if C >= 0
9444     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative())
9445       return true;
9446 
9447     // (X + C)<nsw> s<= X if C <= 0
9448     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) &&
9449         !C.isStrictlyPositive())
9450       return true;
9451     break;
9452 
9453   case ICmpInst::ICMP_SGT:
9454     std::swap(LHS, RHS);
9455     LLVM_FALLTHROUGH;
9456   case ICmpInst::ICMP_SLT:
9457     // X s< (X + C)<nsw> if C > 0
9458     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) &&
9459         C.isStrictlyPositive())
9460       return true;
9461 
9462     // (X + C)<nsw> s< X if C < 0
9463     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative())
9464       return true;
9465     break;
9466   }
9467 
9468   return false;
9469 }
9470 
9471 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
9472                                                    const SCEV *LHS,
9473                                                    const SCEV *RHS) {
9474   if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
9475     return false;
9476 
9477   // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
9478   // the stack can result in exponential time complexity.
9479   SaveAndRestore<bool> Restore(ProvingSplitPredicate, true);
9480 
9481   // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
9482   //
9483   // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
9484   // isKnownPredicate.  isKnownPredicate is more powerful, but also more
9485   // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
9486   // interesting cases seen in practice.  We can consider "upgrading" L >= 0 to
9487   // use isKnownPredicate later if needed.
9488   return isKnownNonNegative(RHS) &&
9489          isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
9490          isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
9491 }
9492 
9493 bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB,
9494                                         ICmpInst::Predicate Pred,
9495                                         const SCEV *LHS, const SCEV *RHS) {
9496   // No need to even try if we know the module has no guards.
9497   if (!HasGuards)
9498     return false;
9499 
9500   return any_of(*BB, [&](Instruction &I) {
9501     using namespace llvm::PatternMatch;
9502 
9503     Value *Condition;
9504     return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
9505                          m_Value(Condition))) &&
9506            isImpliedCond(Pred, LHS, RHS, Condition, false);
9507   });
9508 }
9509 
9510 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
9511 /// protected by a conditional between LHS and RHS.  This is used to
9512 /// to eliminate casts.
9513 bool
9514 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
9515                                              ICmpInst::Predicate Pred,
9516                                              const SCEV *LHS, const SCEV *RHS) {
9517   // Interpret a null as meaning no loop, where there is obviously no guard
9518   // (interprocedural conditions notwithstanding).
9519   if (!L) return true;
9520 
9521   if (VerifyIR)
9522     assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) &&
9523            "This cannot be done on broken IR!");
9524 
9525 
9526   if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
9527     return true;
9528 
9529   BasicBlock *Latch = L->getLoopLatch();
9530   if (!Latch)
9531     return false;
9532 
9533   BranchInst *LoopContinuePredicate =
9534     dyn_cast<BranchInst>(Latch->getTerminator());
9535   if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
9536       isImpliedCond(Pred, LHS, RHS,
9537                     LoopContinuePredicate->getCondition(),
9538                     LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
9539     return true;
9540 
9541   // We don't want more than one activation of the following loops on the stack
9542   // -- that can lead to O(n!) time complexity.
9543   if (WalkingBEDominatingConds)
9544     return false;
9545 
9546   SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true);
9547 
9548   // See if we can exploit a trip count to prove the predicate.
9549   const auto &BETakenInfo = getBackedgeTakenInfo(L);
9550   const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
9551   if (LatchBECount != getCouldNotCompute()) {
9552     // We know that Latch branches back to the loop header exactly
9553     // LatchBECount times.  This means the backdege condition at Latch is
9554     // equivalent to  "{0,+,1} u< LatchBECount".
9555     Type *Ty = LatchBECount->getType();
9556     auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
9557     const SCEV *LoopCounter =
9558       getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
9559     if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
9560                       LatchBECount))
9561       return true;
9562   }
9563 
9564   // Check conditions due to any @llvm.assume intrinsics.
9565   for (auto &AssumeVH : AC.assumptions()) {
9566     if (!AssumeVH)
9567       continue;
9568     auto *CI = cast<CallInst>(AssumeVH);
9569     if (!DT.dominates(CI, Latch->getTerminator()))
9570       continue;
9571 
9572     if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
9573       return true;
9574   }
9575 
9576   // If the loop is not reachable from the entry block, we risk running into an
9577   // infinite loop as we walk up into the dom tree.  These loops do not matter
9578   // anyway, so we just return a conservative answer when we see them.
9579   if (!DT.isReachableFromEntry(L->getHeader()))
9580     return false;
9581 
9582   if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
9583     return true;
9584 
9585   for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
9586        DTN != HeaderDTN; DTN = DTN->getIDom()) {
9587     assert(DTN && "should reach the loop header before reaching the root!");
9588 
9589     BasicBlock *BB = DTN->getBlock();
9590     if (isImpliedViaGuard(BB, Pred, LHS, RHS))
9591       return true;
9592 
9593     BasicBlock *PBB = BB->getSinglePredecessor();
9594     if (!PBB)
9595       continue;
9596 
9597     BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
9598     if (!ContinuePredicate || !ContinuePredicate->isConditional())
9599       continue;
9600 
9601     Value *Condition = ContinuePredicate->getCondition();
9602 
9603     // If we have an edge `E` within the loop body that dominates the only
9604     // latch, the condition guarding `E` also guards the backedge.  This
9605     // reasoning works only for loops with a single latch.
9606 
9607     BasicBlockEdge DominatingEdge(PBB, BB);
9608     if (DominatingEdge.isSingleEdge()) {
9609       // We're constructively (and conservatively) enumerating edges within the
9610       // loop body that dominate the latch.  The dominator tree better agree
9611       // with us on this:
9612       assert(DT.dominates(DominatingEdge, Latch) && "should be!");
9613 
9614       if (isImpliedCond(Pred, LHS, RHS, Condition,
9615                         BB != ContinuePredicate->getSuccessor(0)))
9616         return true;
9617     }
9618   }
9619 
9620   return false;
9621 }
9622 
9623 bool
9624 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
9625                                           ICmpInst::Predicate Pred,
9626                                           const SCEV *LHS, const SCEV *RHS) {
9627   // Interpret a null as meaning no loop, where there is obviously no guard
9628   // (interprocedural conditions notwithstanding).
9629   if (!L) return false;
9630 
9631   if (VerifyIR)
9632     assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) &&
9633            "This cannot be done on broken IR!");
9634 
9635   // Both LHS and RHS must be available at loop entry.
9636   assert(isAvailableAtLoopEntry(LHS, L) &&
9637          "LHS is not available at Loop Entry");
9638   assert(isAvailableAtLoopEntry(RHS, L) &&
9639          "RHS is not available at Loop Entry");
9640 
9641   if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
9642     return true;
9643 
9644   // If we cannot prove strict comparison (e.g. a > b), maybe we can prove
9645   // the facts (a >= b && a != b) separately. A typical situation is when the
9646   // non-strict comparison is known from ranges and non-equality is known from
9647   // dominating predicates. If we are proving strict comparison, we always try
9648   // to prove non-equality and non-strict comparison separately.
9649   auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred);
9650   const bool ProvingStrictComparison = (Pred != NonStrictPredicate);
9651   bool ProvedNonStrictComparison = false;
9652   bool ProvedNonEquality = false;
9653 
9654   if (ProvingStrictComparison) {
9655     ProvedNonStrictComparison =
9656         isKnownViaNonRecursiveReasoning(NonStrictPredicate, LHS, RHS);
9657     ProvedNonEquality =
9658         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, LHS, RHS);
9659     if (ProvedNonStrictComparison && ProvedNonEquality)
9660       return true;
9661   }
9662 
9663   // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard.
9664   auto ProveViaGuard = [&](BasicBlock *Block) {
9665     if (isImpliedViaGuard(Block, Pred, LHS, RHS))
9666       return true;
9667     if (ProvingStrictComparison) {
9668       if (!ProvedNonStrictComparison)
9669         ProvedNonStrictComparison =
9670             isImpliedViaGuard(Block, NonStrictPredicate, LHS, RHS);
9671       if (!ProvedNonEquality)
9672         ProvedNonEquality =
9673             isImpliedViaGuard(Block, ICmpInst::ICMP_NE, LHS, RHS);
9674       if (ProvedNonStrictComparison && ProvedNonEquality)
9675         return true;
9676     }
9677     return false;
9678   };
9679 
9680   // Try to prove (Pred, LHS, RHS) using isImpliedCond.
9681   auto ProveViaCond = [&](Value *Condition, bool Inverse) {
9682     if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse))
9683       return true;
9684     if (ProvingStrictComparison) {
9685       if (!ProvedNonStrictComparison)
9686         ProvedNonStrictComparison =
9687             isImpliedCond(NonStrictPredicate, LHS, RHS, Condition, Inverse);
9688       if (!ProvedNonEquality)
9689         ProvedNonEquality =
9690             isImpliedCond(ICmpInst::ICMP_NE, LHS, RHS, Condition, Inverse);
9691       if (ProvedNonStrictComparison && ProvedNonEquality)
9692         return true;
9693     }
9694     return false;
9695   };
9696 
9697   // Starting at the loop predecessor, climb up the predecessor chain, as long
9698   // as there are predecessors that can be found that have unique successors
9699   // leading to the original header.
9700   for (std::pair<BasicBlock *, BasicBlock *>
9701          Pair(L->getLoopPredecessor(), L->getHeader());
9702        Pair.first;
9703        Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
9704 
9705     if (ProveViaGuard(Pair.first))
9706       return true;
9707 
9708     BranchInst *LoopEntryPredicate =
9709       dyn_cast<BranchInst>(Pair.first->getTerminator());
9710     if (!LoopEntryPredicate ||
9711         LoopEntryPredicate->isUnconditional())
9712       continue;
9713 
9714     if (ProveViaCond(LoopEntryPredicate->getCondition(),
9715                      LoopEntryPredicate->getSuccessor(0) != Pair.second))
9716       return true;
9717   }
9718 
9719   // Check conditions due to any @llvm.assume intrinsics.
9720   for (auto &AssumeVH : AC.assumptions()) {
9721     if (!AssumeVH)
9722       continue;
9723     auto *CI = cast<CallInst>(AssumeVH);
9724     if (!DT.dominates(CI, L->getHeader()))
9725       continue;
9726 
9727     if (ProveViaCond(CI->getArgOperand(0), false))
9728       return true;
9729   }
9730 
9731   return false;
9732 }
9733 
9734 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
9735                                     const SCEV *LHS, const SCEV *RHS,
9736                                     Value *FoundCondValue,
9737                                     bool Inverse) {
9738   if (!PendingLoopPredicates.insert(FoundCondValue).second)
9739     return false;
9740 
9741   auto ClearOnExit =
9742       make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
9743 
9744   // Recursively handle And and Or conditions.
9745   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
9746     if (BO->getOpcode() == Instruction::And) {
9747       if (!Inverse)
9748         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
9749                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
9750     } else if (BO->getOpcode() == Instruction::Or) {
9751       if (Inverse)
9752         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
9753                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
9754     }
9755   }
9756 
9757   ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
9758   if (!ICI) return false;
9759 
9760   // Now that we found a conditional branch that dominates the loop or controls
9761   // the loop latch. Check to see if it is the comparison we are looking for.
9762   ICmpInst::Predicate FoundPred;
9763   if (Inverse)
9764     FoundPred = ICI->getInversePredicate();
9765   else
9766     FoundPred = ICI->getPredicate();
9767 
9768   const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
9769   const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
9770 
9771   return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS);
9772 }
9773 
9774 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
9775                                     const SCEV *RHS,
9776                                     ICmpInst::Predicate FoundPred,
9777                                     const SCEV *FoundLHS,
9778                                     const SCEV *FoundRHS) {
9779   // Balance the types.
9780   if (getTypeSizeInBits(LHS->getType()) <
9781       getTypeSizeInBits(FoundLHS->getType())) {
9782     if (CmpInst::isSigned(Pred)) {
9783       LHS = getSignExtendExpr(LHS, FoundLHS->getType());
9784       RHS = getSignExtendExpr(RHS, FoundLHS->getType());
9785     } else {
9786       LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
9787       RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
9788     }
9789   } else if (getTypeSizeInBits(LHS->getType()) >
9790       getTypeSizeInBits(FoundLHS->getType())) {
9791     if (CmpInst::isSigned(FoundPred)) {
9792       FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
9793       FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
9794     } else {
9795       FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
9796       FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
9797     }
9798   }
9799 
9800   // Canonicalize the query to match the way instcombine will have
9801   // canonicalized the comparison.
9802   if (SimplifyICmpOperands(Pred, LHS, RHS))
9803     if (LHS == RHS)
9804       return CmpInst::isTrueWhenEqual(Pred);
9805   if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
9806     if (FoundLHS == FoundRHS)
9807       return CmpInst::isFalseWhenEqual(FoundPred);
9808 
9809   // Check to see if we can make the LHS or RHS match.
9810   if (LHS == FoundRHS || RHS == FoundLHS) {
9811     if (isa<SCEVConstant>(RHS)) {
9812       std::swap(FoundLHS, FoundRHS);
9813       FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
9814     } else {
9815       std::swap(LHS, RHS);
9816       Pred = ICmpInst::getSwappedPredicate(Pred);
9817     }
9818   }
9819 
9820   // Check whether the found predicate is the same as the desired predicate.
9821   if (FoundPred == Pred)
9822     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
9823 
9824   // Check whether swapping the found predicate makes it the same as the
9825   // desired predicate.
9826   if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
9827     if (isa<SCEVConstant>(RHS))
9828       return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
9829     else
9830       return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
9831                                    RHS, LHS, FoundLHS, FoundRHS);
9832   }
9833 
9834   // Unsigned comparison is the same as signed comparison when both the operands
9835   // are non-negative.
9836   if (CmpInst::isUnsigned(FoundPred) &&
9837       CmpInst::getSignedPredicate(FoundPred) == Pred &&
9838       isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS))
9839     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
9840 
9841   // Check if we can make progress by sharpening ranges.
9842   if (FoundPred == ICmpInst::ICMP_NE &&
9843       (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
9844 
9845     const SCEVConstant *C = nullptr;
9846     const SCEV *V = nullptr;
9847 
9848     if (isa<SCEVConstant>(FoundLHS)) {
9849       C = cast<SCEVConstant>(FoundLHS);
9850       V = FoundRHS;
9851     } else {
9852       C = cast<SCEVConstant>(FoundRHS);
9853       V = FoundLHS;
9854     }
9855 
9856     // The guarding predicate tells us that C != V. If the known range
9857     // of V is [C, t), we can sharpen the range to [C + 1, t).  The
9858     // range we consider has to correspond to same signedness as the
9859     // predicate we're interested in folding.
9860 
9861     APInt Min = ICmpInst::isSigned(Pred) ?
9862         getSignedRangeMin(V) : getUnsignedRangeMin(V);
9863 
9864     if (Min == C->getAPInt()) {
9865       // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
9866       // This is true even if (Min + 1) wraps around -- in case of
9867       // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
9868 
9869       APInt SharperMin = Min + 1;
9870 
9871       switch (Pred) {
9872         case ICmpInst::ICMP_SGE:
9873         case ICmpInst::ICMP_UGE:
9874           // We know V `Pred` SharperMin.  If this implies LHS `Pred`
9875           // RHS, we're done.
9876           if (isImpliedCondOperands(Pred, LHS, RHS, V,
9877                                     getConstant(SharperMin)))
9878             return true;
9879           LLVM_FALLTHROUGH;
9880 
9881         case ICmpInst::ICMP_SGT:
9882         case ICmpInst::ICMP_UGT:
9883           // We know from the range information that (V `Pred` Min ||
9884           // V == Min).  We know from the guarding condition that !(V
9885           // == Min).  This gives us
9886           //
9887           //       V `Pred` Min || V == Min && !(V == Min)
9888           //   =>  V `Pred` Min
9889           //
9890           // If V `Pred` Min implies LHS `Pred` RHS, we're done.
9891 
9892           if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min)))
9893             return true;
9894           LLVM_FALLTHROUGH;
9895 
9896         default:
9897           // No change
9898           break;
9899       }
9900     }
9901   }
9902 
9903   // Check whether the actual condition is beyond sufficient.
9904   if (FoundPred == ICmpInst::ICMP_EQ)
9905     if (ICmpInst::isTrueWhenEqual(Pred))
9906       if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
9907         return true;
9908   if (Pred == ICmpInst::ICMP_NE)
9909     if (!ICmpInst::isTrueWhenEqual(FoundPred))
9910       if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
9911         return true;
9912 
9913   // Otherwise assume the worst.
9914   return false;
9915 }
9916 
9917 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
9918                                      const SCEV *&L, const SCEV *&R,
9919                                      SCEV::NoWrapFlags &Flags) {
9920   const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
9921   if (!AE || AE->getNumOperands() != 2)
9922     return false;
9923 
9924   L = AE->getOperand(0);
9925   R = AE->getOperand(1);
9926   Flags = AE->getNoWrapFlags();
9927   return true;
9928 }
9929 
9930 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More,
9931                                                            const SCEV *Less) {
9932   // We avoid subtracting expressions here because this function is usually
9933   // fairly deep in the call stack (i.e. is called many times).
9934 
9935   // X - X = 0.
9936   if (More == Less)
9937     return APInt(getTypeSizeInBits(More->getType()), 0);
9938 
9939   if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
9940     const auto *LAR = cast<SCEVAddRecExpr>(Less);
9941     const auto *MAR = cast<SCEVAddRecExpr>(More);
9942 
9943     if (LAR->getLoop() != MAR->getLoop())
9944       return None;
9945 
9946     // We look at affine expressions only; not for correctness but to keep
9947     // getStepRecurrence cheap.
9948     if (!LAR->isAffine() || !MAR->isAffine())
9949       return None;
9950 
9951     if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
9952       return None;
9953 
9954     Less = LAR->getStart();
9955     More = MAR->getStart();
9956 
9957     // fall through
9958   }
9959 
9960   if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
9961     const auto &M = cast<SCEVConstant>(More)->getAPInt();
9962     const auto &L = cast<SCEVConstant>(Less)->getAPInt();
9963     return M - L;
9964   }
9965 
9966   SCEV::NoWrapFlags Flags;
9967   const SCEV *LLess = nullptr, *RLess = nullptr;
9968   const SCEV *LMore = nullptr, *RMore = nullptr;
9969   const SCEVConstant *C1 = nullptr, *C2 = nullptr;
9970   // Compare (X + C1) vs X.
9971   if (splitBinaryAdd(Less, LLess, RLess, Flags))
9972     if ((C1 = dyn_cast<SCEVConstant>(LLess)))
9973       if (RLess == More)
9974         return -(C1->getAPInt());
9975 
9976   // Compare X vs (X + C2).
9977   if (splitBinaryAdd(More, LMore, RMore, Flags))
9978     if ((C2 = dyn_cast<SCEVConstant>(LMore)))
9979       if (RMore == Less)
9980         return C2->getAPInt();
9981 
9982   // Compare (X + C1) vs (X + C2).
9983   if (C1 && C2 && RLess == RMore)
9984     return C2->getAPInt() - C1->getAPInt();
9985 
9986   return None;
9987 }
9988 
9989 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
9990     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
9991     const SCEV *FoundLHS, const SCEV *FoundRHS) {
9992   if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
9993     return false;
9994 
9995   const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
9996   if (!AddRecLHS)
9997     return false;
9998 
9999   const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
10000   if (!AddRecFoundLHS)
10001     return false;
10002 
10003   // We'd like to let SCEV reason about control dependencies, so we constrain
10004   // both the inequalities to be about add recurrences on the same loop.  This
10005   // way we can use isLoopEntryGuardedByCond later.
10006 
10007   const Loop *L = AddRecFoundLHS->getLoop();
10008   if (L != AddRecLHS->getLoop())
10009     return false;
10010 
10011   //  FoundLHS u< FoundRHS u< -C =>  (FoundLHS + C) u< (FoundRHS + C) ... (1)
10012   //
10013   //  FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
10014   //                                                                  ... (2)
10015   //
10016   // Informal proof for (2), assuming (1) [*]:
10017   //
10018   // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
10019   //
10020   // Then
10021   //
10022   //       FoundLHS s< FoundRHS s< INT_MIN - C
10023   // <=>  (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C   [ using (3) ]
10024   // <=>  (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
10025   // <=>  (FoundLHS + INT_MIN + C + INT_MIN) s<
10026   //                        (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
10027   // <=>  FoundLHS + C s< FoundRHS + C
10028   //
10029   // [*]: (1) can be proved by ruling out overflow.
10030   //
10031   // [**]: This can be proved by analyzing all the four possibilities:
10032   //    (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
10033   //    (A s>= 0, B s>= 0).
10034   //
10035   // Note:
10036   // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
10037   // will not sign underflow.  For instance, say FoundLHS = (i8 -128), FoundRHS
10038   // = (i8 -127) and C = (i8 -100).  Then INT_MIN - C = (i8 -28), and FoundRHS
10039   // s< (INT_MIN - C).  Lack of sign overflow / underflow in "FoundRHS + C" is
10040   // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
10041   // C)".
10042 
10043   Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
10044   Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
10045   if (!LDiff || !RDiff || *LDiff != *RDiff)
10046     return false;
10047 
10048   if (LDiff->isMinValue())
10049     return true;
10050 
10051   APInt FoundRHSLimit;
10052 
10053   if (Pred == CmpInst::ICMP_ULT) {
10054     FoundRHSLimit = -(*RDiff);
10055   } else {
10056     assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
10057     FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
10058   }
10059 
10060   // Try to prove (1) or (2), as needed.
10061   return isAvailableAtLoopEntry(FoundRHS, L) &&
10062          isLoopEntryGuardedByCond(L, Pred, FoundRHS,
10063                                   getConstant(FoundRHSLimit));
10064 }
10065 
10066 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred,
10067                                         const SCEV *LHS, const SCEV *RHS,
10068                                         const SCEV *FoundLHS,
10069                                         const SCEV *FoundRHS, unsigned Depth) {
10070   const PHINode *LPhi = nullptr, *RPhi = nullptr;
10071 
10072   auto ClearOnExit = make_scope_exit([&]() {
10073     if (LPhi) {
10074       bool Erased = PendingMerges.erase(LPhi);
10075       assert(Erased && "Failed to erase LPhi!");
10076       (void)Erased;
10077     }
10078     if (RPhi) {
10079       bool Erased = PendingMerges.erase(RPhi);
10080       assert(Erased && "Failed to erase RPhi!");
10081       (void)Erased;
10082     }
10083   });
10084 
10085   // Find respective Phis and check that they are not being pending.
10086   if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS))
10087     if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) {
10088       if (!PendingMerges.insert(Phi).second)
10089         return false;
10090       LPhi = Phi;
10091     }
10092   if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS))
10093     if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) {
10094       // If we detect a loop of Phi nodes being processed by this method, for
10095       // example:
10096       //
10097       //   %a = phi i32 [ %some1, %preheader ], [ %b, %latch ]
10098       //   %b = phi i32 [ %some2, %preheader ], [ %a, %latch ]
10099       //
10100       // we don't want to deal with a case that complex, so return conservative
10101       // answer false.
10102       if (!PendingMerges.insert(Phi).second)
10103         return false;
10104       RPhi = Phi;
10105     }
10106 
10107   // If none of LHS, RHS is a Phi, nothing to do here.
10108   if (!LPhi && !RPhi)
10109     return false;
10110 
10111   // If there is a SCEVUnknown Phi we are interested in, make it left.
10112   if (!LPhi) {
10113     std::swap(LHS, RHS);
10114     std::swap(FoundLHS, FoundRHS);
10115     std::swap(LPhi, RPhi);
10116     Pred = ICmpInst::getSwappedPredicate(Pred);
10117   }
10118 
10119   assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!");
10120   const BasicBlock *LBB = LPhi->getParent();
10121   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
10122 
10123   auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) {
10124     return isKnownViaNonRecursiveReasoning(Pred, S1, S2) ||
10125            isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) ||
10126            isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth);
10127   };
10128 
10129   if (RPhi && RPhi->getParent() == LBB) {
10130     // Case one: RHS is also a SCEVUnknown Phi from the same basic block.
10131     // If we compare two Phis from the same block, and for each entry block
10132     // the predicate is true for incoming values from this block, then the
10133     // predicate is also true for the Phis.
10134     for (const BasicBlock *IncBB : predecessors(LBB)) {
10135       const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
10136       const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB));
10137       if (!ProvedEasily(L, R))
10138         return false;
10139     }
10140   } else if (RAR && RAR->getLoop()->getHeader() == LBB) {
10141     // Case two: RHS is also a Phi from the same basic block, and it is an
10142     // AddRec. It means that there is a loop which has both AddRec and Unknown
10143     // PHIs, for it we can compare incoming values of AddRec from above the loop
10144     // and latch with their respective incoming values of LPhi.
10145     // TODO: Generalize to handle loops with many inputs in a header.
10146     if (LPhi->getNumIncomingValues() != 2) return false;
10147 
10148     auto *RLoop = RAR->getLoop();
10149     auto *Predecessor = RLoop->getLoopPredecessor();
10150     assert(Predecessor && "Loop with AddRec with no predecessor?");
10151     const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor));
10152     if (!ProvedEasily(L1, RAR->getStart()))
10153       return false;
10154     auto *Latch = RLoop->getLoopLatch();
10155     assert(Latch && "Loop with AddRec with no latch?");
10156     const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch));
10157     if (!ProvedEasily(L2, RAR->getPostIncExpr(*this)))
10158       return false;
10159   } else {
10160     // In all other cases go over inputs of LHS and compare each of them to RHS,
10161     // the predicate is true for (LHS, RHS) if it is true for all such pairs.
10162     // At this point RHS is either a non-Phi, or it is a Phi from some block
10163     // different from LBB.
10164     for (const BasicBlock *IncBB : predecessors(LBB)) {
10165       // Check that RHS is available in this block.
10166       if (!dominates(RHS, IncBB))
10167         return false;
10168       const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
10169       if (!ProvedEasily(L, RHS))
10170         return false;
10171     }
10172   }
10173   return true;
10174 }
10175 
10176 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
10177                                             const SCEV *LHS, const SCEV *RHS,
10178                                             const SCEV *FoundLHS,
10179                                             const SCEV *FoundRHS) {
10180   if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
10181     return true;
10182 
10183   if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
10184     return true;
10185 
10186   return isImpliedCondOperandsHelper(Pred, LHS, RHS,
10187                                      FoundLHS, FoundRHS) ||
10188          // ~x < ~y --> x > y
10189          isImpliedCondOperandsHelper(Pred, LHS, RHS,
10190                                      getNotSCEV(FoundRHS),
10191                                      getNotSCEV(FoundLHS));
10192 }
10193 
10194 /// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values?
10195 template <typename MinMaxExprType>
10196 static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr,
10197                                  const SCEV *Candidate) {
10198   const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr);
10199   if (!MinMaxExpr)
10200     return false;
10201 
10202   return find(MinMaxExpr->operands(), Candidate) != MinMaxExpr->op_end();
10203 }
10204 
10205 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
10206                                            ICmpInst::Predicate Pred,
10207                                            const SCEV *LHS, const SCEV *RHS) {
10208   // If both sides are affine addrecs for the same loop, with equal
10209   // steps, and we know the recurrences don't wrap, then we only
10210   // need to check the predicate on the starting values.
10211 
10212   if (!ICmpInst::isRelational(Pred))
10213     return false;
10214 
10215   const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
10216   if (!LAR)
10217     return false;
10218   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
10219   if (!RAR)
10220     return false;
10221   if (LAR->getLoop() != RAR->getLoop())
10222     return false;
10223   if (!LAR->isAffine() || !RAR->isAffine())
10224     return false;
10225 
10226   if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
10227     return false;
10228 
10229   SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
10230                          SCEV::FlagNSW : SCEV::FlagNUW;
10231   if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
10232     return false;
10233 
10234   return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
10235 }
10236 
10237 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
10238 /// expression?
10239 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
10240                                         ICmpInst::Predicate Pred,
10241                                         const SCEV *LHS, const SCEV *RHS) {
10242   switch (Pred) {
10243   default:
10244     return false;
10245 
10246   case ICmpInst::ICMP_SGE:
10247     std::swap(LHS, RHS);
10248     LLVM_FALLTHROUGH;
10249   case ICmpInst::ICMP_SLE:
10250     return
10251         // min(A, ...) <= A
10252         IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) ||
10253         // A <= max(A, ...)
10254         IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
10255 
10256   case ICmpInst::ICMP_UGE:
10257     std::swap(LHS, RHS);
10258     LLVM_FALLTHROUGH;
10259   case ICmpInst::ICMP_ULE:
10260     return
10261         // min(A, ...) <= A
10262         IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) ||
10263         // A <= max(A, ...)
10264         IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
10265   }
10266 
10267   llvm_unreachable("covered switch fell through?!");
10268 }
10269 
10270 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred,
10271                                              const SCEV *LHS, const SCEV *RHS,
10272                                              const SCEV *FoundLHS,
10273                                              const SCEV *FoundRHS,
10274                                              unsigned Depth) {
10275   assert(getTypeSizeInBits(LHS->getType()) ==
10276              getTypeSizeInBits(RHS->getType()) &&
10277          "LHS and RHS have different sizes?");
10278   assert(getTypeSizeInBits(FoundLHS->getType()) ==
10279              getTypeSizeInBits(FoundRHS->getType()) &&
10280          "FoundLHS and FoundRHS have different sizes?");
10281   // We want to avoid hurting the compile time with analysis of too big trees.
10282   if (Depth > MaxSCEVOperationsImplicationDepth)
10283     return false;
10284   // We only want to work with ICMP_SGT comparison so far.
10285   // TODO: Extend to ICMP_UGT?
10286   if (Pred == ICmpInst::ICMP_SLT) {
10287     Pred = ICmpInst::ICMP_SGT;
10288     std::swap(LHS, RHS);
10289     std::swap(FoundLHS, FoundRHS);
10290   }
10291   if (Pred != ICmpInst::ICMP_SGT)
10292     return false;
10293 
10294   auto GetOpFromSExt = [&](const SCEV *S) {
10295     if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
10296       return Ext->getOperand();
10297     // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
10298     // the constant in some cases.
10299     return S;
10300   };
10301 
10302   // Acquire values from extensions.
10303   auto *OrigLHS = LHS;
10304   auto *OrigFoundLHS = FoundLHS;
10305   LHS = GetOpFromSExt(LHS);
10306   FoundLHS = GetOpFromSExt(FoundLHS);
10307 
10308   // Is the SGT predicate can be proved trivially or using the found context.
10309   auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
10310     return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
10311            isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
10312                                   FoundRHS, Depth + 1);
10313   };
10314 
10315   if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
10316     // We want to avoid creation of any new non-constant SCEV. Since we are
10317     // going to compare the operands to RHS, we should be certain that we don't
10318     // need any size extensions for this. So let's decline all cases when the
10319     // sizes of types of LHS and RHS do not match.
10320     // TODO: Maybe try to get RHS from sext to catch more cases?
10321     if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType()))
10322       return false;
10323 
10324     // Should not overflow.
10325     if (!LHSAddExpr->hasNoSignedWrap())
10326       return false;
10327 
10328     auto *LL = LHSAddExpr->getOperand(0);
10329     auto *LR = LHSAddExpr->getOperand(1);
10330     auto *MinusOne = getNegativeSCEV(getOne(RHS->getType()));
10331 
10332     // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
10333     auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
10334       return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
10335     };
10336     // Try to prove the following rule:
10337     // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
10338     // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
10339     if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
10340       return true;
10341   } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
10342     Value *LL, *LR;
10343     // FIXME: Once we have SDiv implemented, we can get rid of this matching.
10344 
10345     using namespace llvm::PatternMatch;
10346 
10347     if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
10348       // Rules for division.
10349       // We are going to perform some comparisons with Denominator and its
10350       // derivative expressions. In general case, creating a SCEV for it may
10351       // lead to a complex analysis of the entire graph, and in particular it
10352       // can request trip count recalculation for the same loop. This would
10353       // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
10354       // this, we only want to create SCEVs that are constants in this section.
10355       // So we bail if Denominator is not a constant.
10356       if (!isa<ConstantInt>(LR))
10357         return false;
10358 
10359       auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
10360 
10361       // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
10362       // then a SCEV for the numerator already exists and matches with FoundLHS.
10363       auto *Numerator = getExistingSCEV(LL);
10364       if (!Numerator || Numerator->getType() != FoundLHS->getType())
10365         return false;
10366 
10367       // Make sure that the numerator matches with FoundLHS and the denominator
10368       // is positive.
10369       if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
10370         return false;
10371 
10372       auto *DTy = Denominator->getType();
10373       auto *FRHSTy = FoundRHS->getType();
10374       if (DTy->isPointerTy() != FRHSTy->isPointerTy())
10375         // One of types is a pointer and another one is not. We cannot extend
10376         // them properly to a wider type, so let us just reject this case.
10377         // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
10378         // to avoid this check.
10379         return false;
10380 
10381       // Given that:
10382       // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
10383       auto *WTy = getWiderType(DTy, FRHSTy);
10384       auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
10385       auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
10386 
10387       // Try to prove the following rule:
10388       // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
10389       // For example, given that FoundLHS > 2. It means that FoundLHS is at
10390       // least 3. If we divide it by Denominator < 4, we will have at least 1.
10391       auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
10392       if (isKnownNonPositive(RHS) &&
10393           IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
10394         return true;
10395 
10396       // Try to prove the following rule:
10397       // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
10398       // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
10399       // If we divide it by Denominator > 2, then:
10400       // 1. If FoundLHS is negative, then the result is 0.
10401       // 2. If FoundLHS is non-negative, then the result is non-negative.
10402       // Anyways, the result is non-negative.
10403       auto *MinusOne = getNegativeSCEV(getOne(WTy));
10404       auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
10405       if (isKnownNegative(RHS) &&
10406           IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
10407         return true;
10408     }
10409   }
10410 
10411   // If our expression contained SCEVUnknown Phis, and we split it down and now
10412   // need to prove something for them, try to prove the predicate for every
10413   // possible incoming values of those Phis.
10414   if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1))
10415     return true;
10416 
10417   return false;
10418 }
10419 
10420 static bool isKnownPredicateExtendIdiom(ICmpInst::Predicate Pred,
10421                                         const SCEV *LHS, const SCEV *RHS) {
10422   // zext x u<= sext x, sext x s<= zext x
10423   switch (Pred) {
10424   case ICmpInst::ICMP_SGE:
10425     std::swap(LHS, RHS);
10426     LLVM_FALLTHROUGH;
10427   case ICmpInst::ICMP_SLE: {
10428     // If operand >=s 0 then ZExt == SExt.  If operand <s 0 then SExt <s ZExt.
10429     const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(LHS);
10430     const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(RHS);
10431     if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand())
10432       return true;
10433     break;
10434   }
10435   case ICmpInst::ICMP_UGE:
10436     std::swap(LHS, RHS);
10437     LLVM_FALLTHROUGH;
10438   case ICmpInst::ICMP_ULE: {
10439     // If operand >=s 0 then ZExt == SExt.  If operand <s 0 then ZExt <u SExt.
10440     const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS);
10441     const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(RHS);
10442     if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand())
10443       return true;
10444     break;
10445   }
10446   default:
10447     break;
10448   };
10449   return false;
10450 }
10451 
10452 bool
10453 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred,
10454                                            const SCEV *LHS, const SCEV *RHS) {
10455   return isKnownPredicateExtendIdiom(Pred, LHS, RHS) ||
10456          isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
10457          IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
10458          IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
10459          isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
10460 }
10461 
10462 bool
10463 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
10464                                              const SCEV *LHS, const SCEV *RHS,
10465                                              const SCEV *FoundLHS,
10466                                              const SCEV *FoundRHS) {
10467   switch (Pred) {
10468   default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
10469   case ICmpInst::ICMP_EQ:
10470   case ICmpInst::ICMP_NE:
10471     if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
10472       return true;
10473     break;
10474   case ICmpInst::ICMP_SLT:
10475   case ICmpInst::ICMP_SLE:
10476     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
10477         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS))
10478       return true;
10479     break;
10480   case ICmpInst::ICMP_SGT:
10481   case ICmpInst::ICMP_SGE:
10482     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
10483         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS))
10484       return true;
10485     break;
10486   case ICmpInst::ICMP_ULT:
10487   case ICmpInst::ICMP_ULE:
10488     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
10489         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS))
10490       return true;
10491     break;
10492   case ICmpInst::ICMP_UGT:
10493   case ICmpInst::ICMP_UGE:
10494     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
10495         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS))
10496       return true;
10497     break;
10498   }
10499 
10500   // Maybe it can be proved via operations?
10501   if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
10502     return true;
10503 
10504   return false;
10505 }
10506 
10507 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
10508                                                      const SCEV *LHS,
10509                                                      const SCEV *RHS,
10510                                                      const SCEV *FoundLHS,
10511                                                      const SCEV *FoundRHS) {
10512   if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
10513     // The restriction on `FoundRHS` be lifted easily -- it exists only to
10514     // reduce the compile time impact of this optimization.
10515     return false;
10516 
10517   Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
10518   if (!Addend)
10519     return false;
10520 
10521   const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
10522 
10523   // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
10524   // antecedent "`FoundLHS` `Pred` `FoundRHS`".
10525   ConstantRange FoundLHSRange =
10526       ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS);
10527 
10528   // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
10529   ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
10530 
10531   // We can also compute the range of values for `LHS` that satisfy the
10532   // consequent, "`LHS` `Pred` `RHS`":
10533   const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
10534   ConstantRange SatisfyingLHSRange =
10535       ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS);
10536 
10537   // The antecedent implies the consequent if every value of `LHS` that
10538   // satisfies the antecedent also satisfies the consequent.
10539   return SatisfyingLHSRange.contains(LHSRange);
10540 }
10541 
10542 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
10543                                          bool IsSigned, bool NoWrap) {
10544   assert(isKnownPositive(Stride) && "Positive stride expected!");
10545 
10546   if (NoWrap) return false;
10547 
10548   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
10549   const SCEV *One = getOne(Stride->getType());
10550 
10551   if (IsSigned) {
10552     APInt MaxRHS = getSignedRangeMax(RHS);
10553     APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
10554     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
10555 
10556     // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
10557     return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS);
10558   }
10559 
10560   APInt MaxRHS = getUnsignedRangeMax(RHS);
10561   APInt MaxValue = APInt::getMaxValue(BitWidth);
10562   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
10563 
10564   // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
10565   return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS);
10566 }
10567 
10568 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
10569                                          bool IsSigned, bool NoWrap) {
10570   if (NoWrap) return false;
10571 
10572   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
10573   const SCEV *One = getOne(Stride->getType());
10574 
10575   if (IsSigned) {
10576     APInt MinRHS = getSignedRangeMin(RHS);
10577     APInt MinValue = APInt::getSignedMinValue(BitWidth);
10578     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
10579 
10580     // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
10581     return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS);
10582   }
10583 
10584   APInt MinRHS = getUnsignedRangeMin(RHS);
10585   APInt MinValue = APInt::getMinValue(BitWidth);
10586   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
10587 
10588   // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
10589   return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS);
10590 }
10591 
10592 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step,
10593                                             bool Equality) {
10594   const SCEV *One = getOne(Step->getType());
10595   Delta = Equality ? getAddExpr(Delta, Step)
10596                    : getAddExpr(Delta, getMinusSCEV(Step, One));
10597   return getUDivExpr(Delta, Step);
10598 }
10599 
10600 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start,
10601                                                     const SCEV *Stride,
10602                                                     const SCEV *End,
10603                                                     unsigned BitWidth,
10604                                                     bool IsSigned) {
10605 
10606   assert(!isKnownNonPositive(Stride) &&
10607          "Stride is expected strictly positive!");
10608   // Calculate the maximum backedge count based on the range of values
10609   // permitted by Start, End, and Stride.
10610   const SCEV *MaxBECount;
10611   APInt MinStart =
10612       IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start);
10613 
10614   APInt StrideForMaxBECount =
10615       IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride);
10616 
10617   // We already know that the stride is positive, so we paper over conservatism
10618   // in our range computation by forcing StrideForMaxBECount to be at least one.
10619   // In theory this is unnecessary, but we expect MaxBECount to be a
10620   // SCEVConstant, and (udiv <constant> 0) is not constant folded by SCEV (there
10621   // is nothing to constant fold it to).
10622   APInt One(BitWidth, 1, IsSigned);
10623   StrideForMaxBECount = APIntOps::smax(One, StrideForMaxBECount);
10624 
10625   APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth)
10626                             : APInt::getMaxValue(BitWidth);
10627   APInt Limit = MaxValue - (StrideForMaxBECount - 1);
10628 
10629   // Although End can be a MAX expression we estimate MaxEnd considering only
10630   // the case End = RHS of the loop termination condition. This is safe because
10631   // in the other case (End - Start) is zero, leading to a zero maximum backedge
10632   // taken count.
10633   APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit)
10634                           : APIntOps::umin(getUnsignedRangeMax(End), Limit);
10635 
10636   MaxBECount = computeBECount(getConstant(MaxEnd - MinStart) /* Delta */,
10637                               getConstant(StrideForMaxBECount) /* Step */,
10638                               false /* Equality */);
10639 
10640   return MaxBECount;
10641 }
10642 
10643 ScalarEvolution::ExitLimit
10644 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
10645                                   const Loop *L, bool IsSigned,
10646                                   bool ControlsExit, bool AllowPredicates) {
10647   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
10648 
10649   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
10650   bool PredicatedIV = false;
10651 
10652   if (!IV && AllowPredicates) {
10653     // Try to make this an AddRec using runtime tests, in the first X
10654     // iterations of this loop, where X is the SCEV expression found by the
10655     // algorithm below.
10656     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
10657     PredicatedIV = true;
10658   }
10659 
10660   // Avoid weird loops
10661   if (!IV || IV->getLoop() != L || !IV->isAffine())
10662     return getCouldNotCompute();
10663 
10664   bool NoWrap = ControlsExit &&
10665                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
10666 
10667   const SCEV *Stride = IV->getStepRecurrence(*this);
10668 
10669   bool PositiveStride = isKnownPositive(Stride);
10670 
10671   // Avoid negative or zero stride values.
10672   if (!PositiveStride) {
10673     // We can compute the correct backedge taken count for loops with unknown
10674     // strides if we can prove that the loop is not an infinite loop with side
10675     // effects. Here's the loop structure we are trying to handle -
10676     //
10677     // i = start
10678     // do {
10679     //   A[i] = i;
10680     //   i += s;
10681     // } while (i < end);
10682     //
10683     // The backedge taken count for such loops is evaluated as -
10684     // (max(end, start + stride) - start - 1) /u stride
10685     //
10686     // The additional preconditions that we need to check to prove correctness
10687     // of the above formula is as follows -
10688     //
10689     // a) IV is either nuw or nsw depending upon signedness (indicated by the
10690     //    NoWrap flag).
10691     // b) loop is single exit with no side effects.
10692     //
10693     //
10694     // Precondition a) implies that if the stride is negative, this is a single
10695     // trip loop. The backedge taken count formula reduces to zero in this case.
10696     //
10697     // Precondition b) implies that the unknown stride cannot be zero otherwise
10698     // we have UB.
10699     //
10700     // The positive stride case is the same as isKnownPositive(Stride) returning
10701     // true (original behavior of the function).
10702     //
10703     // We want to make sure that the stride is truly unknown as there are edge
10704     // cases where ScalarEvolution propagates no wrap flags to the
10705     // post-increment/decrement IV even though the increment/decrement operation
10706     // itself is wrapping. The computed backedge taken count may be wrong in
10707     // such cases. This is prevented by checking that the stride is not known to
10708     // be either positive or non-positive. For example, no wrap flags are
10709     // propagated to the post-increment IV of this loop with a trip count of 2 -
10710     //
10711     // unsigned char i;
10712     // for(i=127; i<128; i+=129)
10713     //   A[i] = i;
10714     //
10715     if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) ||
10716         !loopHasNoSideEffects(L))
10717       return getCouldNotCompute();
10718   } else if (!Stride->isOne() &&
10719              doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap))
10720     // Avoid proven overflow cases: this will ensure that the backedge taken
10721     // count will not generate any unsigned overflow. Relaxed no-overflow
10722     // conditions exploit NoWrapFlags, allowing to optimize in presence of
10723     // undefined behaviors like the case of C language.
10724     return getCouldNotCompute();
10725 
10726   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT
10727                                       : ICmpInst::ICMP_ULT;
10728   const SCEV *Start = IV->getStart();
10729   const SCEV *End = RHS;
10730   // When the RHS is not invariant, we do not know the end bound of the loop and
10731   // cannot calculate the ExactBECount needed by ExitLimit. However, we can
10732   // calculate the MaxBECount, given the start, stride and max value for the end
10733   // bound of the loop (RHS), and the fact that IV does not overflow (which is
10734   // checked above).
10735   if (!isLoopInvariant(RHS, L)) {
10736     const SCEV *MaxBECount = computeMaxBECountForLT(
10737         Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
10738     return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount,
10739                      false /*MaxOrZero*/, Predicates);
10740   }
10741   // If the backedge is taken at least once, then it will be taken
10742   // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start
10743   // is the LHS value of the less-than comparison the first time it is evaluated
10744   // and End is the RHS.
10745   const SCEV *BECountIfBackedgeTaken =
10746     computeBECount(getMinusSCEV(End, Start), Stride, false);
10747   // If the loop entry is guarded by the result of the backedge test of the
10748   // first loop iteration, then we know the backedge will be taken at least
10749   // once and so the backedge taken count is as above. If not then we use the
10750   // expression (max(End,Start)-Start)/Stride to describe the backedge count,
10751   // as if the backedge is taken at least once max(End,Start) is End and so the
10752   // result is as above, and if not max(End,Start) is Start so we get a backedge
10753   // count of zero.
10754   const SCEV *BECount;
10755   if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS))
10756     BECount = BECountIfBackedgeTaken;
10757   else {
10758     End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
10759     BECount = computeBECount(getMinusSCEV(End, Start), Stride, false);
10760   }
10761 
10762   const SCEV *MaxBECount;
10763   bool MaxOrZero = false;
10764   if (isa<SCEVConstant>(BECount))
10765     MaxBECount = BECount;
10766   else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) {
10767     // If we know exactly how many times the backedge will be taken if it's
10768     // taken at least once, then the backedge count will either be that or
10769     // zero.
10770     MaxBECount = BECountIfBackedgeTaken;
10771     MaxOrZero = true;
10772   } else {
10773     MaxBECount = computeMaxBECountForLT(
10774         Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
10775   }
10776 
10777   if (isa<SCEVCouldNotCompute>(MaxBECount) &&
10778       !isa<SCEVCouldNotCompute>(BECount))
10779     MaxBECount = getConstant(getUnsignedRangeMax(BECount));
10780 
10781   return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates);
10782 }
10783 
10784 ScalarEvolution::ExitLimit
10785 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
10786                                      const Loop *L, bool IsSigned,
10787                                      bool ControlsExit, bool AllowPredicates) {
10788   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
10789   // We handle only IV > Invariant
10790   if (!isLoopInvariant(RHS, L))
10791     return getCouldNotCompute();
10792 
10793   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
10794   if (!IV && AllowPredicates)
10795     // Try to make this an AddRec using runtime tests, in the first X
10796     // iterations of this loop, where X is the SCEV expression found by the
10797     // algorithm below.
10798     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
10799 
10800   // Avoid weird loops
10801   if (!IV || IV->getLoop() != L || !IV->isAffine())
10802     return getCouldNotCompute();
10803 
10804   bool NoWrap = ControlsExit &&
10805                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
10806 
10807   const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
10808 
10809   // Avoid negative or zero stride values
10810   if (!isKnownPositive(Stride))
10811     return getCouldNotCompute();
10812 
10813   // Avoid proven overflow cases: this will ensure that the backedge taken count
10814   // will not generate any unsigned overflow. Relaxed no-overflow conditions
10815   // exploit NoWrapFlags, allowing to optimize in presence of undefined
10816   // behaviors like the case of C language.
10817   if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap))
10818     return getCouldNotCompute();
10819 
10820   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT
10821                                       : ICmpInst::ICMP_UGT;
10822 
10823   const SCEV *Start = IV->getStart();
10824   const SCEV *End = RHS;
10825   if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS))
10826     End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
10827 
10828   const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false);
10829 
10830   APInt MaxStart = IsSigned ? getSignedRangeMax(Start)
10831                             : getUnsignedRangeMax(Start);
10832 
10833   APInt MinStride = IsSigned ? getSignedRangeMin(Stride)
10834                              : getUnsignedRangeMin(Stride);
10835 
10836   unsigned BitWidth = getTypeSizeInBits(LHS->getType());
10837   APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
10838                          : APInt::getMinValue(BitWidth) + (MinStride - 1);
10839 
10840   // Although End can be a MIN expression we estimate MinEnd considering only
10841   // the case End = RHS. This is safe because in the other case (Start - End)
10842   // is zero, leading to a zero maximum backedge taken count.
10843   APInt MinEnd =
10844     IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit)
10845              : APIntOps::umax(getUnsignedRangeMin(RHS), Limit);
10846 
10847   const SCEV *MaxBECount = isa<SCEVConstant>(BECount)
10848                                ? BECount
10849                                : computeBECount(getConstant(MaxStart - MinEnd),
10850                                                 getConstant(MinStride), false);
10851 
10852   if (isa<SCEVCouldNotCompute>(MaxBECount))
10853     MaxBECount = BECount;
10854 
10855   return ExitLimit(BECount, MaxBECount, false, Predicates);
10856 }
10857 
10858 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range,
10859                                                     ScalarEvolution &SE) const {
10860   if (Range.isFullSet())  // Infinite loop.
10861     return SE.getCouldNotCompute();
10862 
10863   // If the start is a non-zero constant, shift the range to simplify things.
10864   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
10865     if (!SC->getValue()->isZero()) {
10866       SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
10867       Operands[0] = SE.getZero(SC->getType());
10868       const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
10869                                              getNoWrapFlags(FlagNW));
10870       if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
10871         return ShiftedAddRec->getNumIterationsInRange(
10872             Range.subtract(SC->getAPInt()), SE);
10873       // This is strange and shouldn't happen.
10874       return SE.getCouldNotCompute();
10875     }
10876 
10877   // The only time we can solve this is when we have all constant indices.
10878   // Otherwise, we cannot determine the overflow conditions.
10879   if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
10880     return SE.getCouldNotCompute();
10881 
10882   // Okay at this point we know that all elements of the chrec are constants and
10883   // that the start element is zero.
10884 
10885   // First check to see if the range contains zero.  If not, the first
10886   // iteration exits.
10887   unsigned BitWidth = SE.getTypeSizeInBits(getType());
10888   if (!Range.contains(APInt(BitWidth, 0)))
10889     return SE.getZero(getType());
10890 
10891   if (isAffine()) {
10892     // If this is an affine expression then we have this situation:
10893     //   Solve {0,+,A} in Range  ===  Ax in Range
10894 
10895     // We know that zero is in the range.  If A is positive then we know that
10896     // the upper value of the range must be the first possible exit value.
10897     // If A is negative then the lower of the range is the last possible loop
10898     // value.  Also note that we already checked for a full range.
10899     APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
10900     APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower();
10901 
10902     // The exit value should be (End+A)/A.
10903     APInt ExitVal = (End + A).udiv(A);
10904     ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
10905 
10906     // Evaluate at the exit value.  If we really did fall out of the valid
10907     // range, then we computed our trip count, otherwise wrap around or other
10908     // things must have happened.
10909     ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
10910     if (Range.contains(Val->getValue()))
10911       return SE.getCouldNotCompute();  // Something strange happened
10912 
10913     // Ensure that the previous value is in the range.  This is a sanity check.
10914     assert(Range.contains(
10915            EvaluateConstantChrecAtConstant(this,
10916            ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&
10917            "Linear scev computation is off in a bad way!");
10918     return SE.getConstant(ExitValue);
10919   }
10920 
10921   if (isQuadratic()) {
10922     if (auto S = SolveQuadraticAddRecRange(this, Range, SE))
10923       return SE.getConstant(S.getValue());
10924   }
10925 
10926   return SE.getCouldNotCompute();
10927 }
10928 
10929 const SCEVAddRecExpr *
10930 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const {
10931   assert(getNumOperands() > 1 && "AddRec with zero step?");
10932   // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)),
10933   // but in this case we cannot guarantee that the value returned will be an
10934   // AddRec because SCEV does not have a fixed point where it stops
10935   // simplification: it is legal to return ({rec1} + {rec2}). For example, it
10936   // may happen if we reach arithmetic depth limit while simplifying. So we
10937   // construct the returned value explicitly.
10938   SmallVector<const SCEV *, 3> Ops;
10939   // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and
10940   // (this + Step) is {A+B,+,B+C,+...,+,N}.
10941   for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i)
10942     Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1)));
10943   // We know that the last operand is not a constant zero (otherwise it would
10944   // have been popped out earlier). This guarantees us that if the result has
10945   // the same last operand, then it will also not be popped out, meaning that
10946   // the returned value will be an AddRec.
10947   const SCEV *Last = getOperand(getNumOperands() - 1);
10948   assert(!Last->isZero() && "Recurrency with zero step?");
10949   Ops.push_back(Last);
10950   return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(),
10951                                                SCEV::FlagAnyWrap));
10952 }
10953 
10954 // Return true when S contains at least an undef value.
10955 static inline bool containsUndefs(const SCEV *S) {
10956   return SCEVExprContains(S, [](const SCEV *S) {
10957     if (const auto *SU = dyn_cast<SCEVUnknown>(S))
10958       return isa<UndefValue>(SU->getValue());
10959     return false;
10960   });
10961 }
10962 
10963 namespace {
10964 
10965 // Collect all steps of SCEV expressions.
10966 struct SCEVCollectStrides {
10967   ScalarEvolution &SE;
10968   SmallVectorImpl<const SCEV *> &Strides;
10969 
10970   SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S)
10971       : SE(SE), Strides(S) {}
10972 
10973   bool follow(const SCEV *S) {
10974     if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
10975       Strides.push_back(AR->getStepRecurrence(SE));
10976     return true;
10977   }
10978 
10979   bool isDone() const { return false; }
10980 };
10981 
10982 // Collect all SCEVUnknown and SCEVMulExpr expressions.
10983 struct SCEVCollectTerms {
10984   SmallVectorImpl<const SCEV *> &Terms;
10985 
10986   SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) : Terms(T) {}
10987 
10988   bool follow(const SCEV *S) {
10989     if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) ||
10990         isa<SCEVSignExtendExpr>(S)) {
10991       if (!containsUndefs(S))
10992         Terms.push_back(S);
10993 
10994       // Stop recursion: once we collected a term, do not walk its operands.
10995       return false;
10996     }
10997 
10998     // Keep looking.
10999     return true;
11000   }
11001 
11002   bool isDone() const { return false; }
11003 };
11004 
11005 // Check if a SCEV contains an AddRecExpr.
11006 struct SCEVHasAddRec {
11007   bool &ContainsAddRec;
11008 
11009   SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) {
11010     ContainsAddRec = false;
11011   }
11012 
11013   bool follow(const SCEV *S) {
11014     if (isa<SCEVAddRecExpr>(S)) {
11015       ContainsAddRec = true;
11016 
11017       // Stop recursion: once we collected a term, do not walk its operands.
11018       return false;
11019     }
11020 
11021     // Keep looking.
11022     return true;
11023   }
11024 
11025   bool isDone() const { return false; }
11026 };
11027 
11028 // Find factors that are multiplied with an expression that (possibly as a
11029 // subexpression) contains an AddRecExpr. In the expression:
11030 //
11031 //  8 * (100 +  %p * %q * (%a + {0, +, 1}_loop))
11032 //
11033 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)"
11034 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size
11035 // parameters as they form a product with an induction variable.
11036 //
11037 // This collector expects all array size parameters to be in the same MulExpr.
11038 // It might be necessary to later add support for collecting parameters that are
11039 // spread over different nested MulExpr.
11040 struct SCEVCollectAddRecMultiplies {
11041   SmallVectorImpl<const SCEV *> &Terms;
11042   ScalarEvolution &SE;
11043 
11044   SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE)
11045       : Terms(T), SE(SE) {}
11046 
11047   bool follow(const SCEV *S) {
11048     if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) {
11049       bool HasAddRec = false;
11050       SmallVector<const SCEV *, 0> Operands;
11051       for (auto Op : Mul->operands()) {
11052         const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op);
11053         if (Unknown && !isa<CallInst>(Unknown->getValue())) {
11054           Operands.push_back(Op);
11055         } else if (Unknown) {
11056           HasAddRec = true;
11057         } else {
11058           bool ContainsAddRec = false;
11059           SCEVHasAddRec ContiansAddRec(ContainsAddRec);
11060           visitAll(Op, ContiansAddRec);
11061           HasAddRec |= ContainsAddRec;
11062         }
11063       }
11064       if (Operands.size() == 0)
11065         return true;
11066 
11067       if (!HasAddRec)
11068         return false;
11069 
11070       Terms.push_back(SE.getMulExpr(Operands));
11071       // Stop recursion: once we collected a term, do not walk its operands.
11072       return false;
11073     }
11074 
11075     // Keep looking.
11076     return true;
11077   }
11078 
11079   bool isDone() const { return false; }
11080 };
11081 
11082 } // end anonymous namespace
11083 
11084 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in
11085 /// two places:
11086 ///   1) The strides of AddRec expressions.
11087 ///   2) Unknowns that are multiplied with AddRec expressions.
11088 void ScalarEvolution::collectParametricTerms(const SCEV *Expr,
11089     SmallVectorImpl<const SCEV *> &Terms) {
11090   SmallVector<const SCEV *, 4> Strides;
11091   SCEVCollectStrides StrideCollector(*this, Strides);
11092   visitAll(Expr, StrideCollector);
11093 
11094   LLVM_DEBUG({
11095     dbgs() << "Strides:\n";
11096     for (const SCEV *S : Strides)
11097       dbgs() << *S << "\n";
11098   });
11099 
11100   for (const SCEV *S : Strides) {
11101     SCEVCollectTerms TermCollector(Terms);
11102     visitAll(S, TermCollector);
11103   }
11104 
11105   LLVM_DEBUG({
11106     dbgs() << "Terms:\n";
11107     for (const SCEV *T : Terms)
11108       dbgs() << *T << "\n";
11109   });
11110 
11111   SCEVCollectAddRecMultiplies MulCollector(Terms, *this);
11112   visitAll(Expr, MulCollector);
11113 }
11114 
11115 static bool findArrayDimensionsRec(ScalarEvolution &SE,
11116                                    SmallVectorImpl<const SCEV *> &Terms,
11117                                    SmallVectorImpl<const SCEV *> &Sizes) {
11118   int Last = Terms.size() - 1;
11119   const SCEV *Step = Terms[Last];
11120 
11121   // End of recursion.
11122   if (Last == 0) {
11123     if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) {
11124       SmallVector<const SCEV *, 2> Qs;
11125       for (const SCEV *Op : M->operands())
11126         if (!isa<SCEVConstant>(Op))
11127           Qs.push_back(Op);
11128 
11129       Step = SE.getMulExpr(Qs);
11130     }
11131 
11132     Sizes.push_back(Step);
11133     return true;
11134   }
11135 
11136   for (const SCEV *&Term : Terms) {
11137     // Normalize the terms before the next call to findArrayDimensionsRec.
11138     const SCEV *Q, *R;
11139     SCEVDivision::divide(SE, Term, Step, &Q, &R);
11140 
11141     // Bail out when GCD does not evenly divide one of the terms.
11142     if (!R->isZero())
11143       return false;
11144 
11145     Term = Q;
11146   }
11147 
11148   // Remove all SCEVConstants.
11149   Terms.erase(
11150       remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }),
11151       Terms.end());
11152 
11153   if (Terms.size() > 0)
11154     if (!findArrayDimensionsRec(SE, Terms, Sizes))
11155       return false;
11156 
11157   Sizes.push_back(Step);
11158   return true;
11159 }
11160 
11161 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter.
11162 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) {
11163   for (const SCEV *T : Terms)
11164     if (SCEVExprContains(T, isa<SCEVUnknown, const SCEV *>))
11165       return true;
11166   return false;
11167 }
11168 
11169 // Return the number of product terms in S.
11170 static inline int numberOfTerms(const SCEV *S) {
11171   if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S))
11172     return Expr->getNumOperands();
11173   return 1;
11174 }
11175 
11176 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) {
11177   if (isa<SCEVConstant>(T))
11178     return nullptr;
11179 
11180   if (isa<SCEVUnknown>(T))
11181     return T;
11182 
11183   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) {
11184     SmallVector<const SCEV *, 2> Factors;
11185     for (const SCEV *Op : M->operands())
11186       if (!isa<SCEVConstant>(Op))
11187         Factors.push_back(Op);
11188 
11189     return SE.getMulExpr(Factors);
11190   }
11191 
11192   return T;
11193 }
11194 
11195 /// Return the size of an element read or written by Inst.
11196 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
11197   Type *Ty;
11198   if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
11199     Ty = Store->getValueOperand()->getType();
11200   else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
11201     Ty = Load->getType();
11202   else
11203     return nullptr;
11204 
11205   Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
11206   return getSizeOfExpr(ETy, Ty);
11207 }
11208 
11209 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
11210                                           SmallVectorImpl<const SCEV *> &Sizes,
11211                                           const SCEV *ElementSize) {
11212   if (Terms.size() < 1 || !ElementSize)
11213     return;
11214 
11215   // Early return when Terms do not contain parameters: we do not delinearize
11216   // non parametric SCEVs.
11217   if (!containsParameters(Terms))
11218     return;
11219 
11220   LLVM_DEBUG({
11221     dbgs() << "Terms:\n";
11222     for (const SCEV *T : Terms)
11223       dbgs() << *T << "\n";
11224   });
11225 
11226   // Remove duplicates.
11227   array_pod_sort(Terms.begin(), Terms.end());
11228   Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end());
11229 
11230   // Put larger terms first.
11231   llvm::sort(Terms, [](const SCEV *LHS, const SCEV *RHS) {
11232     return numberOfTerms(LHS) > numberOfTerms(RHS);
11233   });
11234 
11235   // Try to divide all terms by the element size. If term is not divisible by
11236   // element size, proceed with the original term.
11237   for (const SCEV *&Term : Terms) {
11238     const SCEV *Q, *R;
11239     SCEVDivision::divide(*this, Term, ElementSize, &Q, &R);
11240     if (!Q->isZero())
11241       Term = Q;
11242   }
11243 
11244   SmallVector<const SCEV *, 4> NewTerms;
11245 
11246   // Remove constant factors.
11247   for (const SCEV *T : Terms)
11248     if (const SCEV *NewT = removeConstantFactors(*this, T))
11249       NewTerms.push_back(NewT);
11250 
11251   LLVM_DEBUG({
11252     dbgs() << "Terms after sorting:\n";
11253     for (const SCEV *T : NewTerms)
11254       dbgs() << *T << "\n";
11255   });
11256 
11257   if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) {
11258     Sizes.clear();
11259     return;
11260   }
11261 
11262   // The last element to be pushed into Sizes is the size of an element.
11263   Sizes.push_back(ElementSize);
11264 
11265   LLVM_DEBUG({
11266     dbgs() << "Sizes:\n";
11267     for (const SCEV *S : Sizes)
11268       dbgs() << *S << "\n";
11269   });
11270 }
11271 
11272 void ScalarEvolution::computeAccessFunctions(
11273     const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts,
11274     SmallVectorImpl<const SCEV *> &Sizes) {
11275   // Early exit in case this SCEV is not an affine multivariate function.
11276   if (Sizes.empty())
11277     return;
11278 
11279   if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr))
11280     if (!AR->isAffine())
11281       return;
11282 
11283   const SCEV *Res = Expr;
11284   int Last = Sizes.size() - 1;
11285   for (int i = Last; i >= 0; i--) {
11286     const SCEV *Q, *R;
11287     SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R);
11288 
11289     LLVM_DEBUG({
11290       dbgs() << "Res: " << *Res << "\n";
11291       dbgs() << "Sizes[i]: " << *Sizes[i] << "\n";
11292       dbgs() << "Res divided by Sizes[i]:\n";
11293       dbgs() << "Quotient: " << *Q << "\n";
11294       dbgs() << "Remainder: " << *R << "\n";
11295     });
11296 
11297     Res = Q;
11298 
11299     // Do not record the last subscript corresponding to the size of elements in
11300     // the array.
11301     if (i == Last) {
11302 
11303       // Bail out if the remainder is too complex.
11304       if (isa<SCEVAddRecExpr>(R)) {
11305         Subscripts.clear();
11306         Sizes.clear();
11307         return;
11308       }
11309 
11310       continue;
11311     }
11312 
11313     // Record the access function for the current subscript.
11314     Subscripts.push_back(R);
11315   }
11316 
11317   // Also push in last position the remainder of the last division: it will be
11318   // the access function of the innermost dimension.
11319   Subscripts.push_back(Res);
11320 
11321   std::reverse(Subscripts.begin(), Subscripts.end());
11322 
11323   LLVM_DEBUG({
11324     dbgs() << "Subscripts:\n";
11325     for (const SCEV *S : Subscripts)
11326       dbgs() << *S << "\n";
11327   });
11328 }
11329 
11330 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and
11331 /// sizes of an array access. Returns the remainder of the delinearization that
11332 /// is the offset start of the array.  The SCEV->delinearize algorithm computes
11333 /// the multiples of SCEV coefficients: that is a pattern matching of sub
11334 /// expressions in the stride and base of a SCEV corresponding to the
11335 /// computation of a GCD (greatest common divisor) of base and stride.  When
11336 /// SCEV->delinearize fails, it returns the SCEV unchanged.
11337 ///
11338 /// For example: when analyzing the memory access A[i][j][k] in this loop nest
11339 ///
11340 ///  void foo(long n, long m, long o, double A[n][m][o]) {
11341 ///
11342 ///    for (long i = 0; i < n; i++)
11343 ///      for (long j = 0; j < m; j++)
11344 ///        for (long k = 0; k < o; k++)
11345 ///          A[i][j][k] = 1.0;
11346 ///  }
11347 ///
11348 /// the delinearization input is the following AddRec SCEV:
11349 ///
11350 ///  AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k>
11351 ///
11352 /// From this SCEV, we are able to say that the base offset of the access is %A
11353 /// because it appears as an offset that does not divide any of the strides in
11354 /// the loops:
11355 ///
11356 ///  CHECK: Base offset: %A
11357 ///
11358 /// and then SCEV->delinearize determines the size of some of the dimensions of
11359 /// the array as these are the multiples by which the strides are happening:
11360 ///
11361 ///  CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes.
11362 ///
11363 /// Note that the outermost dimension remains of UnknownSize because there are
11364 /// no strides that would help identifying the size of the last dimension: when
11365 /// the array has been statically allocated, one could compute the size of that
11366 /// dimension by dividing the overall size of the array by the size of the known
11367 /// dimensions: %m * %o * 8.
11368 ///
11369 /// Finally delinearize provides the access functions for the array reference
11370 /// that does correspond to A[i][j][k] of the above C testcase:
11371 ///
11372 ///  CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>]
11373 ///
11374 /// The testcases are checking the output of a function pass:
11375 /// DelinearizationPass that walks through all loads and stores of a function
11376 /// asking for the SCEV of the memory access with respect to all enclosing
11377 /// loops, calling SCEV->delinearize on that and printing the results.
11378 void ScalarEvolution::delinearize(const SCEV *Expr,
11379                                  SmallVectorImpl<const SCEV *> &Subscripts,
11380                                  SmallVectorImpl<const SCEV *> &Sizes,
11381                                  const SCEV *ElementSize) {
11382   // First step: collect parametric terms.
11383   SmallVector<const SCEV *, 4> Terms;
11384   collectParametricTerms(Expr, Terms);
11385 
11386   if (Terms.empty())
11387     return;
11388 
11389   // Second step: find subscript sizes.
11390   findArrayDimensions(Terms, Sizes, ElementSize);
11391 
11392   if (Sizes.empty())
11393     return;
11394 
11395   // Third step: compute the access functions for each subscript.
11396   computeAccessFunctions(Expr, Subscripts, Sizes);
11397 
11398   if (Subscripts.empty())
11399     return;
11400 
11401   LLVM_DEBUG({
11402     dbgs() << "succeeded to delinearize " << *Expr << "\n";
11403     dbgs() << "ArrayDecl[UnknownSize]";
11404     for (const SCEV *S : Sizes)
11405       dbgs() << "[" << *S << "]";
11406 
11407     dbgs() << "\nArrayRef";
11408     for (const SCEV *S : Subscripts)
11409       dbgs() << "[" << *S << "]";
11410     dbgs() << "\n";
11411   });
11412 }
11413 
11414 //===----------------------------------------------------------------------===//
11415 //                   SCEVCallbackVH Class Implementation
11416 //===----------------------------------------------------------------------===//
11417 
11418 void ScalarEvolution::SCEVCallbackVH::deleted() {
11419   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
11420   if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
11421     SE->ConstantEvolutionLoopExitValue.erase(PN);
11422   SE->eraseValueFromMap(getValPtr());
11423   // this now dangles!
11424 }
11425 
11426 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
11427   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
11428 
11429   // Forget all the expressions associated with users of the old value,
11430   // so that future queries will recompute the expressions using the new
11431   // value.
11432   Value *Old = getValPtr();
11433   SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end());
11434   SmallPtrSet<User *, 8> Visited;
11435   while (!Worklist.empty()) {
11436     User *U = Worklist.pop_back_val();
11437     // Deleting the Old value will cause this to dangle. Postpone
11438     // that until everything else is done.
11439     if (U == Old)
11440       continue;
11441     if (!Visited.insert(U).second)
11442       continue;
11443     if (PHINode *PN = dyn_cast<PHINode>(U))
11444       SE->ConstantEvolutionLoopExitValue.erase(PN);
11445     SE->eraseValueFromMap(U);
11446     Worklist.insert(Worklist.end(), U->user_begin(), U->user_end());
11447   }
11448   // Delete the Old value.
11449   if (PHINode *PN = dyn_cast<PHINode>(Old))
11450     SE->ConstantEvolutionLoopExitValue.erase(PN);
11451   SE->eraseValueFromMap(Old);
11452   // this now dangles!
11453 }
11454 
11455 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
11456   : CallbackVH(V), SE(se) {}
11457 
11458 //===----------------------------------------------------------------------===//
11459 //                   ScalarEvolution Class Implementation
11460 //===----------------------------------------------------------------------===//
11461 
11462 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
11463                                  AssumptionCache &AC, DominatorTree &DT,
11464                                  LoopInfo &LI)
11465     : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
11466       CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64),
11467       LoopDispositions(64), BlockDispositions(64) {
11468   // To use guards for proving predicates, we need to scan every instruction in
11469   // relevant basic blocks, and not just terminators.  Doing this is a waste of
11470   // time if the IR does not actually contain any calls to
11471   // @llvm.experimental.guard, so do a quick check and remember this beforehand.
11472   //
11473   // This pessimizes the case where a pass that preserves ScalarEvolution wants
11474   // to _add_ guards to the module when there weren't any before, and wants
11475   // ScalarEvolution to optimize based on those guards.  For now we prefer to be
11476   // efficient in lieu of being smart in that rather obscure case.
11477 
11478   auto *GuardDecl = F.getParent()->getFunction(
11479       Intrinsic::getName(Intrinsic::experimental_guard));
11480   HasGuards = GuardDecl && !GuardDecl->use_empty();
11481 }
11482 
11483 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
11484     : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT),
11485       LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
11486       ValueExprMap(std::move(Arg.ValueExprMap)),
11487       PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
11488       PendingPhiRanges(std::move(Arg.PendingPhiRanges)),
11489       PendingMerges(std::move(Arg.PendingMerges)),
11490       MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)),
11491       BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
11492       PredicatedBackedgeTakenCounts(
11493           std::move(Arg.PredicatedBackedgeTakenCounts)),
11494       ConstantEvolutionLoopExitValue(
11495           std::move(Arg.ConstantEvolutionLoopExitValue)),
11496       ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
11497       LoopDispositions(std::move(Arg.LoopDispositions)),
11498       LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
11499       BlockDispositions(std::move(Arg.BlockDispositions)),
11500       UnsignedRanges(std::move(Arg.UnsignedRanges)),
11501       SignedRanges(std::move(Arg.SignedRanges)),
11502       UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
11503       UniquePreds(std::move(Arg.UniquePreds)),
11504       SCEVAllocator(std::move(Arg.SCEVAllocator)),
11505       LoopUsers(std::move(Arg.LoopUsers)),
11506       PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)),
11507       FirstUnknown(Arg.FirstUnknown) {
11508   Arg.FirstUnknown = nullptr;
11509 }
11510 
11511 ScalarEvolution::~ScalarEvolution() {
11512   // Iterate through all the SCEVUnknown instances and call their
11513   // destructors, so that they release their references to their values.
11514   for (SCEVUnknown *U = FirstUnknown; U;) {
11515     SCEVUnknown *Tmp = U;
11516     U = U->Next;
11517     Tmp->~SCEVUnknown();
11518   }
11519   FirstUnknown = nullptr;
11520 
11521   ExprValueMap.clear();
11522   ValueExprMap.clear();
11523   HasRecMap.clear();
11524 
11525   // Free any extra memory created for ExitNotTakenInfo in the unlikely event
11526   // that a loop had multiple computable exits.
11527   for (auto &BTCI : BackedgeTakenCounts)
11528     BTCI.second.clear();
11529   for (auto &BTCI : PredicatedBackedgeTakenCounts)
11530     BTCI.second.clear();
11531 
11532   assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
11533   assert(PendingPhiRanges.empty() && "getRangeRef garbage");
11534   assert(PendingMerges.empty() && "isImpliedViaMerge garbage");
11535   assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
11536   assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
11537 }
11538 
11539 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
11540   return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
11541 }
11542 
11543 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
11544                           const Loop *L) {
11545   // Print all inner loops first
11546   for (Loop *I : *L)
11547     PrintLoopInfo(OS, SE, I);
11548 
11549   OS << "Loop ";
11550   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
11551   OS << ": ";
11552 
11553   SmallVector<BasicBlock *, 8> ExitingBlocks;
11554   L->getExitingBlocks(ExitingBlocks);
11555   if (ExitingBlocks.size() != 1)
11556     OS << "<multiple exits> ";
11557 
11558   if (SE->hasLoopInvariantBackedgeTakenCount(L))
11559     OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L) << "\n";
11560   else
11561     OS << "Unpredictable backedge-taken count.\n";
11562 
11563   if (ExitingBlocks.size() > 1)
11564     for (BasicBlock *ExitingBlock : ExitingBlocks) {
11565       OS << "  exit count for " << ExitingBlock->getName() << ": "
11566          << *SE->getExitCount(L, ExitingBlock) << "\n";
11567     }
11568 
11569   OS << "Loop ";
11570   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
11571   OS << ": ";
11572 
11573   if (!isa<SCEVCouldNotCompute>(SE->getConstantMaxBackedgeTakenCount(L))) {
11574     OS << "max backedge-taken count is " << *SE->getConstantMaxBackedgeTakenCount(L);
11575     if (SE->isBackedgeTakenCountMaxOrZero(L))
11576       OS << ", actual taken count either this or zero.";
11577   } else {
11578     OS << "Unpredictable max backedge-taken count. ";
11579   }
11580 
11581   OS << "\n"
11582         "Loop ";
11583   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
11584   OS << ": ";
11585 
11586   SCEVUnionPredicate Pred;
11587   auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred);
11588   if (!isa<SCEVCouldNotCompute>(PBT)) {
11589     OS << "Predicated backedge-taken count is " << *PBT << "\n";
11590     OS << " Predicates:\n";
11591     Pred.print(OS, 4);
11592   } else {
11593     OS << "Unpredictable predicated backedge-taken count. ";
11594   }
11595   OS << "\n";
11596 
11597   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
11598     OS << "Loop ";
11599     L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
11600     OS << ": ";
11601     OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
11602   }
11603 }
11604 
11605 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) {
11606   switch (LD) {
11607   case ScalarEvolution::LoopVariant:
11608     return "Variant";
11609   case ScalarEvolution::LoopInvariant:
11610     return "Invariant";
11611   case ScalarEvolution::LoopComputable:
11612     return "Computable";
11613   }
11614   llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!");
11615 }
11616 
11617 void ScalarEvolution::print(raw_ostream &OS) const {
11618   // ScalarEvolution's implementation of the print method is to print
11619   // out SCEV values of all instructions that are interesting. Doing
11620   // this potentially causes it to create new SCEV objects though,
11621   // which technically conflicts with the const qualifier. This isn't
11622   // observable from outside the class though, so casting away the
11623   // const isn't dangerous.
11624   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
11625 
11626   if (ClassifyExpressions) {
11627     OS << "Classifying expressions for: ";
11628     F.printAsOperand(OS, /*PrintType=*/false);
11629     OS << "\n";
11630     for (Instruction &I : instructions(F))
11631       if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
11632         OS << I << '\n';
11633         OS << "  -->  ";
11634         const SCEV *SV = SE.getSCEV(&I);
11635         SV->print(OS);
11636         if (!isa<SCEVCouldNotCompute>(SV)) {
11637           OS << " U: ";
11638           SE.getUnsignedRange(SV).print(OS);
11639           OS << " S: ";
11640           SE.getSignedRange(SV).print(OS);
11641         }
11642 
11643         const Loop *L = LI.getLoopFor(I.getParent());
11644 
11645         const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
11646         if (AtUse != SV) {
11647           OS << "  -->  ";
11648           AtUse->print(OS);
11649           if (!isa<SCEVCouldNotCompute>(AtUse)) {
11650             OS << " U: ";
11651             SE.getUnsignedRange(AtUse).print(OS);
11652             OS << " S: ";
11653             SE.getSignedRange(AtUse).print(OS);
11654           }
11655         }
11656 
11657         if (L) {
11658           OS << "\t\t" "Exits: ";
11659           const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
11660           if (!SE.isLoopInvariant(ExitValue, L)) {
11661             OS << "<<Unknown>>";
11662           } else {
11663             OS << *ExitValue;
11664           }
11665 
11666           bool First = true;
11667           for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
11668             if (First) {
11669               OS << "\t\t" "LoopDispositions: { ";
11670               First = false;
11671             } else {
11672               OS << ", ";
11673             }
11674 
11675             Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
11676             OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter));
11677           }
11678 
11679           for (auto *InnerL : depth_first(L)) {
11680             if (InnerL == L)
11681               continue;
11682             if (First) {
11683               OS << "\t\t" "LoopDispositions: { ";
11684               First = false;
11685             } else {
11686               OS << ", ";
11687             }
11688 
11689             InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
11690             OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL));
11691           }
11692 
11693           OS << " }";
11694         }
11695 
11696         OS << "\n";
11697       }
11698   }
11699 
11700   OS << "Determining loop execution counts for: ";
11701   F.printAsOperand(OS, /*PrintType=*/false);
11702   OS << "\n";
11703   for (Loop *I : LI)
11704     PrintLoopInfo(OS, &SE, I);
11705 }
11706 
11707 ScalarEvolution::LoopDisposition
11708 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
11709   auto &Values = LoopDispositions[S];
11710   for (auto &V : Values) {
11711     if (V.getPointer() == L)
11712       return V.getInt();
11713   }
11714   Values.emplace_back(L, LoopVariant);
11715   LoopDisposition D = computeLoopDisposition(S, L);
11716   auto &Values2 = LoopDispositions[S];
11717   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
11718     if (V.getPointer() == L) {
11719       V.setInt(D);
11720       break;
11721     }
11722   }
11723   return D;
11724 }
11725 
11726 ScalarEvolution::LoopDisposition
11727 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
11728   switch (static_cast<SCEVTypes>(S->getSCEVType())) {
11729   case scConstant:
11730     return LoopInvariant;
11731   case scTruncate:
11732   case scZeroExtend:
11733   case scSignExtend:
11734     return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
11735   case scAddRecExpr: {
11736     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
11737 
11738     // If L is the addrec's loop, it's computable.
11739     if (AR->getLoop() == L)
11740       return LoopComputable;
11741 
11742     // Add recurrences are never invariant in the function-body (null loop).
11743     if (!L)
11744       return LoopVariant;
11745 
11746     // Everything that is not defined at loop entry is variant.
11747     if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader()))
11748       return LoopVariant;
11749     assert(!L->contains(AR->getLoop()) && "Containing loop's header does not"
11750            " dominate the contained loop's header?");
11751 
11752     // This recurrence is invariant w.r.t. L if AR's loop contains L.
11753     if (AR->getLoop()->contains(L))
11754       return LoopInvariant;
11755 
11756     // This recurrence is variant w.r.t. L if any of its operands
11757     // are variant.
11758     for (auto *Op : AR->operands())
11759       if (!isLoopInvariant(Op, L))
11760         return LoopVariant;
11761 
11762     // Otherwise it's loop-invariant.
11763     return LoopInvariant;
11764   }
11765   case scAddExpr:
11766   case scMulExpr:
11767   case scUMaxExpr:
11768   case scSMaxExpr:
11769   case scUMinExpr:
11770   case scSMinExpr: {
11771     bool HasVarying = false;
11772     for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) {
11773       LoopDisposition D = getLoopDisposition(Op, L);
11774       if (D == LoopVariant)
11775         return LoopVariant;
11776       if (D == LoopComputable)
11777         HasVarying = true;
11778     }
11779     return HasVarying ? LoopComputable : LoopInvariant;
11780   }
11781   case scUDivExpr: {
11782     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
11783     LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
11784     if (LD == LoopVariant)
11785       return LoopVariant;
11786     LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
11787     if (RD == LoopVariant)
11788       return LoopVariant;
11789     return (LD == LoopInvariant && RD == LoopInvariant) ?
11790            LoopInvariant : LoopComputable;
11791   }
11792   case scUnknown:
11793     // All non-instruction values are loop invariant.  All instructions are loop
11794     // invariant if they are not contained in the specified loop.
11795     // Instructions are never considered invariant in the function body
11796     // (null loop) because they are defined within the "loop".
11797     if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
11798       return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
11799     return LoopInvariant;
11800   case scCouldNotCompute:
11801     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
11802   }
11803   llvm_unreachable("Unknown SCEV kind!");
11804 }
11805 
11806 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
11807   return getLoopDisposition(S, L) == LoopInvariant;
11808 }
11809 
11810 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
11811   return getLoopDisposition(S, L) == LoopComputable;
11812 }
11813 
11814 ScalarEvolution::BlockDisposition
11815 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
11816   auto &Values = BlockDispositions[S];
11817   for (auto &V : Values) {
11818     if (V.getPointer() == BB)
11819       return V.getInt();
11820   }
11821   Values.emplace_back(BB, DoesNotDominateBlock);
11822   BlockDisposition D = computeBlockDisposition(S, BB);
11823   auto &Values2 = BlockDispositions[S];
11824   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
11825     if (V.getPointer() == BB) {
11826       V.setInt(D);
11827       break;
11828     }
11829   }
11830   return D;
11831 }
11832 
11833 ScalarEvolution::BlockDisposition
11834 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
11835   switch (static_cast<SCEVTypes>(S->getSCEVType())) {
11836   case scConstant:
11837     return ProperlyDominatesBlock;
11838   case scTruncate:
11839   case scZeroExtend:
11840   case scSignExtend:
11841     return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
11842   case scAddRecExpr: {
11843     // This uses a "dominates" query instead of "properly dominates" query
11844     // to test for proper dominance too, because the instruction which
11845     // produces the addrec's value is a PHI, and a PHI effectively properly
11846     // dominates its entire containing block.
11847     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
11848     if (!DT.dominates(AR->getLoop()->getHeader(), BB))
11849       return DoesNotDominateBlock;
11850 
11851     // Fall through into SCEVNAryExpr handling.
11852     LLVM_FALLTHROUGH;
11853   }
11854   case scAddExpr:
11855   case scMulExpr:
11856   case scUMaxExpr:
11857   case scSMaxExpr:
11858   case scUMinExpr:
11859   case scSMinExpr: {
11860     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
11861     bool Proper = true;
11862     for (const SCEV *NAryOp : NAry->operands()) {
11863       BlockDisposition D = getBlockDisposition(NAryOp, BB);
11864       if (D == DoesNotDominateBlock)
11865         return DoesNotDominateBlock;
11866       if (D == DominatesBlock)
11867         Proper = false;
11868     }
11869     return Proper ? ProperlyDominatesBlock : DominatesBlock;
11870   }
11871   case scUDivExpr: {
11872     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
11873     const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
11874     BlockDisposition LD = getBlockDisposition(LHS, BB);
11875     if (LD == DoesNotDominateBlock)
11876       return DoesNotDominateBlock;
11877     BlockDisposition RD = getBlockDisposition(RHS, BB);
11878     if (RD == DoesNotDominateBlock)
11879       return DoesNotDominateBlock;
11880     return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
11881       ProperlyDominatesBlock : DominatesBlock;
11882   }
11883   case scUnknown:
11884     if (Instruction *I =
11885           dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
11886       if (I->getParent() == BB)
11887         return DominatesBlock;
11888       if (DT.properlyDominates(I->getParent(), BB))
11889         return ProperlyDominatesBlock;
11890       return DoesNotDominateBlock;
11891     }
11892     return ProperlyDominatesBlock;
11893   case scCouldNotCompute:
11894     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
11895   }
11896   llvm_unreachable("Unknown SCEV kind!");
11897 }
11898 
11899 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
11900   return getBlockDisposition(S, BB) >= DominatesBlock;
11901 }
11902 
11903 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
11904   return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
11905 }
11906 
11907 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
11908   return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; });
11909 }
11910 
11911 bool ScalarEvolution::ExitLimit::hasOperand(const SCEV *S) const {
11912   auto IsS = [&](const SCEV *X) { return S == X; };
11913   auto ContainsS = [&](const SCEV *X) {
11914     return !isa<SCEVCouldNotCompute>(X) && SCEVExprContains(X, IsS);
11915   };
11916   return ContainsS(ExactNotTaken) || ContainsS(MaxNotTaken);
11917 }
11918 
11919 void
11920 ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
11921   ValuesAtScopes.erase(S);
11922   LoopDispositions.erase(S);
11923   BlockDispositions.erase(S);
11924   UnsignedRanges.erase(S);
11925   SignedRanges.erase(S);
11926   ExprValueMap.erase(S);
11927   HasRecMap.erase(S);
11928   MinTrailingZerosCache.erase(S);
11929 
11930   for (auto I = PredicatedSCEVRewrites.begin();
11931        I != PredicatedSCEVRewrites.end();) {
11932     std::pair<const SCEV *, const Loop *> Entry = I->first;
11933     if (Entry.first == S)
11934       PredicatedSCEVRewrites.erase(I++);
11935     else
11936       ++I;
11937   }
11938 
11939   auto RemoveSCEVFromBackedgeMap =
11940       [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
11941         for (auto I = Map.begin(), E = Map.end(); I != E;) {
11942           BackedgeTakenInfo &BEInfo = I->second;
11943           if (BEInfo.hasOperand(S, this)) {
11944             BEInfo.clear();
11945             Map.erase(I++);
11946           } else
11947             ++I;
11948         }
11949       };
11950 
11951   RemoveSCEVFromBackedgeMap(BackedgeTakenCounts);
11952   RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts);
11953 }
11954 
11955 void
11956 ScalarEvolution::getUsedLoops(const SCEV *S,
11957                               SmallPtrSetImpl<const Loop *> &LoopsUsed) {
11958   struct FindUsedLoops {
11959     FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed)
11960         : LoopsUsed(LoopsUsed) {}
11961     SmallPtrSetImpl<const Loop *> &LoopsUsed;
11962     bool follow(const SCEV *S) {
11963       if (auto *AR = dyn_cast<SCEVAddRecExpr>(S))
11964         LoopsUsed.insert(AR->getLoop());
11965       return true;
11966     }
11967 
11968     bool isDone() const { return false; }
11969   };
11970 
11971   FindUsedLoops F(LoopsUsed);
11972   SCEVTraversal<FindUsedLoops>(F).visitAll(S);
11973 }
11974 
11975 void ScalarEvolution::addToLoopUseLists(const SCEV *S) {
11976   SmallPtrSet<const Loop *, 8> LoopsUsed;
11977   getUsedLoops(S, LoopsUsed);
11978   for (auto *L : LoopsUsed)
11979     LoopUsers[L].push_back(S);
11980 }
11981 
11982 void ScalarEvolution::verify() const {
11983   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
11984   ScalarEvolution SE2(F, TLI, AC, DT, LI);
11985 
11986   SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end());
11987 
11988   // Map's SCEV expressions from one ScalarEvolution "universe" to another.
11989   struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> {
11990     SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {}
11991 
11992     const SCEV *visitConstant(const SCEVConstant *Constant) {
11993       return SE.getConstant(Constant->getAPInt());
11994     }
11995 
11996     const SCEV *visitUnknown(const SCEVUnknown *Expr) {
11997       return SE.getUnknown(Expr->getValue());
11998     }
11999 
12000     const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
12001       return SE.getCouldNotCompute();
12002     }
12003   };
12004 
12005   SCEVMapper SCM(SE2);
12006 
12007   while (!LoopStack.empty()) {
12008     auto *L = LoopStack.pop_back_val();
12009     LoopStack.insert(LoopStack.end(), L->begin(), L->end());
12010 
12011     auto *CurBECount = SCM.visit(
12012         const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L));
12013     auto *NewBECount = SE2.getBackedgeTakenCount(L);
12014 
12015     if (CurBECount == SE2.getCouldNotCompute() ||
12016         NewBECount == SE2.getCouldNotCompute()) {
12017       // NB! This situation is legal, but is very suspicious -- whatever pass
12018       // change the loop to make a trip count go from could not compute to
12019       // computable or vice-versa *should have* invalidated SCEV.  However, we
12020       // choose not to assert here (for now) since we don't want false
12021       // positives.
12022       continue;
12023     }
12024 
12025     if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) {
12026       // SCEV treats "undef" as an unknown but consistent value (i.e. it does
12027       // not propagate undef aggressively).  This means we can (and do) fail
12028       // verification in cases where a transform makes the trip count of a loop
12029       // go from "undef" to "undef+1" (say).  The transform is fine, since in
12030       // both cases the loop iterates "undef" times, but SCEV thinks we
12031       // increased the trip count of the loop by 1 incorrectly.
12032       continue;
12033     }
12034 
12035     if (SE.getTypeSizeInBits(CurBECount->getType()) >
12036         SE.getTypeSizeInBits(NewBECount->getType()))
12037       NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType());
12038     else if (SE.getTypeSizeInBits(CurBECount->getType()) <
12039              SE.getTypeSizeInBits(NewBECount->getType()))
12040       CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType());
12041 
12042     const SCEV *Delta = SE2.getMinusSCEV(CurBECount, NewBECount);
12043 
12044     // Unless VerifySCEVStrict is set, we only compare constant deltas.
12045     if ((VerifySCEVStrict || isa<SCEVConstant>(Delta)) && !Delta->isZero()) {
12046       dbgs() << "Trip Count for " << *L << " Changed!\n";
12047       dbgs() << "Old: " << *CurBECount << "\n";
12048       dbgs() << "New: " << *NewBECount << "\n";
12049       dbgs() << "Delta: " << *Delta << "\n";
12050       std::abort();
12051     }
12052   }
12053 }
12054 
12055 bool ScalarEvolution::invalidate(
12056     Function &F, const PreservedAnalyses &PA,
12057     FunctionAnalysisManager::Invalidator &Inv) {
12058   // Invalidate the ScalarEvolution object whenever it isn't preserved or one
12059   // of its dependencies is invalidated.
12060   auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
12061   return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
12062          Inv.invalidate<AssumptionAnalysis>(F, PA) ||
12063          Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
12064          Inv.invalidate<LoopAnalysis>(F, PA);
12065 }
12066 
12067 AnalysisKey ScalarEvolutionAnalysis::Key;
12068 
12069 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
12070                                              FunctionAnalysisManager &AM) {
12071   return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F),
12072                          AM.getResult<AssumptionAnalysis>(F),
12073                          AM.getResult<DominatorTreeAnalysis>(F),
12074                          AM.getResult<LoopAnalysis>(F));
12075 }
12076 
12077 PreservedAnalyses
12078 ScalarEvolutionVerifierPass::run(Function &F, FunctionAnalysisManager &AM) {
12079   AM.getResult<ScalarEvolutionAnalysis>(F).verify();
12080   return PreservedAnalyses::all();
12081 }
12082 
12083 PreservedAnalyses
12084 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
12085   AM.getResult<ScalarEvolutionAnalysis>(F).print(OS);
12086   return PreservedAnalyses::all();
12087 }
12088 
12089 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
12090                       "Scalar Evolution Analysis", false, true)
12091 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
12092 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
12093 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
12094 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
12095 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
12096                     "Scalar Evolution Analysis", false, true)
12097 
12098 char ScalarEvolutionWrapperPass::ID = 0;
12099 
12100 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
12101   initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
12102 }
12103 
12104 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
12105   SE.reset(new ScalarEvolution(
12106       F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F),
12107       getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
12108       getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
12109       getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
12110   return false;
12111 }
12112 
12113 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
12114 
12115 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
12116   SE->print(OS);
12117 }
12118 
12119 void ScalarEvolutionWrapperPass::verifyAnalysis() const {
12120   if (!VerifySCEV)
12121     return;
12122 
12123   SE->verify();
12124 }
12125 
12126 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
12127   AU.setPreservesAll();
12128   AU.addRequiredTransitive<AssumptionCacheTracker>();
12129   AU.addRequiredTransitive<LoopInfoWrapperPass>();
12130   AU.addRequiredTransitive<DominatorTreeWrapperPass>();
12131   AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
12132 }
12133 
12134 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS,
12135                                                         const SCEV *RHS) {
12136   FoldingSetNodeID ID;
12137   assert(LHS->getType() == RHS->getType() &&
12138          "Type mismatch between LHS and RHS");
12139   // Unique this node based on the arguments
12140   ID.AddInteger(SCEVPredicate::P_Equal);
12141   ID.AddPointer(LHS);
12142   ID.AddPointer(RHS);
12143   void *IP = nullptr;
12144   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
12145     return S;
12146   SCEVEqualPredicate *Eq = new (SCEVAllocator)
12147       SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS);
12148   UniquePreds.InsertNode(Eq, IP);
12149   return Eq;
12150 }
12151 
12152 const SCEVPredicate *ScalarEvolution::getWrapPredicate(
12153     const SCEVAddRecExpr *AR,
12154     SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
12155   FoldingSetNodeID ID;
12156   // Unique this node based on the arguments
12157   ID.AddInteger(SCEVPredicate::P_Wrap);
12158   ID.AddPointer(AR);
12159   ID.AddInteger(AddedFlags);
12160   void *IP = nullptr;
12161   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
12162     return S;
12163   auto *OF = new (SCEVAllocator)
12164       SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
12165   UniquePreds.InsertNode(OF, IP);
12166   return OF;
12167 }
12168 
12169 namespace {
12170 
12171 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
12172 public:
12173 
12174   /// Rewrites \p S in the context of a loop L and the SCEV predication
12175   /// infrastructure.
12176   ///
12177   /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
12178   /// equivalences present in \p Pred.
12179   ///
12180   /// If \p NewPreds is non-null, rewrite is free to add further predicates to
12181   /// \p NewPreds such that the result will be an AddRecExpr.
12182   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
12183                              SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
12184                              SCEVUnionPredicate *Pred) {
12185     SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
12186     return Rewriter.visit(S);
12187   }
12188 
12189   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
12190     if (Pred) {
12191       auto ExprPreds = Pred->getPredicatesForExpr(Expr);
12192       for (auto *Pred : ExprPreds)
12193         if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred))
12194           if (IPred->getLHS() == Expr)
12195             return IPred->getRHS();
12196     }
12197     return convertToAddRecWithPreds(Expr);
12198   }
12199 
12200   const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
12201     const SCEV *Operand = visit(Expr->getOperand());
12202     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
12203     if (AR && AR->getLoop() == L && AR->isAffine()) {
12204       // This couldn't be folded because the operand didn't have the nuw
12205       // flag. Add the nusw flag as an assumption that we could make.
12206       const SCEV *Step = AR->getStepRecurrence(SE);
12207       Type *Ty = Expr->getType();
12208       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
12209         return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
12210                                 SE.getSignExtendExpr(Step, Ty), L,
12211                                 AR->getNoWrapFlags());
12212     }
12213     return SE.getZeroExtendExpr(Operand, Expr->getType());
12214   }
12215 
12216   const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
12217     const SCEV *Operand = visit(Expr->getOperand());
12218     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
12219     if (AR && AR->getLoop() == L && AR->isAffine()) {
12220       // This couldn't be folded because the operand didn't have the nsw
12221       // flag. Add the nssw flag as an assumption that we could make.
12222       const SCEV *Step = AR->getStepRecurrence(SE);
12223       Type *Ty = Expr->getType();
12224       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
12225         return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
12226                                 SE.getSignExtendExpr(Step, Ty), L,
12227                                 AR->getNoWrapFlags());
12228     }
12229     return SE.getSignExtendExpr(Operand, Expr->getType());
12230   }
12231 
12232 private:
12233   explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE,
12234                         SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
12235                         SCEVUnionPredicate *Pred)
12236       : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
12237 
12238   bool addOverflowAssumption(const SCEVPredicate *P) {
12239     if (!NewPreds) {
12240       // Check if we've already made this assumption.
12241       return Pred && Pred->implies(P);
12242     }
12243     NewPreds->insert(P);
12244     return true;
12245   }
12246 
12247   bool addOverflowAssumption(const SCEVAddRecExpr *AR,
12248                              SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
12249     auto *A = SE.getWrapPredicate(AR, AddedFlags);
12250     return addOverflowAssumption(A);
12251   }
12252 
12253   // If \p Expr represents a PHINode, we try to see if it can be represented
12254   // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible
12255   // to add this predicate as a runtime overflow check, we return the AddRec.
12256   // If \p Expr does not meet these conditions (is not a PHI node, or we
12257   // couldn't create an AddRec for it, or couldn't add the predicate), we just
12258   // return \p Expr.
12259   const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) {
12260     if (!isa<PHINode>(Expr->getValue()))
12261       return Expr;
12262     Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
12263     PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr);
12264     if (!PredicatedRewrite)
12265       return Expr;
12266     for (auto *P : PredicatedRewrite->second){
12267       // Wrap predicates from outer loops are not supported.
12268       if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) {
12269         auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr());
12270         if (L != AR->getLoop())
12271           return Expr;
12272       }
12273       if (!addOverflowAssumption(P))
12274         return Expr;
12275     }
12276     return PredicatedRewrite->first;
12277   }
12278 
12279   SmallPtrSetImpl<const SCEVPredicate *> *NewPreds;
12280   SCEVUnionPredicate *Pred;
12281   const Loop *L;
12282 };
12283 
12284 } // end anonymous namespace
12285 
12286 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
12287                                                    SCEVUnionPredicate &Preds) {
12288   return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
12289 }
12290 
12291 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates(
12292     const SCEV *S, const Loop *L,
12293     SmallPtrSetImpl<const SCEVPredicate *> &Preds) {
12294   SmallPtrSet<const SCEVPredicate *, 4> TransformPreds;
12295   S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
12296   auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
12297 
12298   if (!AddRec)
12299     return nullptr;
12300 
12301   // Since the transformation was successful, we can now transfer the SCEV
12302   // predicates.
12303   for (auto *P : TransformPreds)
12304     Preds.insert(P);
12305 
12306   return AddRec;
12307 }
12308 
12309 /// SCEV predicates
12310 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
12311                              SCEVPredicateKind Kind)
12312     : FastID(ID), Kind(Kind) {}
12313 
12314 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID,
12315                                        const SCEV *LHS, const SCEV *RHS)
12316     : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {
12317   assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match");
12318   assert(LHS != RHS && "LHS and RHS are the same SCEV");
12319 }
12320 
12321 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const {
12322   const auto *Op = dyn_cast<SCEVEqualPredicate>(N);
12323 
12324   if (!Op)
12325     return false;
12326 
12327   return Op->LHS == LHS && Op->RHS == RHS;
12328 }
12329 
12330 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; }
12331 
12332 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; }
12333 
12334 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const {
12335   OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
12336 }
12337 
12338 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
12339                                      const SCEVAddRecExpr *AR,
12340                                      IncrementWrapFlags Flags)
12341     : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
12342 
12343 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; }
12344 
12345 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const {
12346   const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
12347 
12348   return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags;
12349 }
12350 
12351 bool SCEVWrapPredicate::isAlwaysTrue() const {
12352   SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
12353   IncrementWrapFlags IFlags = Flags;
12354 
12355   if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
12356     IFlags = clearFlags(IFlags, IncrementNSSW);
12357 
12358   return IFlags == IncrementAnyWrap;
12359 }
12360 
12361 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
12362   OS.indent(Depth) << *getExpr() << " Added Flags: ";
12363   if (SCEVWrapPredicate::IncrementNUSW & getFlags())
12364     OS << "<nusw>";
12365   if (SCEVWrapPredicate::IncrementNSSW & getFlags())
12366     OS << "<nssw>";
12367   OS << "\n";
12368 }
12369 
12370 SCEVWrapPredicate::IncrementWrapFlags
12371 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR,
12372                                    ScalarEvolution &SE) {
12373   IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
12374   SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
12375 
12376   // We can safely transfer the NSW flag as NSSW.
12377   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
12378     ImpliedFlags = IncrementNSSW;
12379 
12380   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
12381     // If the increment is positive, the SCEV NUW flag will also imply the
12382     // WrapPredicate NUSW flag.
12383     if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
12384       if (Step->getValue()->getValue().isNonNegative())
12385         ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
12386   }
12387 
12388   return ImpliedFlags;
12389 }
12390 
12391 /// Union predicates don't get cached so create a dummy set ID for it.
12392 SCEVUnionPredicate::SCEVUnionPredicate()
12393     : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {}
12394 
12395 bool SCEVUnionPredicate::isAlwaysTrue() const {
12396   return all_of(Preds,
12397                 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
12398 }
12399 
12400 ArrayRef<const SCEVPredicate *>
12401 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) {
12402   auto I = SCEVToPreds.find(Expr);
12403   if (I == SCEVToPreds.end())
12404     return ArrayRef<const SCEVPredicate *>();
12405   return I->second;
12406 }
12407 
12408 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
12409   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
12410     return all_of(Set->Preds,
12411                   [this](const SCEVPredicate *I) { return this->implies(I); });
12412 
12413   auto ScevPredsIt = SCEVToPreds.find(N->getExpr());
12414   if (ScevPredsIt == SCEVToPreds.end())
12415     return false;
12416   auto &SCEVPreds = ScevPredsIt->second;
12417 
12418   return any_of(SCEVPreds,
12419                 [N](const SCEVPredicate *I) { return I->implies(N); });
12420 }
12421 
12422 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; }
12423 
12424 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
12425   for (auto Pred : Preds)
12426     Pred->print(OS, Depth);
12427 }
12428 
12429 void SCEVUnionPredicate::add(const SCEVPredicate *N) {
12430   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
12431     for (auto Pred : Set->Preds)
12432       add(Pred);
12433     return;
12434   }
12435 
12436   if (implies(N))
12437     return;
12438 
12439   const SCEV *Key = N->getExpr();
12440   assert(Key && "Only SCEVUnionPredicate doesn't have an "
12441                 " associated expression!");
12442 
12443   SCEVToPreds[Key].push_back(N);
12444   Preds.push_back(N);
12445 }
12446 
12447 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
12448                                                      Loop &L)
12449     : SE(SE), L(L) {}
12450 
12451 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
12452   const SCEV *Expr = SE.getSCEV(V);
12453   RewriteEntry &Entry = RewriteMap[Expr];
12454 
12455   // If we already have an entry and the version matches, return it.
12456   if (Entry.second && Generation == Entry.first)
12457     return Entry.second;
12458 
12459   // We found an entry but it's stale. Rewrite the stale entry
12460   // according to the current predicate.
12461   if (Entry.second)
12462     Expr = Entry.second;
12463 
12464   const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds);
12465   Entry = {Generation, NewSCEV};
12466 
12467   return NewSCEV;
12468 }
12469 
12470 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() {
12471   if (!BackedgeCount) {
12472     SCEVUnionPredicate BackedgePred;
12473     BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred);
12474     addPredicate(BackedgePred);
12475   }
12476   return BackedgeCount;
12477 }
12478 
12479 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
12480   if (Preds.implies(&Pred))
12481     return;
12482   Preds.add(&Pred);
12483   updateGeneration();
12484 }
12485 
12486 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const {
12487   return Preds;
12488 }
12489 
12490 void PredicatedScalarEvolution::updateGeneration() {
12491   // If the generation number wrapped recompute everything.
12492   if (++Generation == 0) {
12493     for (auto &II : RewriteMap) {
12494       const SCEV *Rewritten = II.second.second;
12495       II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)};
12496     }
12497   }
12498 }
12499 
12500 void PredicatedScalarEvolution::setNoOverflow(
12501     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
12502   const SCEV *Expr = getSCEV(V);
12503   const auto *AR = cast<SCEVAddRecExpr>(Expr);
12504 
12505   auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE);
12506 
12507   // Clear the statically implied flags.
12508   Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags);
12509   addPredicate(*SE.getWrapPredicate(AR, Flags));
12510 
12511   auto II = FlagsMap.insert({V, Flags});
12512   if (!II.second)
12513     II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second);
12514 }
12515 
12516 bool PredicatedScalarEvolution::hasNoOverflow(
12517     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
12518   const SCEV *Expr = getSCEV(V);
12519   const auto *AR = cast<SCEVAddRecExpr>(Expr);
12520 
12521   Flags = SCEVWrapPredicate::clearFlags(
12522       Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
12523 
12524   auto II = FlagsMap.find(V);
12525 
12526   if (II != FlagsMap.end())
12527     Flags = SCEVWrapPredicate::clearFlags(Flags, II->second);
12528 
12529   return Flags == SCEVWrapPredicate::IncrementAnyWrap;
12530 }
12531 
12532 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) {
12533   const SCEV *Expr = this->getSCEV(V);
12534   SmallPtrSet<const SCEVPredicate *, 4> NewPreds;
12535   auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
12536 
12537   if (!New)
12538     return nullptr;
12539 
12540   for (auto *P : NewPreds)
12541     Preds.add(P);
12542 
12543   updateGeneration();
12544   RewriteMap[SE.getSCEV(V)] = {Generation, New};
12545   return New;
12546 }
12547 
12548 PredicatedScalarEvolution::PredicatedScalarEvolution(
12549     const PredicatedScalarEvolution &Init)
12550     : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds),
12551       Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
12552   for (auto I : Init.FlagsMap)
12553     FlagsMap.insert(I);
12554 }
12555 
12556 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const {
12557   // For each block.
12558   for (auto *BB : L.getBlocks())
12559     for (auto &I : *BB) {
12560       if (!SE.isSCEVable(I.getType()))
12561         continue;
12562 
12563       auto *Expr = SE.getSCEV(&I);
12564       auto II = RewriteMap.find(Expr);
12565 
12566       if (II == RewriteMap.end())
12567         continue;
12568 
12569       // Don't print things that are not interesting.
12570       if (II->second.second == Expr)
12571         continue;
12572 
12573       OS.indent(Depth) << "[PSE]" << I << ":\n";
12574       OS.indent(Depth + 2) << *Expr << "\n";
12575       OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
12576     }
12577 }
12578 
12579 // Match the mathematical pattern A - (A / B) * B, where A and B can be
12580 // arbitrary expressions.
12581 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is
12582 // 4, A / B becomes X / 8).
12583 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS,
12584                                 const SCEV *&RHS) {
12585   const auto *Add = dyn_cast<SCEVAddExpr>(Expr);
12586   if (Add == nullptr || Add->getNumOperands() != 2)
12587     return false;
12588 
12589   const SCEV *A = Add->getOperand(1);
12590   const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0));
12591 
12592   if (Mul == nullptr)
12593     return false;
12594 
12595   const auto MatchURemWithDivisor = [&](const SCEV *B) {
12596     // (SomeExpr + (-(SomeExpr / B) * B)).
12597     if (Expr == getURemExpr(A, B)) {
12598       LHS = A;
12599       RHS = B;
12600       return true;
12601     }
12602     return false;
12603   };
12604 
12605   // (SomeExpr + (-1 * (SomeExpr / B) * B)).
12606   if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0)))
12607     return MatchURemWithDivisor(Mul->getOperand(1)) ||
12608            MatchURemWithDivisor(Mul->getOperand(2));
12609 
12610   // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)).
12611   if (Mul->getNumOperands() == 2)
12612     return MatchURemWithDivisor(Mul->getOperand(1)) ||
12613            MatchURemWithDivisor(Mul->getOperand(0)) ||
12614            MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) ||
12615            MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0)));
12616   return false;
12617 }
12618