1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains the implementation of the scalar evolution analysis
11 // engine, which is used primarily to analyze expressions involving induction
12 // variables in loops.
13 //
14 // There are several aspects to this library.  First is the representation of
15 // scalar expressions, which are represented as subclasses of the SCEV class.
16 // These classes are used to represent certain types of subexpressions that we
17 // can handle. We only create one SCEV of a particular shape, so
18 // pointer-comparisons for equality are legal.
19 //
20 // One important aspect of the SCEV objects is that they are never cyclic, even
21 // if there is a cycle in the dataflow for an expression (ie, a PHI node).  If
22 // the PHI node is one of the idioms that we can represent (e.g., a polynomial
23 // recurrence) then we represent it directly as a recurrence node, otherwise we
24 // represent it as a SCEVUnknown node.
25 //
26 // In addition to being able to represent expressions of various types, we also
27 // have folders that are used to build the *canonical* representation for a
28 // particular expression.  These folders are capable of using a variety of
29 // rewrite rules to simplify the expressions.
30 //
31 // Once the folders are defined, we can implement the more interesting
32 // higher-level code, such as the code that recognizes PHI nodes of various
33 // types, computes the execution count of a loop, etc.
34 //
35 // TODO: We should use these routines and value representations to implement
36 // dependence analysis!
37 //
38 //===----------------------------------------------------------------------===//
39 //
40 // There are several good references for the techniques used in this analysis.
41 //
42 //  Chains of recurrences -- a method to expedite the evaluation
43 //  of closed-form functions
44 //  Olaf Bachmann, Paul S. Wang, Eugene V. Zima
45 //
46 //  On computational properties of chains of recurrences
47 //  Eugene V. Zima
48 //
49 //  Symbolic Evaluation of Chains of Recurrences for Loop Optimization
50 //  Robert A. van Engelen
51 //
52 //  Efficient Symbolic Analysis for Optimizing Compilers
53 //  Robert A. van Engelen
54 //
55 //  Using the chains of recurrences algebra for data dependence testing and
56 //  induction variable substitution
57 //  MS Thesis, Johnie Birch
58 //
59 //===----------------------------------------------------------------------===//
60 
61 #include "llvm/Analysis/ScalarEvolution.h"
62 #include "llvm/ADT/APInt.h"
63 #include "llvm/ADT/ArrayRef.h"
64 #include "llvm/ADT/DenseMap.h"
65 #include "llvm/ADT/DepthFirstIterator.h"
66 #include "llvm/ADT/EquivalenceClasses.h"
67 #include "llvm/ADT/FoldingSet.h"
68 #include "llvm/ADT/None.h"
69 #include "llvm/ADT/Optional.h"
70 #include "llvm/ADT/STLExtras.h"
71 #include "llvm/ADT/ScopeExit.h"
72 #include "llvm/ADT/Sequence.h"
73 #include "llvm/ADT/SetVector.h"
74 #include "llvm/ADT/SmallPtrSet.h"
75 #include "llvm/ADT/SmallSet.h"
76 #include "llvm/ADT/SmallVector.h"
77 #include "llvm/ADT/Statistic.h"
78 #include "llvm/ADT/StringRef.h"
79 #include "llvm/Analysis/AssumptionCache.h"
80 #include "llvm/Analysis/ConstantFolding.h"
81 #include "llvm/Analysis/InstructionSimplify.h"
82 #include "llvm/Analysis/LoopInfo.h"
83 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
84 #include "llvm/Analysis/TargetLibraryInfo.h"
85 #include "llvm/Analysis/ValueTracking.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/Pass.h"
115 #include "llvm/Support/Casting.h"
116 #include "llvm/Support/CommandLine.h"
117 #include "llvm/Support/Compiler.h"
118 #include "llvm/Support/Debug.h"
119 #include "llvm/Support/ErrorHandling.h"
120 #include "llvm/Support/KnownBits.h"
121 #include "llvm/Support/SaveAndRestore.h"
122 #include "llvm/Support/raw_ostream.h"
123 #include <algorithm>
124 #include <cassert>
125 #include <climits>
126 #include <cstddef>
127 #include <cstdint>
128 #include <cstdlib>
129 #include <map>
130 #include <memory>
131 #include <tuple>
132 #include <utility>
133 #include <vector>
134 
135 using namespace llvm;
136 
137 #define DEBUG_TYPE "scalar-evolution"
138 
139 STATISTIC(NumArrayLenItCounts,
140           "Number of trip counts computed with array length");
141 STATISTIC(NumTripCountsComputed,
142           "Number of loops with predictable loop counts");
143 STATISTIC(NumTripCountsNotComputed,
144           "Number of loops without predictable loop counts");
145 STATISTIC(NumBruteForceTripCountsComputed,
146           "Number of loops with trip counts computed by force");
147 
148 static cl::opt<unsigned>
149 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
150                         cl::desc("Maximum number of iterations SCEV will "
151                                  "symbolically execute a constant "
152                                  "derived loop"),
153                         cl::init(100));
154 
155 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean.
156 static cl::opt<bool> VerifySCEV(
157     "verify-scev", cl::Hidden,
158     cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
159 static cl::opt<bool>
160     VerifySCEVMap("verify-scev-maps", cl::Hidden,
161                   cl::desc("Verify no dangling value in ScalarEvolution's "
162                            "ExprValueMap (slow)"));
163 
164 static cl::opt<unsigned> MulOpsInlineThreshold(
165     "scev-mulops-inline-threshold", cl::Hidden,
166     cl::desc("Threshold for inlining multiplication operands into a SCEV"),
167     cl::init(32));
168 
169 static cl::opt<unsigned> AddOpsInlineThreshold(
170     "scev-addops-inline-threshold", cl::Hidden,
171     cl::desc("Threshold for inlining addition operands into a SCEV"),
172     cl::init(500));
173 
174 static cl::opt<unsigned> MaxSCEVCompareDepth(
175     "scalar-evolution-max-scev-compare-depth", cl::Hidden,
176     cl::desc("Maximum depth of recursive SCEV complexity comparisons"),
177     cl::init(32));
178 
179 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth(
180     "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden,
181     cl::desc("Maximum depth of recursive SCEV operations implication analysis"),
182     cl::init(2));
183 
184 static cl::opt<unsigned> MaxValueCompareDepth(
185     "scalar-evolution-max-value-compare-depth", cl::Hidden,
186     cl::desc("Maximum depth of recursive value complexity comparisons"),
187     cl::init(2));
188 
189 static cl::opt<unsigned>
190     MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden,
191                   cl::desc("Maximum depth of recursive arithmetics"),
192                   cl::init(32));
193 
194 static cl::opt<unsigned> MaxConstantEvolvingDepth(
195     "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
196     cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
197 
198 static cl::opt<unsigned>
199     MaxExtDepth("scalar-evolution-max-ext-depth", cl::Hidden,
200                 cl::desc("Maximum depth of recursive SExt/ZExt"),
201                 cl::init(8));
202 
203 static cl::opt<unsigned>
204     MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden,
205                   cl::desc("Max coefficients in AddRec during evolving"),
206                   cl::init(16));
207 
208 static cl::opt<bool> VersionUnknown(
209     "scev-version-unknown", cl::Hidden,
210     cl::desc("Use predicated scalar evolution to version SCEVUnknowns"),
211     cl::init(false));
212 
213 //===----------------------------------------------------------------------===//
214 //                           SCEV class definitions
215 //===----------------------------------------------------------------------===//
216 
217 //===----------------------------------------------------------------------===//
218 // Implementation of the SCEV class.
219 //
220 
221 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
222 LLVM_DUMP_METHOD void SCEV::dump() const {
223   print(dbgs());
224   dbgs() << '\n';
225 }
226 #endif
227 
228 void SCEV::print(raw_ostream &OS) const {
229   switch (static_cast<SCEVTypes>(getSCEVType())) {
230   case scConstant:
231     cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
232     return;
233   case scTruncate: {
234     const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
235     const SCEV *Op = Trunc->getOperand();
236     OS << "(trunc " << *Op->getType() << " " << *Op << " to "
237        << *Trunc->getType() << ")";
238     return;
239   }
240   case scZeroExtend: {
241     const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
242     const SCEV *Op = ZExt->getOperand();
243     OS << "(zext " << *Op->getType() << " " << *Op << " to "
244        << *ZExt->getType() << ")";
245     return;
246   }
247   case scSignExtend: {
248     const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
249     const SCEV *Op = SExt->getOperand();
250     OS << "(sext " << *Op->getType() << " " << *Op << " to "
251        << *SExt->getType() << ")";
252     return;
253   }
254   case scAddRecExpr: {
255     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
256     OS << "{" << *AR->getOperand(0);
257     for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
258       OS << ",+," << *AR->getOperand(i);
259     OS << "}<";
260     if (AR->hasNoUnsignedWrap())
261       OS << "nuw><";
262     if (AR->hasNoSignedWrap())
263       OS << "nsw><";
264     if (AR->hasNoSelfWrap() &&
265         !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
266       OS << "nw><";
267     AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
268     OS << ">";
269     return;
270   }
271   case scAddExpr:
272   case scMulExpr:
273   case scUMaxExpr:
274   case scSMaxExpr: {
275     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
276     const char *OpStr = nullptr;
277     switch (NAry->getSCEVType()) {
278     case scAddExpr: OpStr = " + "; break;
279     case scMulExpr: OpStr = " * "; break;
280     case scUMaxExpr: OpStr = " umax "; break;
281     case scSMaxExpr: OpStr = " smax "; break;
282     }
283     OS << "(";
284     for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
285          I != E; ++I) {
286       OS << **I;
287       if (std::next(I) != E)
288         OS << OpStr;
289     }
290     OS << ")";
291     switch (NAry->getSCEVType()) {
292     case scAddExpr:
293     case scMulExpr:
294       if (NAry->hasNoUnsignedWrap())
295         OS << "<nuw>";
296       if (NAry->hasNoSignedWrap())
297         OS << "<nsw>";
298     }
299     return;
300   }
301   case scUDivExpr: {
302     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
303     OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
304     return;
305   }
306   case scUnknown: {
307     const SCEVUnknown *U = cast<SCEVUnknown>(this);
308     Type *AllocTy;
309     if (U->isSizeOf(AllocTy)) {
310       OS << "sizeof(" << *AllocTy << ")";
311       return;
312     }
313     if (U->isAlignOf(AllocTy)) {
314       OS << "alignof(" << *AllocTy << ")";
315       return;
316     }
317 
318     Type *CTy;
319     Constant *FieldNo;
320     if (U->isOffsetOf(CTy, FieldNo)) {
321       OS << "offsetof(" << *CTy << ", ";
322       FieldNo->printAsOperand(OS, false);
323       OS << ")";
324       return;
325     }
326 
327     // Otherwise just print it normally.
328     U->getValue()->printAsOperand(OS, false);
329     return;
330   }
331   case scCouldNotCompute:
332     OS << "***COULDNOTCOMPUTE***";
333     return;
334   }
335   llvm_unreachable("Unknown SCEV kind!");
336 }
337 
338 Type *SCEV::getType() const {
339   switch (static_cast<SCEVTypes>(getSCEVType())) {
340   case scConstant:
341     return cast<SCEVConstant>(this)->getType();
342   case scTruncate:
343   case scZeroExtend:
344   case scSignExtend:
345     return cast<SCEVCastExpr>(this)->getType();
346   case scAddRecExpr:
347   case scMulExpr:
348   case scUMaxExpr:
349   case scSMaxExpr:
350     return cast<SCEVNAryExpr>(this)->getType();
351   case scAddExpr:
352     return cast<SCEVAddExpr>(this)->getType();
353   case scUDivExpr:
354     return cast<SCEVUDivExpr>(this)->getType();
355   case scUnknown:
356     return cast<SCEVUnknown>(this)->getType();
357   case scCouldNotCompute:
358     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
359   }
360   llvm_unreachable("Unknown SCEV kind!");
361 }
362 
363 bool SCEV::isZero() const {
364   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
365     return SC->getValue()->isZero();
366   return false;
367 }
368 
369 bool SCEV::isOne() const {
370   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
371     return SC->getValue()->isOne();
372   return false;
373 }
374 
375 bool SCEV::isAllOnesValue() const {
376   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
377     return SC->getValue()->isMinusOne();
378   return false;
379 }
380 
381 bool SCEV::isNonConstantNegative() const {
382   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
383   if (!Mul) return false;
384 
385   // If there is a constant factor, it will be first.
386   const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
387   if (!SC) return false;
388 
389   // Return true if the value is negative, this matches things like (-42 * V).
390   return SC->getAPInt().isNegative();
391 }
392 
393 SCEVCouldNotCompute::SCEVCouldNotCompute() :
394   SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {}
395 
396 bool SCEVCouldNotCompute::classof(const SCEV *S) {
397   return S->getSCEVType() == scCouldNotCompute;
398 }
399 
400 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
401   FoldingSetNodeID ID;
402   ID.AddInteger(scConstant);
403   ID.AddPointer(V);
404   void *IP = nullptr;
405   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
406   SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
407   UniqueSCEVs.InsertNode(S, IP);
408   return S;
409 }
410 
411 const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
412   return getConstant(ConstantInt::get(getContext(), Val));
413 }
414 
415 const SCEV *
416 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
417   IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
418   return getConstant(ConstantInt::get(ITy, V, isSigned));
419 }
420 
421 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
422                            unsigned SCEVTy, const SCEV *op, Type *ty)
423   : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
424 
425 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
426                                    const SCEV *op, Type *ty)
427   : SCEVCastExpr(ID, scTruncate, op, ty) {
428   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
429          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
430          "Cannot truncate non-integer value!");
431 }
432 
433 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
434                                        const SCEV *op, Type *ty)
435   : SCEVCastExpr(ID, scZeroExtend, op, ty) {
436   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
437          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
438          "Cannot zero extend non-integer value!");
439 }
440 
441 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
442                                        const SCEV *op, Type *ty)
443   : SCEVCastExpr(ID, scSignExtend, op, ty) {
444   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
445          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
446          "Cannot sign extend non-integer value!");
447 }
448 
449 void SCEVUnknown::deleted() {
450   // Clear this SCEVUnknown from various maps.
451   SE->forgetMemoizedResults(this);
452 
453   // Remove this SCEVUnknown from the uniquing map.
454   SE->UniqueSCEVs.RemoveNode(this);
455 
456   // Release the value.
457   setValPtr(nullptr);
458 }
459 
460 void SCEVUnknown::allUsesReplacedWith(Value *New) {
461   // Remove this SCEVUnknown from the uniquing map.
462   SE->UniqueSCEVs.RemoveNode(this);
463 
464   // Update this SCEVUnknown to point to the new value. This is needed
465   // because there may still be outstanding SCEVs which still point to
466   // this SCEVUnknown.
467   setValPtr(New);
468 }
469 
470 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
471   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
472     if (VCE->getOpcode() == Instruction::PtrToInt)
473       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
474         if (CE->getOpcode() == Instruction::GetElementPtr &&
475             CE->getOperand(0)->isNullValue() &&
476             CE->getNumOperands() == 2)
477           if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
478             if (CI->isOne()) {
479               AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
480                                  ->getElementType();
481               return true;
482             }
483 
484   return false;
485 }
486 
487 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
488   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
489     if (VCE->getOpcode() == Instruction::PtrToInt)
490       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
491         if (CE->getOpcode() == Instruction::GetElementPtr &&
492             CE->getOperand(0)->isNullValue()) {
493           Type *Ty =
494             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
495           if (StructType *STy = dyn_cast<StructType>(Ty))
496             if (!STy->isPacked() &&
497                 CE->getNumOperands() == 3 &&
498                 CE->getOperand(1)->isNullValue()) {
499               if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
500                 if (CI->isOne() &&
501                     STy->getNumElements() == 2 &&
502                     STy->getElementType(0)->isIntegerTy(1)) {
503                   AllocTy = STy->getElementType(1);
504                   return true;
505                 }
506             }
507         }
508 
509   return false;
510 }
511 
512 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
513   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
514     if (VCE->getOpcode() == Instruction::PtrToInt)
515       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
516         if (CE->getOpcode() == Instruction::GetElementPtr &&
517             CE->getNumOperands() == 3 &&
518             CE->getOperand(0)->isNullValue() &&
519             CE->getOperand(1)->isNullValue()) {
520           Type *Ty =
521             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
522           // Ignore vector types here so that ScalarEvolutionExpander doesn't
523           // emit getelementptrs that index into vectors.
524           if (Ty->isStructTy() || Ty->isArrayTy()) {
525             CTy = Ty;
526             FieldNo = CE->getOperand(2);
527             return true;
528           }
529         }
530 
531   return false;
532 }
533 
534 //===----------------------------------------------------------------------===//
535 //                               SCEV Utilities
536 //===----------------------------------------------------------------------===//
537 
538 /// Compare the two values \p LV and \p RV in terms of their "complexity" where
539 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order
540 /// operands in SCEV expressions.  \p EqCache is a set of pairs of values that
541 /// have been previously deemed to be "equally complex" by this routine.  It is
542 /// intended to avoid exponential time complexity in cases like:
543 ///
544 ///   %a = f(%x, %y)
545 ///   %b = f(%a, %a)
546 ///   %c = f(%b, %b)
547 ///
548 ///   %d = f(%x, %y)
549 ///   %e = f(%d, %d)
550 ///   %f = f(%e, %e)
551 ///
552 ///   CompareValueComplexity(%f, %c)
553 ///
554 /// Since we do not continue running this routine on expression trees once we
555 /// have seen unequal values, there is no need to track them in the cache.
556 static int
557 CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue,
558                        const LoopInfo *const LI, Value *LV, Value *RV,
559                        unsigned Depth) {
560   if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV))
561     return 0;
562 
563   // Order pointer values after integer values. This helps SCEVExpander form
564   // GEPs.
565   bool LIsPointer = LV->getType()->isPointerTy(),
566        RIsPointer = RV->getType()->isPointerTy();
567   if (LIsPointer != RIsPointer)
568     return (int)LIsPointer - (int)RIsPointer;
569 
570   // Compare getValueID values.
571   unsigned LID = LV->getValueID(), RID = RV->getValueID();
572   if (LID != RID)
573     return (int)LID - (int)RID;
574 
575   // Sort arguments by their position.
576   if (const auto *LA = dyn_cast<Argument>(LV)) {
577     const auto *RA = cast<Argument>(RV);
578     unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
579     return (int)LArgNo - (int)RArgNo;
580   }
581 
582   if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
583     const auto *RGV = cast<GlobalValue>(RV);
584 
585     const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
586       auto LT = GV->getLinkage();
587       return !(GlobalValue::isPrivateLinkage(LT) ||
588                GlobalValue::isInternalLinkage(LT));
589     };
590 
591     // Use the names to distinguish the two values, but only if the
592     // names are semantically important.
593     if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
594       return LGV->getName().compare(RGV->getName());
595   }
596 
597   // For instructions, compare their loop depth, and their operand count.  This
598   // is pretty loose.
599   if (const auto *LInst = dyn_cast<Instruction>(LV)) {
600     const auto *RInst = cast<Instruction>(RV);
601 
602     // Compare loop depths.
603     const BasicBlock *LParent = LInst->getParent(),
604                      *RParent = RInst->getParent();
605     if (LParent != RParent) {
606       unsigned LDepth = LI->getLoopDepth(LParent),
607                RDepth = LI->getLoopDepth(RParent);
608       if (LDepth != RDepth)
609         return (int)LDepth - (int)RDepth;
610     }
611 
612     // Compare the number of operands.
613     unsigned LNumOps = LInst->getNumOperands(),
614              RNumOps = RInst->getNumOperands();
615     if (LNumOps != RNumOps)
616       return (int)LNumOps - (int)RNumOps;
617 
618     for (unsigned Idx : seq(0u, LNumOps)) {
619       int Result =
620           CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx),
621                                  RInst->getOperand(Idx), Depth + 1);
622       if (Result != 0)
623         return Result;
624     }
625   }
626 
627   EqCacheValue.unionSets(LV, RV);
628   return 0;
629 }
630 
631 // Return negative, zero, or positive, if LHS is less than, equal to, or greater
632 // than RHS, respectively. A three-way result allows recursive comparisons to be
633 // more efficient.
634 static int CompareSCEVComplexity(
635     EquivalenceClasses<const SCEV *> &EqCacheSCEV,
636     EquivalenceClasses<const Value *> &EqCacheValue,
637     const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS,
638     DominatorTree &DT, unsigned Depth = 0) {
639   // Fast-path: SCEVs are uniqued so we can do a quick equality check.
640   if (LHS == RHS)
641     return 0;
642 
643   // Primarily, sort the SCEVs by their getSCEVType().
644   unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
645   if (LType != RType)
646     return (int)LType - (int)RType;
647 
648   if (Depth > MaxSCEVCompareDepth || EqCacheSCEV.isEquivalent(LHS, RHS))
649     return 0;
650   // Aside from the getSCEVType() ordering, the particular ordering
651   // isn't very important except that it's beneficial to be consistent,
652   // so that (a + b) and (b + a) don't end up as different expressions.
653   switch (static_cast<SCEVTypes>(LType)) {
654   case scUnknown: {
655     const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
656     const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
657 
658     int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(),
659                                    RU->getValue(), Depth + 1);
660     if (X == 0)
661       EqCacheSCEV.unionSets(LHS, RHS);
662     return X;
663   }
664 
665   case scConstant: {
666     const SCEVConstant *LC = cast<SCEVConstant>(LHS);
667     const SCEVConstant *RC = cast<SCEVConstant>(RHS);
668 
669     // Compare constant values.
670     const APInt &LA = LC->getAPInt();
671     const APInt &RA = RC->getAPInt();
672     unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
673     if (LBitWidth != RBitWidth)
674       return (int)LBitWidth - (int)RBitWidth;
675     return LA.ult(RA) ? -1 : 1;
676   }
677 
678   case scAddRecExpr: {
679     const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
680     const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
681 
682     // There is always a dominance between two recs that are used by one SCEV,
683     // so we can safely sort recs by loop header dominance. We require such
684     // order in getAddExpr.
685     const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
686     if (LLoop != RLoop) {
687       const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
688       assert(LHead != RHead && "Two loops share the same header?");
689       if (DT.dominates(LHead, RHead))
690         return 1;
691       else
692         assert(DT.dominates(RHead, LHead) &&
693                "No dominance between recurrences used by one SCEV?");
694       return -1;
695     }
696 
697     // Addrec complexity grows with operand count.
698     unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
699     if (LNumOps != RNumOps)
700       return (int)LNumOps - (int)RNumOps;
701 
702     // Compare NoWrap flags.
703     if (LA->getNoWrapFlags() != RA->getNoWrapFlags())
704       return (int)LA->getNoWrapFlags() - (int)RA->getNoWrapFlags();
705 
706     // Lexicographically compare.
707     for (unsigned i = 0; i != LNumOps; ++i) {
708       int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
709                                     LA->getOperand(i), RA->getOperand(i), DT,
710                                     Depth + 1);
711       if (X != 0)
712         return X;
713     }
714     EqCacheSCEV.unionSets(LHS, RHS);
715     return 0;
716   }
717 
718   case scAddExpr:
719   case scMulExpr:
720   case scSMaxExpr:
721   case scUMaxExpr: {
722     const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
723     const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
724 
725     // Lexicographically compare n-ary expressions.
726     unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
727     if (LNumOps != RNumOps)
728       return (int)LNumOps - (int)RNumOps;
729 
730     // Compare NoWrap flags.
731     if (LC->getNoWrapFlags() != RC->getNoWrapFlags())
732       return (int)LC->getNoWrapFlags() - (int)RC->getNoWrapFlags();
733 
734     for (unsigned i = 0; i != LNumOps; ++i) {
735       int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
736                                     LC->getOperand(i), RC->getOperand(i), DT,
737                                     Depth + 1);
738       if (X != 0)
739         return X;
740     }
741     EqCacheSCEV.unionSets(LHS, RHS);
742     return 0;
743   }
744 
745   case scUDivExpr: {
746     const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
747     const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
748 
749     // Lexicographically compare udiv expressions.
750     int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(),
751                                   RC->getLHS(), DT, Depth + 1);
752     if (X != 0)
753       return X;
754     X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(),
755                               RC->getRHS(), DT, Depth + 1);
756     if (X == 0)
757       EqCacheSCEV.unionSets(LHS, RHS);
758     return X;
759   }
760 
761   case scTruncate:
762   case scZeroExtend:
763   case scSignExtend: {
764     const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
765     const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
766 
767     // Compare cast expressions by operand.
768     int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
769                                   LC->getOperand(), RC->getOperand(), DT,
770                                   Depth + 1);
771     if (X == 0)
772       EqCacheSCEV.unionSets(LHS, RHS);
773     return X;
774   }
775 
776   case scCouldNotCompute:
777     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
778   }
779   llvm_unreachable("Unknown SCEV kind!");
780 }
781 
782 /// Given a list of SCEV objects, order them by their complexity, and group
783 /// objects of the same complexity together by value.  When this routine is
784 /// finished, we know that any duplicates in the vector are consecutive and that
785 /// complexity is monotonically increasing.
786 ///
787 /// Note that we go take special precautions to ensure that we get deterministic
788 /// results from this routine.  In other words, we don't want the results of
789 /// this to depend on where the addresses of various SCEV objects happened to
790 /// land in memory.
791 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
792                               LoopInfo *LI, DominatorTree &DT) {
793   if (Ops.size() < 2) return;  // Noop
794 
795   EquivalenceClasses<const SCEV *> EqCacheSCEV;
796   EquivalenceClasses<const Value *> EqCacheValue;
797   if (Ops.size() == 2) {
798     // This is the common case, which also happens to be trivially simple.
799     // Special case it.
800     const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
801     if (CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, RHS, LHS, DT) < 0)
802       std::swap(LHS, RHS);
803     return;
804   }
805 
806   // Do the rough sort by complexity.
807   std::stable_sort(Ops.begin(), Ops.end(),
808                    [&](const SCEV *LHS, const SCEV *RHS) {
809                      return CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
810                                                   LHS, RHS, DT) < 0;
811                    });
812 
813   // Now that we are sorted by complexity, group elements of the same
814   // complexity.  Note that this is, at worst, N^2, but the vector is likely to
815   // be extremely short in practice.  Note that we take this approach because we
816   // do not want to depend on the addresses of the objects we are grouping.
817   for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
818     const SCEV *S = Ops[i];
819     unsigned Complexity = S->getSCEVType();
820 
821     // If there are any objects of the same complexity and same value as this
822     // one, group them.
823     for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
824       if (Ops[j] == S) { // Found a duplicate.
825         // Move it to immediately after i'th element.
826         std::swap(Ops[i+1], Ops[j]);
827         ++i;   // no need to rescan it.
828         if (i == e-2) return;  // Done!
829       }
830     }
831   }
832 }
833 
834 // Returns the size of the SCEV S.
835 static inline int sizeOfSCEV(const SCEV *S) {
836   struct FindSCEVSize {
837     int Size = 0;
838 
839     FindSCEVSize() = default;
840 
841     bool follow(const SCEV *S) {
842       ++Size;
843       // Keep looking at all operands of S.
844       return true;
845     }
846 
847     bool isDone() const {
848       return false;
849     }
850   };
851 
852   FindSCEVSize F;
853   SCEVTraversal<FindSCEVSize> ST(F);
854   ST.visitAll(S);
855   return F.Size;
856 }
857 
858 namespace {
859 
860 struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> {
861 public:
862   // Computes the Quotient and Remainder of the division of Numerator by
863   // Denominator.
864   static void divide(ScalarEvolution &SE, const SCEV *Numerator,
865                      const SCEV *Denominator, const SCEV **Quotient,
866                      const SCEV **Remainder) {
867     assert(Numerator && Denominator && "Uninitialized SCEV");
868 
869     SCEVDivision D(SE, Numerator, Denominator);
870 
871     // Check for the trivial case here to avoid having to check for it in the
872     // rest of the code.
873     if (Numerator == Denominator) {
874       *Quotient = D.One;
875       *Remainder = D.Zero;
876       return;
877     }
878 
879     if (Numerator->isZero()) {
880       *Quotient = D.Zero;
881       *Remainder = D.Zero;
882       return;
883     }
884 
885     // A simple case when N/1. The quotient is N.
886     if (Denominator->isOne()) {
887       *Quotient = Numerator;
888       *Remainder = D.Zero;
889       return;
890     }
891 
892     // Split the Denominator when it is a product.
893     if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) {
894       const SCEV *Q, *R;
895       *Quotient = Numerator;
896       for (const SCEV *Op : T->operands()) {
897         divide(SE, *Quotient, Op, &Q, &R);
898         *Quotient = Q;
899 
900         // Bail out when the Numerator is not divisible by one of the terms of
901         // the Denominator.
902         if (!R->isZero()) {
903           *Quotient = D.Zero;
904           *Remainder = Numerator;
905           return;
906         }
907       }
908       *Remainder = D.Zero;
909       return;
910     }
911 
912     D.visit(Numerator);
913     *Quotient = D.Quotient;
914     *Remainder = D.Remainder;
915   }
916 
917   // Except in the trivial case described above, we do not know how to divide
918   // Expr by Denominator for the following functions with empty implementation.
919   void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {}
920   void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {}
921   void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {}
922   void visitUDivExpr(const SCEVUDivExpr *Numerator) {}
923   void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {}
924   void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {}
925   void visitUnknown(const SCEVUnknown *Numerator) {}
926   void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {}
927 
928   void visitConstant(const SCEVConstant *Numerator) {
929     if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) {
930       APInt NumeratorVal = Numerator->getAPInt();
931       APInt DenominatorVal = D->getAPInt();
932       uint32_t NumeratorBW = NumeratorVal.getBitWidth();
933       uint32_t DenominatorBW = DenominatorVal.getBitWidth();
934 
935       if (NumeratorBW > DenominatorBW)
936         DenominatorVal = DenominatorVal.sext(NumeratorBW);
937       else if (NumeratorBW < DenominatorBW)
938         NumeratorVal = NumeratorVal.sext(DenominatorBW);
939 
940       APInt QuotientVal(NumeratorVal.getBitWidth(), 0);
941       APInt RemainderVal(NumeratorVal.getBitWidth(), 0);
942       APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal);
943       Quotient = SE.getConstant(QuotientVal);
944       Remainder = SE.getConstant(RemainderVal);
945       return;
946     }
947   }
948 
949   void visitAddRecExpr(const SCEVAddRecExpr *Numerator) {
950     const SCEV *StartQ, *StartR, *StepQ, *StepR;
951     if (!Numerator->isAffine())
952       return cannotDivide(Numerator);
953     divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR);
954     divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR);
955     // Bail out if the types do not match.
956     Type *Ty = Denominator->getType();
957     if (Ty != StartQ->getType() || Ty != StartR->getType() ||
958         Ty != StepQ->getType() || Ty != StepR->getType())
959       return cannotDivide(Numerator);
960     Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(),
961                                 Numerator->getNoWrapFlags());
962     Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(),
963                                  Numerator->getNoWrapFlags());
964   }
965 
966   void visitAddExpr(const SCEVAddExpr *Numerator) {
967     SmallVector<const SCEV *, 2> Qs, Rs;
968     Type *Ty = Denominator->getType();
969 
970     for (const SCEV *Op : Numerator->operands()) {
971       const SCEV *Q, *R;
972       divide(SE, Op, Denominator, &Q, &R);
973 
974       // Bail out if types do not match.
975       if (Ty != Q->getType() || Ty != R->getType())
976         return cannotDivide(Numerator);
977 
978       Qs.push_back(Q);
979       Rs.push_back(R);
980     }
981 
982     if (Qs.size() == 1) {
983       Quotient = Qs[0];
984       Remainder = Rs[0];
985       return;
986     }
987 
988     Quotient = SE.getAddExpr(Qs);
989     Remainder = SE.getAddExpr(Rs);
990   }
991 
992   void visitMulExpr(const SCEVMulExpr *Numerator) {
993     SmallVector<const SCEV *, 2> Qs;
994     Type *Ty = Denominator->getType();
995 
996     bool FoundDenominatorTerm = false;
997     for (const SCEV *Op : Numerator->operands()) {
998       // Bail out if types do not match.
999       if (Ty != Op->getType())
1000         return cannotDivide(Numerator);
1001 
1002       if (FoundDenominatorTerm) {
1003         Qs.push_back(Op);
1004         continue;
1005       }
1006 
1007       // Check whether Denominator divides one of the product operands.
1008       const SCEV *Q, *R;
1009       divide(SE, Op, Denominator, &Q, &R);
1010       if (!R->isZero()) {
1011         Qs.push_back(Op);
1012         continue;
1013       }
1014 
1015       // Bail out if types do not match.
1016       if (Ty != Q->getType())
1017         return cannotDivide(Numerator);
1018 
1019       FoundDenominatorTerm = true;
1020       Qs.push_back(Q);
1021     }
1022 
1023     if (FoundDenominatorTerm) {
1024       Remainder = Zero;
1025       if (Qs.size() == 1)
1026         Quotient = Qs[0];
1027       else
1028         Quotient = SE.getMulExpr(Qs);
1029       return;
1030     }
1031 
1032     if (!isa<SCEVUnknown>(Denominator))
1033       return cannotDivide(Numerator);
1034 
1035     // The Remainder is obtained by replacing Denominator by 0 in Numerator.
1036     ValueToValueMap RewriteMap;
1037     RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
1038         cast<SCEVConstant>(Zero)->getValue();
1039     Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
1040 
1041     if (Remainder->isZero()) {
1042       // The Quotient is obtained by replacing Denominator by 1 in Numerator.
1043       RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
1044           cast<SCEVConstant>(One)->getValue();
1045       Quotient =
1046           SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
1047       return;
1048     }
1049 
1050     // Quotient is (Numerator - Remainder) divided by Denominator.
1051     const SCEV *Q, *R;
1052     const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder);
1053     // This SCEV does not seem to simplify: fail the division here.
1054     if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator))
1055       return cannotDivide(Numerator);
1056     divide(SE, Diff, Denominator, &Q, &R);
1057     if (R != Zero)
1058       return cannotDivide(Numerator);
1059     Quotient = Q;
1060   }
1061 
1062 private:
1063   SCEVDivision(ScalarEvolution &S, const SCEV *Numerator,
1064                const SCEV *Denominator)
1065       : SE(S), Denominator(Denominator) {
1066     Zero = SE.getZero(Denominator->getType());
1067     One = SE.getOne(Denominator->getType());
1068 
1069     // We generally do not know how to divide Expr by Denominator. We
1070     // initialize the division to a "cannot divide" state to simplify the rest
1071     // of the code.
1072     cannotDivide(Numerator);
1073   }
1074 
1075   // Convenience function for giving up on the division. We set the quotient to
1076   // be equal to zero and the remainder to be equal to the numerator.
1077   void cannotDivide(const SCEV *Numerator) {
1078     Quotient = Zero;
1079     Remainder = Numerator;
1080   }
1081 
1082   ScalarEvolution &SE;
1083   const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One;
1084 };
1085 
1086 } // end anonymous namespace
1087 
1088 //===----------------------------------------------------------------------===//
1089 //                      Simple SCEV method implementations
1090 //===----------------------------------------------------------------------===//
1091 
1092 /// Compute BC(It, K).  The result has width W.  Assume, K > 0.
1093 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
1094                                        ScalarEvolution &SE,
1095                                        Type *ResultTy) {
1096   // Handle the simplest case efficiently.
1097   if (K == 1)
1098     return SE.getTruncateOrZeroExtend(It, ResultTy);
1099 
1100   // We are using the following formula for BC(It, K):
1101   //
1102   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
1103   //
1104   // Suppose, W is the bitwidth of the return value.  We must be prepared for
1105   // overflow.  Hence, we must assure that the result of our computation is
1106   // equal to the accurate one modulo 2^W.  Unfortunately, division isn't
1107   // safe in modular arithmetic.
1108   //
1109   // However, this code doesn't use exactly that formula; the formula it uses
1110   // is something like the following, where T is the number of factors of 2 in
1111   // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
1112   // exponentiation:
1113   //
1114   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
1115   //
1116   // This formula is trivially equivalent to the previous formula.  However,
1117   // this formula can be implemented much more efficiently.  The trick is that
1118   // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
1119   // arithmetic.  To do exact division in modular arithmetic, all we have
1120   // to do is multiply by the inverse.  Therefore, this step can be done at
1121   // width W.
1122   //
1123   // The next issue is how to safely do the division by 2^T.  The way this
1124   // is done is by doing the multiplication step at a width of at least W + T
1125   // bits.  This way, the bottom W+T bits of the product are accurate. Then,
1126   // when we perform the division by 2^T (which is equivalent to a right shift
1127   // by T), the bottom W bits are accurate.  Extra bits are okay; they'll get
1128   // truncated out after the division by 2^T.
1129   //
1130   // In comparison to just directly using the first formula, this technique
1131   // is much more efficient; using the first formula requires W * K bits,
1132   // but this formula less than W + K bits. Also, the first formula requires
1133   // a division step, whereas this formula only requires multiplies and shifts.
1134   //
1135   // It doesn't matter whether the subtraction step is done in the calculation
1136   // width or the input iteration count's width; if the subtraction overflows,
1137   // the result must be zero anyway.  We prefer here to do it in the width of
1138   // the induction variable because it helps a lot for certain cases; CodeGen
1139   // isn't smart enough to ignore the overflow, which leads to much less
1140   // efficient code if the width of the subtraction is wider than the native
1141   // register width.
1142   //
1143   // (It's possible to not widen at all by pulling out factors of 2 before
1144   // the multiplication; for example, K=2 can be calculated as
1145   // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
1146   // extra arithmetic, so it's not an obvious win, and it gets
1147   // much more complicated for K > 3.)
1148 
1149   // Protection from insane SCEVs; this bound is conservative,
1150   // but it probably doesn't matter.
1151   if (K > 1000)
1152     return SE.getCouldNotCompute();
1153 
1154   unsigned W = SE.getTypeSizeInBits(ResultTy);
1155 
1156   // Calculate K! / 2^T and T; we divide out the factors of two before
1157   // multiplying for calculating K! / 2^T to avoid overflow.
1158   // Other overflow doesn't matter because we only care about the bottom
1159   // W bits of the result.
1160   APInt OddFactorial(W, 1);
1161   unsigned T = 1;
1162   for (unsigned i = 3; i <= K; ++i) {
1163     APInt Mult(W, i);
1164     unsigned TwoFactors = Mult.countTrailingZeros();
1165     T += TwoFactors;
1166     Mult.lshrInPlace(TwoFactors);
1167     OddFactorial *= Mult;
1168   }
1169 
1170   // We need at least W + T bits for the multiplication step
1171   unsigned CalculationBits = W + T;
1172 
1173   // Calculate 2^T, at width T+W.
1174   APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
1175 
1176   // Calculate the multiplicative inverse of K! / 2^T;
1177   // this multiplication factor will perform the exact division by
1178   // K! / 2^T.
1179   APInt Mod = APInt::getSignedMinValue(W+1);
1180   APInt MultiplyFactor = OddFactorial.zext(W+1);
1181   MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
1182   MultiplyFactor = MultiplyFactor.trunc(W);
1183 
1184   // Calculate the product, at width T+W
1185   IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
1186                                                       CalculationBits);
1187   const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
1188   for (unsigned i = 1; i != K; ++i) {
1189     const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
1190     Dividend = SE.getMulExpr(Dividend,
1191                              SE.getTruncateOrZeroExtend(S, CalculationTy));
1192   }
1193 
1194   // Divide by 2^T
1195   const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
1196 
1197   // Truncate the result, and divide by K! / 2^T.
1198 
1199   return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1200                        SE.getTruncateOrZeroExtend(DivResult, ResultTy));
1201 }
1202 
1203 /// Return the value of this chain of recurrences at the specified iteration
1204 /// number.  We can evaluate this recurrence by multiplying each element in the
1205 /// chain by the binomial coefficient corresponding to it.  In other words, we
1206 /// can evaluate {A,+,B,+,C,+,D} as:
1207 ///
1208 ///   A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
1209 ///
1210 /// where BC(It, k) stands for binomial coefficient.
1211 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
1212                                                 ScalarEvolution &SE) const {
1213   const SCEV *Result = getStart();
1214   for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1215     // The computation is correct in the face of overflow provided that the
1216     // multiplication is performed _after_ the evaluation of the binomial
1217     // coefficient.
1218     const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
1219     if (isa<SCEVCouldNotCompute>(Coeff))
1220       return Coeff;
1221 
1222     Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
1223   }
1224   return Result;
1225 }
1226 
1227 //===----------------------------------------------------------------------===//
1228 //                    SCEV Expression folder implementations
1229 //===----------------------------------------------------------------------===//
1230 
1231 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
1232                                              Type *Ty) {
1233   assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1234          "This is not a truncating conversion!");
1235   assert(isSCEVable(Ty) &&
1236          "This is not a conversion to a SCEVable type!");
1237   Ty = getEffectiveSCEVType(Ty);
1238 
1239   FoldingSetNodeID ID;
1240   ID.AddInteger(scTruncate);
1241   ID.AddPointer(Op);
1242   ID.AddPointer(Ty);
1243   void *IP = nullptr;
1244   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1245 
1246   // Fold if the operand is constant.
1247   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1248     return getConstant(
1249       cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1250 
1251   // trunc(trunc(x)) --> trunc(x)
1252   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
1253     return getTruncateExpr(ST->getOperand(), Ty);
1254 
1255   // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1256   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1257     return getTruncateOrSignExtend(SS->getOperand(), Ty);
1258 
1259   // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1260   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1261     return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
1262 
1263   // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can
1264   // eliminate all the truncates, or we replace other casts with truncates.
1265   if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) {
1266     SmallVector<const SCEV *, 4> Operands;
1267     bool hasTrunc = false;
1268     for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) {
1269       const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty);
1270       if (!isa<SCEVCastExpr>(SA->getOperand(i)))
1271         hasTrunc = isa<SCEVTruncateExpr>(S);
1272       Operands.push_back(S);
1273     }
1274     if (!hasTrunc)
1275       return getAddExpr(Operands);
1276     // In spite we checked in the beginning that ID is not in the cache,
1277     // it is possible that during recursion and different modification
1278     // ID came to cache, so if we found it, just return it.
1279     if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1280       return S;
1281   }
1282 
1283   // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can
1284   // eliminate all the truncates, or we replace other casts with truncates.
1285   if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) {
1286     SmallVector<const SCEV *, 4> Operands;
1287     bool hasTrunc = false;
1288     for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) {
1289       const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty);
1290       if (!isa<SCEVCastExpr>(SM->getOperand(i)))
1291         hasTrunc = isa<SCEVTruncateExpr>(S);
1292       Operands.push_back(S);
1293     }
1294     if (!hasTrunc)
1295       return getMulExpr(Operands);
1296     // In spite we checked in the beginning that ID is not in the cache,
1297     // it is possible that during recursion and different modification
1298     // ID came to cache, so if we found it, just return it.
1299     if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1300       return S;
1301   }
1302 
1303   // If the input value is a chrec scev, truncate the chrec's operands.
1304   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1305     SmallVector<const SCEV *, 4> Operands;
1306     for (const SCEV *Op : AddRec->operands())
1307       Operands.push_back(getTruncateExpr(Op, Ty));
1308     return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1309   }
1310 
1311   // The cast wasn't folded; create an explicit cast node. We can reuse
1312   // the existing insert position since if we get here, we won't have
1313   // made any changes which would invalidate it.
1314   SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1315                                                  Op, Ty);
1316   UniqueSCEVs.InsertNode(S, IP);
1317   addToLoopUseLists(S);
1318   return S;
1319 }
1320 
1321 // Get the limit of a recurrence such that incrementing by Step cannot cause
1322 // signed overflow as long as the value of the recurrence within the
1323 // loop does not exceed this limit before incrementing.
1324 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1325                                                  ICmpInst::Predicate *Pred,
1326                                                  ScalarEvolution *SE) {
1327   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1328   if (SE->isKnownPositive(Step)) {
1329     *Pred = ICmpInst::ICMP_SLT;
1330     return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1331                            SE->getSignedRangeMax(Step));
1332   }
1333   if (SE->isKnownNegative(Step)) {
1334     *Pred = ICmpInst::ICMP_SGT;
1335     return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1336                            SE->getSignedRangeMin(Step));
1337   }
1338   return nullptr;
1339 }
1340 
1341 // Get the limit of a recurrence such that incrementing by Step cannot cause
1342 // unsigned overflow as long as the value of the recurrence within the loop does
1343 // not exceed this limit before incrementing.
1344 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1345                                                    ICmpInst::Predicate *Pred,
1346                                                    ScalarEvolution *SE) {
1347   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1348   *Pred = ICmpInst::ICMP_ULT;
1349 
1350   return SE->getConstant(APInt::getMinValue(BitWidth) -
1351                          SE->getUnsignedRangeMax(Step));
1352 }
1353 
1354 namespace {
1355 
1356 struct ExtendOpTraitsBase {
1357   typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *,
1358                                                           unsigned);
1359 };
1360 
1361 // Used to make code generic over signed and unsigned overflow.
1362 template <typename ExtendOp> struct ExtendOpTraits {
1363   // Members present:
1364   //
1365   // static const SCEV::NoWrapFlags WrapType;
1366   //
1367   // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1368   //
1369   // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1370   //                                           ICmpInst::Predicate *Pred,
1371   //                                           ScalarEvolution *SE);
1372 };
1373 
1374 template <>
1375 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1376   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1377 
1378   static const GetExtendExprTy GetExtendExpr;
1379 
1380   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1381                                              ICmpInst::Predicate *Pred,
1382                                              ScalarEvolution *SE) {
1383     return getSignedOverflowLimitForStep(Step, Pred, SE);
1384   }
1385 };
1386 
1387 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1388     SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr;
1389 
1390 template <>
1391 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1392   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1393 
1394   static const GetExtendExprTy GetExtendExpr;
1395 
1396   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1397                                              ICmpInst::Predicate *Pred,
1398                                              ScalarEvolution *SE) {
1399     return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1400   }
1401 };
1402 
1403 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1404     SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr;
1405 
1406 } // end anonymous namespace
1407 
1408 // The recurrence AR has been shown to have no signed/unsigned wrap or something
1409 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1410 // easily prove NSW/NUW for its preincrement or postincrement sibling. This
1411 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1412 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1413 // expression "Step + sext/zext(PreIncAR)" is congruent with
1414 // "sext/zext(PostIncAR)"
1415 template <typename ExtendOpTy>
1416 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1417                                         ScalarEvolution *SE, unsigned Depth) {
1418   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1419   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1420 
1421   const Loop *L = AR->getLoop();
1422   const SCEV *Start = AR->getStart();
1423   const SCEV *Step = AR->getStepRecurrence(*SE);
1424 
1425   // Check for a simple looking step prior to loop entry.
1426   const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1427   if (!SA)
1428     return nullptr;
1429 
1430   // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1431   // subtraction is expensive. For this purpose, perform a quick and dirty
1432   // difference, by checking for Step in the operand list.
1433   SmallVector<const SCEV *, 4> DiffOps;
1434   for (const SCEV *Op : SA->operands())
1435     if (Op != Step)
1436       DiffOps.push_back(Op);
1437 
1438   if (DiffOps.size() == SA->getNumOperands())
1439     return nullptr;
1440 
1441   // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1442   // `Step`:
1443 
1444   // 1. NSW/NUW flags on the step increment.
1445   auto PreStartFlags =
1446     ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
1447   const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1448   const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1449       SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1450 
1451   // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1452   // "S+X does not sign/unsign-overflow".
1453   //
1454 
1455   const SCEV *BECount = SE->getBackedgeTakenCount(L);
1456   if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1457       !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1458     return PreStart;
1459 
1460   // 2. Direct overflow check on the step operation's expression.
1461   unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1462   Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1463   const SCEV *OperandExtendedStart =
1464       SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
1465                      (SE->*GetExtendExpr)(Step, WideTy, Depth));
1466   if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
1467     if (PreAR && AR->getNoWrapFlags(WrapType)) {
1468       // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1469       // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1470       // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`.  Cache this fact.
1471       const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType);
1472     }
1473     return PreStart;
1474   }
1475 
1476   // 3. Loop precondition.
1477   ICmpInst::Predicate Pred;
1478   const SCEV *OverflowLimit =
1479       ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1480 
1481   if (OverflowLimit &&
1482       SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1483     return PreStart;
1484 
1485   return nullptr;
1486 }
1487 
1488 // Get the normalized zero or sign extended expression for this AddRec's Start.
1489 template <typename ExtendOpTy>
1490 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1491                                         ScalarEvolution *SE,
1492                                         unsigned Depth) {
1493   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1494 
1495   const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth);
1496   if (!PreStart)
1497     return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth);
1498 
1499   return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty,
1500                                              Depth),
1501                         (SE->*GetExtendExpr)(PreStart, Ty, Depth));
1502 }
1503 
1504 // Try to prove away overflow by looking at "nearby" add recurrences.  A
1505 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1506 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1507 //
1508 // Formally:
1509 //
1510 //     {S,+,X} == {S-T,+,X} + T
1511 //  => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1512 //
1513 // If ({S-T,+,X} + T) does not overflow  ... (1)
1514 //
1515 //  RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1516 //
1517 // If {S-T,+,X} does not overflow  ... (2)
1518 //
1519 //  RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1520 //      == {Ext(S-T)+Ext(T),+,Ext(X)}
1521 //
1522 // If (S-T)+T does not overflow  ... (3)
1523 //
1524 //  RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1525 //      == {Ext(S),+,Ext(X)} == LHS
1526 //
1527 // Thus, if (1), (2) and (3) are true for some T, then
1528 //   Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1529 //
1530 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1531 // does not overflow" restricted to the 0th iteration.  Therefore we only need
1532 // to check for (1) and (2).
1533 //
1534 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1535 // is `Delta` (defined below).
1536 template <typename ExtendOpTy>
1537 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1538                                                 const SCEV *Step,
1539                                                 const Loop *L) {
1540   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1541 
1542   // We restrict `Start` to a constant to prevent SCEV from spending too much
1543   // time here.  It is correct (but more expensive) to continue with a
1544   // non-constant `Start` and do a general SCEV subtraction to compute
1545   // `PreStart` below.
1546   const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1547   if (!StartC)
1548     return false;
1549 
1550   APInt StartAI = StartC->getAPInt();
1551 
1552   for (unsigned Delta : {-2, -1, 1, 2}) {
1553     const SCEV *PreStart = getConstant(StartAI - Delta);
1554 
1555     FoldingSetNodeID ID;
1556     ID.AddInteger(scAddRecExpr);
1557     ID.AddPointer(PreStart);
1558     ID.AddPointer(Step);
1559     ID.AddPointer(L);
1560     void *IP = nullptr;
1561     const auto *PreAR =
1562       static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1563 
1564     // Give up if we don't already have the add recurrence we need because
1565     // actually constructing an add recurrence is relatively expensive.
1566     if (PreAR && PreAR->getNoWrapFlags(WrapType)) {  // proves (2)
1567       const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1568       ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1569       const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1570           DeltaS, &Pred, this);
1571       if (Limit && isKnownPredicate(Pred, PreAR, Limit))  // proves (1)
1572         return true;
1573     }
1574   }
1575 
1576   return false;
1577 }
1578 
1579 const SCEV *
1580 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1581   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1582          "This is not an extending conversion!");
1583   assert(isSCEVable(Ty) &&
1584          "This is not a conversion to a SCEVable type!");
1585   Ty = getEffectiveSCEVType(Ty);
1586 
1587   // Fold if the operand is constant.
1588   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1589     return getConstant(
1590       cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
1591 
1592   // zext(zext(x)) --> zext(x)
1593   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1594     return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1595 
1596   // Before doing any expensive analysis, check to see if we've already
1597   // computed a SCEV for this Op and Ty.
1598   FoldingSetNodeID ID;
1599   ID.AddInteger(scZeroExtend);
1600   ID.AddPointer(Op);
1601   ID.AddPointer(Ty);
1602   void *IP = nullptr;
1603   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1604   if (Depth > MaxExtDepth) {
1605     SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1606                                                      Op, Ty);
1607     UniqueSCEVs.InsertNode(S, IP);
1608     addToLoopUseLists(S);
1609     return S;
1610   }
1611 
1612   // zext(trunc(x)) --> zext(x) or x or trunc(x)
1613   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1614     // It's possible the bits taken off by the truncate were all zero bits. If
1615     // so, we should be able to simplify this further.
1616     const SCEV *X = ST->getOperand();
1617     ConstantRange CR = getUnsignedRange(X);
1618     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1619     unsigned NewBits = getTypeSizeInBits(Ty);
1620     if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1621             CR.zextOrTrunc(NewBits)))
1622       return getTruncateOrZeroExtend(X, Ty);
1623   }
1624 
1625   // If the input value is a chrec scev, and we can prove that the value
1626   // did not overflow the old, smaller, value, we can zero extend all of the
1627   // operands (often constants).  This allows analysis of something like
1628   // this:  for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1629   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1630     if (AR->isAffine()) {
1631       const SCEV *Start = AR->getStart();
1632       const SCEV *Step = AR->getStepRecurrence(*this);
1633       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1634       const Loop *L = AR->getLoop();
1635 
1636       if (!AR->hasNoUnsignedWrap()) {
1637         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1638         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1639       }
1640 
1641       // If we have special knowledge that this addrec won't overflow,
1642       // we don't need to do any further analysis.
1643       if (AR->hasNoUnsignedWrap())
1644         return getAddRecExpr(
1645             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1646             getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1647 
1648       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1649       // Note that this serves two purposes: It filters out loops that are
1650       // simply not analyzable, and it covers the case where this code is
1651       // being called from within backedge-taken count analysis, such that
1652       // attempting to ask for the backedge-taken count would likely result
1653       // in infinite recursion. In the later case, the analysis code will
1654       // cope with a conservative value, and it will take care to purge
1655       // that value once it has finished.
1656       const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1657       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1658         // Manually compute the final value for AR, checking for
1659         // overflow.
1660 
1661         // Check whether the backedge-taken count can be losslessly casted to
1662         // the addrec's type. The count is always unsigned.
1663         const SCEV *CastedMaxBECount =
1664           getTruncateOrZeroExtend(MaxBECount, Start->getType());
1665         const SCEV *RecastedMaxBECount =
1666           getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1667         if (MaxBECount == RecastedMaxBECount) {
1668           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1669           // Check whether Start+Step*MaxBECount has no unsigned overflow.
1670           const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step,
1671                                         SCEV::FlagAnyWrap, Depth + 1);
1672           const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul,
1673                                                           SCEV::FlagAnyWrap,
1674                                                           Depth + 1),
1675                                                WideTy, Depth + 1);
1676           const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
1677           const SCEV *WideMaxBECount =
1678             getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1679           const SCEV *OperandExtendedAdd =
1680             getAddExpr(WideStart,
1681                        getMulExpr(WideMaxBECount,
1682                                   getZeroExtendExpr(Step, WideTy, Depth + 1),
1683                                   SCEV::FlagAnyWrap, Depth + 1),
1684                        SCEV::FlagAnyWrap, Depth + 1);
1685           if (ZAdd == OperandExtendedAdd) {
1686             // Cache knowledge of AR NUW, which is propagated to this AddRec.
1687             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1688             // Return the expression with the addrec on the outside.
1689             return getAddRecExpr(
1690                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1691                                                          Depth + 1),
1692                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1693                 AR->getNoWrapFlags());
1694           }
1695           // Similar to above, only this time treat the step value as signed.
1696           // This covers loops that count down.
1697           OperandExtendedAdd =
1698             getAddExpr(WideStart,
1699                        getMulExpr(WideMaxBECount,
1700                                   getSignExtendExpr(Step, WideTy, Depth + 1),
1701                                   SCEV::FlagAnyWrap, Depth + 1),
1702                        SCEV::FlagAnyWrap, Depth + 1);
1703           if (ZAdd == OperandExtendedAdd) {
1704             // Cache knowledge of AR NW, which is propagated to this AddRec.
1705             // Negative step causes unsigned wrap, but it still can't self-wrap.
1706             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1707             // Return the expression with the addrec on the outside.
1708             return getAddRecExpr(
1709                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1710                                                          Depth + 1),
1711                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1712                 AR->getNoWrapFlags());
1713           }
1714         }
1715       }
1716 
1717       // Normally, in the cases we can prove no-overflow via a
1718       // backedge guarding condition, we can also compute a backedge
1719       // taken count for the loop.  The exceptions are assumptions and
1720       // guards present in the loop -- SCEV is not great at exploiting
1721       // these to compute max backedge taken counts, but can still use
1722       // these to prove lack of overflow.  Use this fact to avoid
1723       // doing extra work that may not pay off.
1724       if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1725           !AC.assumptions().empty()) {
1726         // If the backedge is guarded by a comparison with the pre-inc
1727         // value the addrec is safe. Also, if the entry is guarded by
1728         // a comparison with the start value and the backedge is
1729         // guarded by a comparison with the post-inc value, the addrec
1730         // is safe.
1731         if (isKnownPositive(Step)) {
1732           const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
1733                                       getUnsignedRangeMax(Step));
1734           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
1735               isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) {
1736             // Cache knowledge of AR NUW, which is propagated to this
1737             // AddRec.
1738             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1739             // Return the expression with the addrec on the outside.
1740             return getAddRecExpr(
1741                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1742                                                          Depth + 1),
1743                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1744                 AR->getNoWrapFlags());
1745           }
1746         } else if (isKnownNegative(Step)) {
1747           const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1748                                       getSignedRangeMin(Step));
1749           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1750               isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) {
1751             // Cache knowledge of AR NW, which is propagated to this
1752             // AddRec.  Negative step causes unsigned wrap, but it
1753             // still can't self-wrap.
1754             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1755             // Return the expression with the addrec on the outside.
1756             return getAddRecExpr(
1757                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1758                                                          Depth + 1),
1759                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1760                 AR->getNoWrapFlags());
1761           }
1762         }
1763       }
1764 
1765       if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1766         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1767         return getAddRecExpr(
1768             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1769             getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1770       }
1771     }
1772 
1773   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1774     // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1775     if (SA->hasNoUnsignedWrap()) {
1776       // If the addition does not unsign overflow then we can, by definition,
1777       // commute the zero extension with the addition operation.
1778       SmallVector<const SCEV *, 4> Ops;
1779       for (const auto *Op : SA->operands())
1780         Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1781       return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1);
1782     }
1783   }
1784 
1785   // The cast wasn't folded; create an explicit cast node.
1786   // Recompute the insert position, as it may have been invalidated.
1787   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1788   SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1789                                                    Op, Ty);
1790   UniqueSCEVs.InsertNode(S, IP);
1791   addToLoopUseLists(S);
1792   return S;
1793 }
1794 
1795 const SCEV *
1796 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1797   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1798          "This is not an extending conversion!");
1799   assert(isSCEVable(Ty) &&
1800          "This is not a conversion to a SCEVable type!");
1801   Ty = getEffectiveSCEVType(Ty);
1802 
1803   // Fold if the operand is constant.
1804   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1805     return getConstant(
1806       cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
1807 
1808   // sext(sext(x)) --> sext(x)
1809   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1810     return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1);
1811 
1812   // sext(zext(x)) --> zext(x)
1813   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1814     return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1815 
1816   // Before doing any expensive analysis, check to see if we've already
1817   // computed a SCEV for this Op and Ty.
1818   FoldingSetNodeID ID;
1819   ID.AddInteger(scSignExtend);
1820   ID.AddPointer(Op);
1821   ID.AddPointer(Ty);
1822   void *IP = nullptr;
1823   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1824   // Limit recursion depth.
1825   if (Depth > MaxExtDepth) {
1826     SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1827                                                      Op, Ty);
1828     UniqueSCEVs.InsertNode(S, IP);
1829     addToLoopUseLists(S);
1830     return S;
1831   }
1832 
1833   // sext(trunc(x)) --> sext(x) or x or trunc(x)
1834   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1835     // It's possible the bits taken off by the truncate were all sign bits. If
1836     // so, we should be able to simplify this further.
1837     const SCEV *X = ST->getOperand();
1838     ConstantRange CR = getSignedRange(X);
1839     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1840     unsigned NewBits = getTypeSizeInBits(Ty);
1841     if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1842             CR.sextOrTrunc(NewBits)))
1843       return getTruncateOrSignExtend(X, Ty);
1844   }
1845 
1846   // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2
1847   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1848     if (SA->getNumOperands() == 2) {
1849       auto *SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0));
1850       auto *SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1));
1851       if (SMul && SC1) {
1852         if (auto *SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) {
1853           const APInt &C1 = SC1->getAPInt();
1854           const APInt &C2 = SC2->getAPInt();
1855           if (C1.isStrictlyPositive() && C2.isStrictlyPositive() &&
1856               C2.ugt(C1) && C2.isPowerOf2())
1857             return getAddExpr(getSignExtendExpr(SC1, Ty, Depth + 1),
1858                               getSignExtendExpr(SMul, Ty, Depth + 1),
1859                               SCEV::FlagAnyWrap, Depth + 1);
1860         }
1861       }
1862     }
1863 
1864     // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1865     if (SA->hasNoSignedWrap()) {
1866       // If the addition does not sign overflow then we can, by definition,
1867       // commute the sign extension with the addition operation.
1868       SmallVector<const SCEV *, 4> Ops;
1869       for (const auto *Op : SA->operands())
1870         Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1));
1871       return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1);
1872     }
1873   }
1874   // If the input value is a chrec scev, and we can prove that the value
1875   // did not overflow the old, smaller, value, we can sign extend all of the
1876   // operands (often constants).  This allows analysis of something like
1877   // this:  for (signed char X = 0; X < 100; ++X) { int Y = X; }
1878   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1879     if (AR->isAffine()) {
1880       const SCEV *Start = AR->getStart();
1881       const SCEV *Step = AR->getStepRecurrence(*this);
1882       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1883       const Loop *L = AR->getLoop();
1884 
1885       if (!AR->hasNoSignedWrap()) {
1886         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1887         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1888       }
1889 
1890       // If we have special knowledge that this addrec won't overflow,
1891       // we don't need to do any further analysis.
1892       if (AR->hasNoSignedWrap())
1893         return getAddRecExpr(
1894             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
1895             getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW);
1896 
1897       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1898       // Note that this serves two purposes: It filters out loops that are
1899       // simply not analyzable, and it covers the case where this code is
1900       // being called from within backedge-taken count analysis, such that
1901       // attempting to ask for the backedge-taken count would likely result
1902       // in infinite recursion. In the later case, the analysis code will
1903       // cope with a conservative value, and it will take care to purge
1904       // that value once it has finished.
1905       const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1906       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1907         // Manually compute the final value for AR, checking for
1908         // overflow.
1909 
1910         // Check whether the backedge-taken count can be losslessly casted to
1911         // the addrec's type. The count is always unsigned.
1912         const SCEV *CastedMaxBECount =
1913           getTruncateOrZeroExtend(MaxBECount, Start->getType());
1914         const SCEV *RecastedMaxBECount =
1915           getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1916         if (MaxBECount == RecastedMaxBECount) {
1917           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1918           // Check whether Start+Step*MaxBECount has no signed overflow.
1919           const SCEV *SMul = getMulExpr(CastedMaxBECount, Step,
1920                                         SCEV::FlagAnyWrap, Depth + 1);
1921           const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul,
1922                                                           SCEV::FlagAnyWrap,
1923                                                           Depth + 1),
1924                                                WideTy, Depth + 1);
1925           const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
1926           const SCEV *WideMaxBECount =
1927             getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1928           const SCEV *OperandExtendedAdd =
1929             getAddExpr(WideStart,
1930                        getMulExpr(WideMaxBECount,
1931                                   getSignExtendExpr(Step, WideTy, Depth + 1),
1932                                   SCEV::FlagAnyWrap, Depth + 1),
1933                        SCEV::FlagAnyWrap, Depth + 1);
1934           if (SAdd == OperandExtendedAdd) {
1935             // Cache knowledge of AR NSW, which is propagated to this AddRec.
1936             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1937             // Return the expression with the addrec on the outside.
1938             return getAddRecExpr(
1939                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
1940                                                          Depth + 1),
1941                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1942                 AR->getNoWrapFlags());
1943           }
1944           // Similar to above, only this time treat the step value as unsigned.
1945           // This covers loops that count up with an unsigned step.
1946           OperandExtendedAdd =
1947             getAddExpr(WideStart,
1948                        getMulExpr(WideMaxBECount,
1949                                   getZeroExtendExpr(Step, WideTy, Depth + 1),
1950                                   SCEV::FlagAnyWrap, Depth + 1),
1951                        SCEV::FlagAnyWrap, Depth + 1);
1952           if (SAdd == OperandExtendedAdd) {
1953             // If AR wraps around then
1954             //
1955             //    abs(Step) * MaxBECount > unsigned-max(AR->getType())
1956             // => SAdd != OperandExtendedAdd
1957             //
1958             // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
1959             // (SAdd == OperandExtendedAdd => AR is NW)
1960 
1961             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1962 
1963             // Return the expression with the addrec on the outside.
1964             return getAddRecExpr(
1965                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
1966                                                          Depth + 1),
1967                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1968                 AR->getNoWrapFlags());
1969           }
1970         }
1971       }
1972 
1973       // Normally, in the cases we can prove no-overflow via a
1974       // backedge guarding condition, we can also compute a backedge
1975       // taken count for the loop.  The exceptions are assumptions and
1976       // guards present in the loop -- SCEV is not great at exploiting
1977       // these to compute max backedge taken counts, but can still use
1978       // these to prove lack of overflow.  Use this fact to avoid
1979       // doing extra work that may not pay off.
1980 
1981       if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1982           !AC.assumptions().empty()) {
1983         // If the backedge is guarded by a comparison with the pre-inc
1984         // value the addrec is safe. Also, if the entry is guarded by
1985         // a comparison with the start value and the backedge is
1986         // guarded by a comparison with the post-inc value, the addrec
1987         // is safe.
1988         ICmpInst::Predicate Pred;
1989         const SCEV *OverflowLimit =
1990             getSignedOverflowLimitForStep(Step, &Pred, this);
1991         if (OverflowLimit &&
1992             (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
1993              isKnownOnEveryIteration(Pred, AR, OverflowLimit))) {
1994           // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec.
1995           const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1996           return getAddRecExpr(
1997               getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
1998               getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1999         }
2000       }
2001 
2002       // If Start and Step are constants, check if we can apply this
2003       // transformation:
2004       // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2
2005       auto *SC1 = dyn_cast<SCEVConstant>(Start);
2006       auto *SC2 = dyn_cast<SCEVConstant>(Step);
2007       if (SC1 && SC2) {
2008         const APInt &C1 = SC1->getAPInt();
2009         const APInt &C2 = SC2->getAPInt();
2010         if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) &&
2011             C2.isPowerOf2()) {
2012           Start = getSignExtendExpr(Start, Ty, Depth + 1);
2013           const SCEV *NewAR = getAddRecExpr(getZero(AR->getType()), Step, L,
2014                                             AR->getNoWrapFlags());
2015           return getAddExpr(Start, getSignExtendExpr(NewAR, Ty, Depth + 1),
2016                             SCEV::FlagAnyWrap, Depth + 1);
2017         }
2018       }
2019 
2020       if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
2021         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
2022         return getAddRecExpr(
2023             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2024             getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2025       }
2026     }
2027 
2028   // If the input value is provably positive and we could not simplify
2029   // away the sext build a zext instead.
2030   if (isKnownNonNegative(Op))
2031     return getZeroExtendExpr(Op, Ty, Depth + 1);
2032 
2033   // The cast wasn't folded; create an explicit cast node.
2034   // Recompute the insert position, as it may have been invalidated.
2035   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2036   SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
2037                                                    Op, Ty);
2038   UniqueSCEVs.InsertNode(S, IP);
2039   addToLoopUseLists(S);
2040   return S;
2041 }
2042 
2043 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
2044 /// unspecified bits out to the given type.
2045 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
2046                                               Type *Ty) {
2047   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
2048          "This is not an extending conversion!");
2049   assert(isSCEVable(Ty) &&
2050          "This is not a conversion to a SCEVable type!");
2051   Ty = getEffectiveSCEVType(Ty);
2052 
2053   // Sign-extend negative constants.
2054   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
2055     if (SC->getAPInt().isNegative())
2056       return getSignExtendExpr(Op, Ty);
2057 
2058   // Peel off a truncate cast.
2059   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
2060     const SCEV *NewOp = T->getOperand();
2061     if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
2062       return getAnyExtendExpr(NewOp, Ty);
2063     return getTruncateOrNoop(NewOp, Ty);
2064   }
2065 
2066   // Next try a zext cast. If the cast is folded, use it.
2067   const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2068   if (!isa<SCEVZeroExtendExpr>(ZExt))
2069     return ZExt;
2070 
2071   // Next try a sext cast. If the cast is folded, use it.
2072   const SCEV *SExt = getSignExtendExpr(Op, Ty);
2073   if (!isa<SCEVSignExtendExpr>(SExt))
2074     return SExt;
2075 
2076   // Force the cast to be folded into the operands of an addrec.
2077   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2078     SmallVector<const SCEV *, 4> Ops;
2079     for (const SCEV *Op : AR->operands())
2080       Ops.push_back(getAnyExtendExpr(Op, Ty));
2081     return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2082   }
2083 
2084   // If the expression is obviously signed, use the sext cast value.
2085   if (isa<SCEVSMaxExpr>(Op))
2086     return SExt;
2087 
2088   // Absent any other information, use the zext cast value.
2089   return ZExt;
2090 }
2091 
2092 /// Process the given Ops list, which is a list of operands to be added under
2093 /// the given scale, update the given map. This is a helper function for
2094 /// getAddRecExpr. As an example of what it does, given a sequence of operands
2095 /// that would form an add expression like this:
2096 ///
2097 ///    m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2098 ///
2099 /// where A and B are constants, update the map with these values:
2100 ///
2101 ///    (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2102 ///
2103 /// and add 13 + A*B*29 to AccumulatedConstant.
2104 /// This will allow getAddRecExpr to produce this:
2105 ///
2106 ///    13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2107 ///
2108 /// This form often exposes folding opportunities that are hidden in
2109 /// the original operand list.
2110 ///
2111 /// Return true iff it appears that any interesting folding opportunities
2112 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
2113 /// the common case where no interesting opportunities are present, and
2114 /// is also used as a check to avoid infinite recursion.
2115 static bool
2116 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
2117                              SmallVectorImpl<const SCEV *> &NewOps,
2118                              APInt &AccumulatedConstant,
2119                              const SCEV *const *Ops, size_t NumOperands,
2120                              const APInt &Scale,
2121                              ScalarEvolution &SE) {
2122   bool Interesting = false;
2123 
2124   // Iterate over the add operands. They are sorted, with constants first.
2125   unsigned i = 0;
2126   while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2127     ++i;
2128     // Pull a buried constant out to the outside.
2129     if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2130       Interesting = true;
2131     AccumulatedConstant += Scale * C->getAPInt();
2132   }
2133 
2134   // Next comes everything else. We're especially interested in multiplies
2135   // here, but they're in the middle, so just visit the rest with one loop.
2136   for (; i != NumOperands; ++i) {
2137     const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
2138     if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2139       APInt NewScale =
2140           Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2141       if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2142         // A multiplication of a constant with another add; recurse.
2143         const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2144         Interesting |=
2145           CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2146                                        Add->op_begin(), Add->getNumOperands(),
2147                                        NewScale, SE);
2148       } else {
2149         // A multiplication of a constant with some other value. Update
2150         // the map.
2151         SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
2152         const SCEV *Key = SE.getMulExpr(MulOps);
2153         auto Pair = M.insert({Key, NewScale});
2154         if (Pair.second) {
2155           NewOps.push_back(Pair.first->first);
2156         } else {
2157           Pair.first->second += NewScale;
2158           // The map already had an entry for this value, which may indicate
2159           // a folding opportunity.
2160           Interesting = true;
2161         }
2162       }
2163     } else {
2164       // An ordinary operand. Update the map.
2165       std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
2166           M.insert({Ops[i], Scale});
2167       if (Pair.second) {
2168         NewOps.push_back(Pair.first->first);
2169       } else {
2170         Pair.first->second += Scale;
2171         // The map already had an entry for this value, which may indicate
2172         // a folding opportunity.
2173         Interesting = true;
2174       }
2175     }
2176   }
2177 
2178   return Interesting;
2179 }
2180 
2181 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2182 // `OldFlags' as can't-wrap behavior.  Infer a more aggressive set of
2183 // can't-overflow flags for the operation if possible.
2184 static SCEV::NoWrapFlags
2185 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
2186                       const SmallVectorImpl<const SCEV *> &Ops,
2187                       SCEV::NoWrapFlags Flags) {
2188   using namespace std::placeholders;
2189 
2190   using OBO = OverflowingBinaryOperator;
2191 
2192   bool CanAnalyze =
2193       Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
2194   (void)CanAnalyze;
2195   assert(CanAnalyze && "don't call from other places!");
2196 
2197   int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2198   SCEV::NoWrapFlags SignOrUnsignWrap =
2199       ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2200 
2201   // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2202   auto IsKnownNonNegative = [&](const SCEV *S) {
2203     return SE->isKnownNonNegative(S);
2204   };
2205 
2206   if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2207     Flags =
2208         ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
2209 
2210   SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2211 
2212   if (SignOrUnsignWrap != SignOrUnsignMask && Type == scAddExpr &&
2213       Ops.size() == 2 && isa<SCEVConstant>(Ops[0])) {
2214 
2215     // (A + C) --> (A + C)<nsw> if the addition does not sign overflow
2216     // (A + C) --> (A + C)<nuw> if the addition does not unsign overflow
2217 
2218     const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2219     if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2220       auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2221           Instruction::Add, C, OBO::NoSignedWrap);
2222       if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2223         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2224     }
2225     if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2226       auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2227           Instruction::Add, C, OBO::NoUnsignedWrap);
2228       if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2229         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2230     }
2231   }
2232 
2233   return Flags;
2234 }
2235 
2236 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) {
2237   if (!isLoopInvariant(S, L))
2238     return false;
2239   // If a value depends on a SCEVUnknown which is defined after the loop, we
2240   // conservatively assume that we cannot calculate it at the loop's entry.
2241   struct FindDominatedSCEVUnknown {
2242     bool Found = false;
2243     const Loop *L;
2244     DominatorTree &DT;
2245     LoopInfo &LI;
2246 
2247     FindDominatedSCEVUnknown(const Loop *L, DominatorTree &DT, LoopInfo &LI)
2248         : L(L), DT(DT), LI(LI) {}
2249 
2250     bool checkSCEVUnknown(const SCEVUnknown *SU) {
2251       if (auto *I = dyn_cast<Instruction>(SU->getValue())) {
2252         if (DT.dominates(L->getHeader(), I->getParent()))
2253           Found = true;
2254         else
2255           assert(DT.dominates(I->getParent(), L->getHeader()) &&
2256                  "No dominance relationship between SCEV and loop?");
2257       }
2258       return false;
2259     }
2260 
2261     bool follow(const SCEV *S) {
2262       switch (static_cast<SCEVTypes>(S->getSCEVType())) {
2263       case scConstant:
2264         return false;
2265       case scAddRecExpr:
2266       case scTruncate:
2267       case scZeroExtend:
2268       case scSignExtend:
2269       case scAddExpr:
2270       case scMulExpr:
2271       case scUMaxExpr:
2272       case scSMaxExpr:
2273       case scUDivExpr:
2274         return true;
2275       case scUnknown:
2276         return checkSCEVUnknown(cast<SCEVUnknown>(S));
2277       case scCouldNotCompute:
2278         llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
2279       }
2280       return false;
2281     }
2282 
2283     bool isDone() { return Found; }
2284   };
2285 
2286   FindDominatedSCEVUnknown FSU(L, DT, LI);
2287   SCEVTraversal<FindDominatedSCEVUnknown> ST(FSU);
2288   ST.visitAll(S);
2289   return !FSU.Found;
2290 }
2291 
2292 /// Get a canonical add expression, or something simpler if possible.
2293 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2294                                         SCEV::NoWrapFlags Flags,
2295                                         unsigned Depth) {
2296   assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2297          "only nuw or nsw allowed");
2298   assert(!Ops.empty() && "Cannot get empty add!");
2299   if (Ops.size() == 1) return Ops[0];
2300 #ifndef NDEBUG
2301   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2302   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2303     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2304            "SCEVAddExpr operand types don't match!");
2305 #endif
2306 
2307   // Sort by complexity, this groups all similar expression types together.
2308   GroupByComplexity(Ops, &LI, DT);
2309 
2310   Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags);
2311 
2312   // If there are any constants, fold them together.
2313   unsigned Idx = 0;
2314   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2315     ++Idx;
2316     assert(Idx < Ops.size());
2317     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2318       // We found two constants, fold them together!
2319       Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
2320       if (Ops.size() == 2) return Ops[0];
2321       Ops.erase(Ops.begin()+1);  // Erase the folded element
2322       LHSC = cast<SCEVConstant>(Ops[0]);
2323     }
2324 
2325     // If we are left with a constant zero being added, strip it off.
2326     if (LHSC->getValue()->isZero()) {
2327       Ops.erase(Ops.begin());
2328       --Idx;
2329     }
2330 
2331     if (Ops.size() == 1) return Ops[0];
2332   }
2333 
2334   // Limit recursion calls depth.
2335   if (Depth > MaxArithDepth)
2336     return getOrCreateAddExpr(Ops, Flags);
2337 
2338   // Okay, check to see if the same value occurs in the operand list more than
2339   // once.  If so, merge them together into an multiply expression.  Since we
2340   // sorted the list, these values are required to be adjacent.
2341   Type *Ty = Ops[0]->getType();
2342   bool FoundMatch = false;
2343   for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2344     if (Ops[i] == Ops[i+1]) {      //  X + Y + Y  -->  X + Y*2
2345       // Scan ahead to count how many equal operands there are.
2346       unsigned Count = 2;
2347       while (i+Count != e && Ops[i+Count] == Ops[i])
2348         ++Count;
2349       // Merge the values into a multiply.
2350       const SCEV *Scale = getConstant(Ty, Count);
2351       const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1);
2352       if (Ops.size() == Count)
2353         return Mul;
2354       Ops[i] = Mul;
2355       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2356       --i; e -= Count - 1;
2357       FoundMatch = true;
2358     }
2359   if (FoundMatch)
2360     return getAddExpr(Ops, Flags, Depth + 1);
2361 
2362   // Check for truncates. If all the operands are truncated from the same
2363   // type, see if factoring out the truncate would permit the result to be
2364   // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
2365   // if the contents of the resulting outer trunc fold to something simple.
2366   auto FindTruncSrcType = [&]() -> Type * {
2367     // We're ultimately looking to fold an addrec of truncs and muls of only
2368     // constants and truncs, so if we find any other types of SCEV
2369     // as operands of the addrec then we bail and return nullptr here.
2370     // Otherwise, we return the type of the operand of a trunc that we find.
2371     if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx]))
2372       return T->getOperand()->getType();
2373     if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2374       const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1);
2375       if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp))
2376         return T->getOperand()->getType();
2377     }
2378     return nullptr;
2379   };
2380   if (auto *SrcType = FindTruncSrcType()) {
2381     SmallVector<const SCEV *, 8> LargeOps;
2382     bool Ok = true;
2383     // Check all the operands to see if they can be represented in the
2384     // source type of the truncate.
2385     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2386       if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2387         if (T->getOperand()->getType() != SrcType) {
2388           Ok = false;
2389           break;
2390         }
2391         LargeOps.push_back(T->getOperand());
2392       } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2393         LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2394       } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
2395         SmallVector<const SCEV *, 8> LargeMulOps;
2396         for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2397           if (const SCEVTruncateExpr *T =
2398                 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2399             if (T->getOperand()->getType() != SrcType) {
2400               Ok = false;
2401               break;
2402             }
2403             LargeMulOps.push_back(T->getOperand());
2404           } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2405             LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2406           } else {
2407             Ok = false;
2408             break;
2409           }
2410         }
2411         if (Ok)
2412           LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1));
2413       } else {
2414         Ok = false;
2415         break;
2416       }
2417     }
2418     if (Ok) {
2419       // Evaluate the expression in the larger type.
2420       const SCEV *Fold = getAddExpr(LargeOps, Flags, Depth + 1);
2421       // If it folds to something simple, use it. Otherwise, don't.
2422       if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2423         return getTruncateExpr(Fold, Ty);
2424     }
2425   }
2426 
2427   // Skip past any other cast SCEVs.
2428   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2429     ++Idx;
2430 
2431   // If there are add operands they would be next.
2432   if (Idx < Ops.size()) {
2433     bool DeletedAdd = false;
2434     while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2435       if (Ops.size() > AddOpsInlineThreshold ||
2436           Add->getNumOperands() > AddOpsInlineThreshold)
2437         break;
2438       // If we have an add, expand the add operands onto the end of the operands
2439       // list.
2440       Ops.erase(Ops.begin()+Idx);
2441       Ops.append(Add->op_begin(), Add->op_end());
2442       DeletedAdd = true;
2443     }
2444 
2445     // If we deleted at least one add, we added operands to the end of the list,
2446     // and they are not necessarily sorted.  Recurse to resort and resimplify
2447     // any operands we just acquired.
2448     if (DeletedAdd)
2449       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2450   }
2451 
2452   // Skip over the add expression until we get to a multiply.
2453   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2454     ++Idx;
2455 
2456   // Check to see if there are any folding opportunities present with
2457   // operands multiplied by constant values.
2458   if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2459     uint64_t BitWidth = getTypeSizeInBits(Ty);
2460     DenseMap<const SCEV *, APInt> M;
2461     SmallVector<const SCEV *, 8> NewOps;
2462     APInt AccumulatedConstant(BitWidth, 0);
2463     if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2464                                      Ops.data(), Ops.size(),
2465                                      APInt(BitWidth, 1), *this)) {
2466       struct APIntCompare {
2467         bool operator()(const APInt &LHS, const APInt &RHS) const {
2468           return LHS.ult(RHS);
2469         }
2470       };
2471 
2472       // Some interesting folding opportunity is present, so its worthwhile to
2473       // re-generate the operands list. Group the operands by constant scale,
2474       // to avoid multiplying by the same constant scale multiple times.
2475       std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
2476       for (const SCEV *NewOp : NewOps)
2477         MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2478       // Re-generate the operands list.
2479       Ops.clear();
2480       if (AccumulatedConstant != 0)
2481         Ops.push_back(getConstant(AccumulatedConstant));
2482       for (auto &MulOp : MulOpLists)
2483         if (MulOp.first != 0)
2484           Ops.push_back(getMulExpr(
2485               getConstant(MulOp.first),
2486               getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1),
2487               SCEV::FlagAnyWrap, Depth + 1));
2488       if (Ops.empty())
2489         return getZero(Ty);
2490       if (Ops.size() == 1)
2491         return Ops[0];
2492       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2493     }
2494   }
2495 
2496   // If we are adding something to a multiply expression, make sure the
2497   // something is not already an operand of the multiply.  If so, merge it into
2498   // the multiply.
2499   for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2500     const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2501     for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2502       const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2503       if (isa<SCEVConstant>(MulOpSCEV))
2504         continue;
2505       for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
2506         if (MulOpSCEV == Ops[AddOp]) {
2507           // Fold W + X + (X * Y * Z)  -->  W + (X * ((Y*Z)+1))
2508           const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
2509           if (Mul->getNumOperands() != 2) {
2510             // If the multiply has more than two operands, we must get the
2511             // Y*Z term.
2512             SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2513                                                 Mul->op_begin()+MulOp);
2514             MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2515             InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2516           }
2517           SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul};
2518           const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2519           const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV,
2520                                             SCEV::FlagAnyWrap, Depth + 1);
2521           if (Ops.size() == 2) return OuterMul;
2522           if (AddOp < Idx) {
2523             Ops.erase(Ops.begin()+AddOp);
2524             Ops.erase(Ops.begin()+Idx-1);
2525           } else {
2526             Ops.erase(Ops.begin()+Idx);
2527             Ops.erase(Ops.begin()+AddOp-1);
2528           }
2529           Ops.push_back(OuterMul);
2530           return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2531         }
2532 
2533       // Check this multiply against other multiplies being added together.
2534       for (unsigned OtherMulIdx = Idx+1;
2535            OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2536            ++OtherMulIdx) {
2537         const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
2538         // If MulOp occurs in OtherMul, we can fold the two multiplies
2539         // together.
2540         for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2541              OMulOp != e; ++OMulOp)
2542           if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2543             // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
2544             const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
2545             if (Mul->getNumOperands() != 2) {
2546               SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2547                                                   Mul->op_begin()+MulOp);
2548               MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2549               InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2550             }
2551             const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
2552             if (OtherMul->getNumOperands() != 2) {
2553               SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
2554                                                   OtherMul->op_begin()+OMulOp);
2555               MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
2556               InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2557             }
2558             SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2};
2559             const SCEV *InnerMulSum =
2560                 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2561             const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum,
2562                                               SCEV::FlagAnyWrap, Depth + 1);
2563             if (Ops.size() == 2) return OuterMul;
2564             Ops.erase(Ops.begin()+Idx);
2565             Ops.erase(Ops.begin()+OtherMulIdx-1);
2566             Ops.push_back(OuterMul);
2567             return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2568           }
2569       }
2570     }
2571   }
2572 
2573   // If there are any add recurrences in the operands list, see if any other
2574   // added values are loop invariant.  If so, we can fold them into the
2575   // recurrence.
2576   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2577     ++Idx;
2578 
2579   // Scan over all recurrences, trying to fold loop invariants into them.
2580   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2581     // Scan all of the other operands to this add and add them to the vector if
2582     // they are loop invariant w.r.t. the recurrence.
2583     SmallVector<const SCEV *, 8> LIOps;
2584     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2585     const Loop *AddRecLoop = AddRec->getLoop();
2586     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2587       if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2588         LIOps.push_back(Ops[i]);
2589         Ops.erase(Ops.begin()+i);
2590         --i; --e;
2591       }
2592 
2593     // If we found some loop invariants, fold them into the recurrence.
2594     if (!LIOps.empty()) {
2595       //  NLI + LI + {Start,+,Step}  -->  NLI + {LI+Start,+,Step}
2596       LIOps.push_back(AddRec->getStart());
2597 
2598       SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2599                                              AddRec->op_end());
2600       // This follows from the fact that the no-wrap flags on the outer add
2601       // expression are applicable on the 0th iteration, when the add recurrence
2602       // will be equal to its start value.
2603       AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1);
2604 
2605       // Build the new addrec. Propagate the NUW and NSW flags if both the
2606       // outer add and the inner addrec are guaranteed to have no overflow.
2607       // Always propagate NW.
2608       Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2609       const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2610 
2611       // If all of the other operands were loop invariant, we are done.
2612       if (Ops.size() == 1) return NewRec;
2613 
2614       // Otherwise, add the folded AddRec by the non-invariant parts.
2615       for (unsigned i = 0;; ++i)
2616         if (Ops[i] == AddRec) {
2617           Ops[i] = NewRec;
2618           break;
2619         }
2620       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2621     }
2622 
2623     // Okay, if there weren't any loop invariants to be folded, check to see if
2624     // there are multiple AddRec's with the same loop induction variable being
2625     // added together.  If so, we can fold them.
2626     for (unsigned OtherIdx = Idx+1;
2627          OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2628          ++OtherIdx) {
2629       // We expect the AddRecExpr's to be sorted in reverse dominance order,
2630       // so that the 1st found AddRecExpr is dominated by all others.
2631       assert(DT.dominates(
2632            cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
2633            AddRec->getLoop()->getHeader()) &&
2634         "AddRecExprs are not sorted in reverse dominance order?");
2635       if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2636         // Other + {A,+,B}<L> + {C,+,D}<L>  -->  Other + {A+C,+,B+D}<L>
2637         SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2638                                                AddRec->op_end());
2639         for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2640              ++OtherIdx) {
2641           const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2642           if (OtherAddRec->getLoop() == AddRecLoop) {
2643             for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2644                  i != e; ++i) {
2645               if (i >= AddRecOps.size()) {
2646                 AddRecOps.append(OtherAddRec->op_begin()+i,
2647                                  OtherAddRec->op_end());
2648                 break;
2649               }
2650               SmallVector<const SCEV *, 2> TwoOps = {
2651                   AddRecOps[i], OtherAddRec->getOperand(i)};
2652               AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2653             }
2654             Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2655           }
2656         }
2657         // Step size has changed, so we cannot guarantee no self-wraparound.
2658         Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2659         return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2660       }
2661     }
2662 
2663     // Otherwise couldn't fold anything into this recurrence.  Move onto the
2664     // next one.
2665   }
2666 
2667   // Okay, it looks like we really DO need an add expr.  Check to see if we
2668   // already have one, otherwise create a new one.
2669   return getOrCreateAddExpr(Ops, Flags);
2670 }
2671 
2672 const SCEV *
2673 ScalarEvolution::getOrCreateAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2674                                     SCEV::NoWrapFlags Flags) {
2675   FoldingSetNodeID ID;
2676   ID.AddInteger(scAddExpr);
2677   for (const SCEV *Op : Ops)
2678     ID.AddPointer(Op);
2679   void *IP = nullptr;
2680   SCEVAddExpr *S =
2681       static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2682   if (!S) {
2683     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2684     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2685     S = new (SCEVAllocator)
2686         SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
2687     UniqueSCEVs.InsertNode(S, IP);
2688     addToLoopUseLists(S);
2689   }
2690   S->setNoWrapFlags(Flags);
2691   return S;
2692 }
2693 
2694 const SCEV *
2695 ScalarEvolution::getOrCreateMulExpr(SmallVectorImpl<const SCEV *> &Ops,
2696                                     SCEV::NoWrapFlags Flags) {
2697   FoldingSetNodeID ID;
2698   ID.AddInteger(scMulExpr);
2699   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2700     ID.AddPointer(Ops[i]);
2701   void *IP = nullptr;
2702   SCEVMulExpr *S =
2703     static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2704   if (!S) {
2705     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2706     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2707     S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2708                                         O, Ops.size());
2709     UniqueSCEVs.InsertNode(S, IP);
2710     addToLoopUseLists(S);
2711   }
2712   S->setNoWrapFlags(Flags);
2713   return S;
2714 }
2715 
2716 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2717   uint64_t k = i*j;
2718   if (j > 1 && k / j != i) Overflow = true;
2719   return k;
2720 }
2721 
2722 /// Compute the result of "n choose k", the binomial coefficient.  If an
2723 /// intermediate computation overflows, Overflow will be set and the return will
2724 /// be garbage. Overflow is not cleared on absence of overflow.
2725 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2726   // We use the multiplicative formula:
2727   //     n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2728   // At each iteration, we take the n-th term of the numeral and divide by the
2729   // (k-n)th term of the denominator.  This division will always produce an
2730   // integral result, and helps reduce the chance of overflow in the
2731   // intermediate computations. However, we can still overflow even when the
2732   // final result would fit.
2733 
2734   if (n == 0 || n == k) return 1;
2735   if (k > n) return 0;
2736 
2737   if (k > n/2)
2738     k = n-k;
2739 
2740   uint64_t r = 1;
2741   for (uint64_t i = 1; i <= k; ++i) {
2742     r = umul_ov(r, n-(i-1), Overflow);
2743     r /= i;
2744   }
2745   return r;
2746 }
2747 
2748 /// Determine if any of the operands in this SCEV are a constant or if
2749 /// any of the add or multiply expressions in this SCEV contain a constant.
2750 static bool containsConstantInAddMulChain(const SCEV *StartExpr) {
2751   struct FindConstantInAddMulChain {
2752     bool FoundConstant = false;
2753 
2754     bool follow(const SCEV *S) {
2755       FoundConstant |= isa<SCEVConstant>(S);
2756       return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
2757     }
2758 
2759     bool isDone() const {
2760       return FoundConstant;
2761     }
2762   };
2763 
2764   FindConstantInAddMulChain F;
2765   SCEVTraversal<FindConstantInAddMulChain> ST(F);
2766   ST.visitAll(StartExpr);
2767   return F.FoundConstant;
2768 }
2769 
2770 /// Get a canonical multiply expression, or something simpler if possible.
2771 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
2772                                         SCEV::NoWrapFlags Flags,
2773                                         unsigned Depth) {
2774   assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&
2775          "only nuw or nsw allowed");
2776   assert(!Ops.empty() && "Cannot get empty mul!");
2777   if (Ops.size() == 1) return Ops[0];
2778 #ifndef NDEBUG
2779   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2780   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2781     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2782            "SCEVMulExpr operand types don't match!");
2783 #endif
2784 
2785   // Sort by complexity, this groups all similar expression types together.
2786   GroupByComplexity(Ops, &LI, DT);
2787 
2788   Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags);
2789 
2790   // Limit recursion calls depth.
2791   if (Depth > MaxArithDepth)
2792     return getOrCreateMulExpr(Ops, Flags);
2793 
2794   // If there are any constants, fold them together.
2795   unsigned Idx = 0;
2796   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2797 
2798     // C1*(C2+V) -> C1*C2 + C1*V
2799     if (Ops.size() == 2)
2800         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
2801           // If any of Add's ops are Adds or Muls with a constant,
2802           // apply this transformation as well.
2803           if (Add->getNumOperands() == 2)
2804             // TODO: There are some cases where this transformation is not
2805             // profitable, for example:
2806             // Add = (C0 + X) * Y + Z.
2807             // Maybe the scope of this transformation should be narrowed down.
2808             if (containsConstantInAddMulChain(Add))
2809               return getAddExpr(getMulExpr(LHSC, Add->getOperand(0),
2810                                            SCEV::FlagAnyWrap, Depth + 1),
2811                                 getMulExpr(LHSC, Add->getOperand(1),
2812                                            SCEV::FlagAnyWrap, Depth + 1),
2813                                 SCEV::FlagAnyWrap, Depth + 1);
2814 
2815     ++Idx;
2816     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2817       // We found two constants, fold them together!
2818       ConstantInt *Fold =
2819           ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt());
2820       Ops[0] = getConstant(Fold);
2821       Ops.erase(Ops.begin()+1);  // Erase the folded element
2822       if (Ops.size() == 1) return Ops[0];
2823       LHSC = cast<SCEVConstant>(Ops[0]);
2824     }
2825 
2826     // If we are left with a constant one being multiplied, strip it off.
2827     if (cast<SCEVConstant>(Ops[0])->getValue()->isOne()) {
2828       Ops.erase(Ops.begin());
2829       --Idx;
2830     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
2831       // If we have a multiply of zero, it will always be zero.
2832       return Ops[0];
2833     } else if (Ops[0]->isAllOnesValue()) {
2834       // If we have a mul by -1 of an add, try distributing the -1 among the
2835       // add operands.
2836       if (Ops.size() == 2) {
2837         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
2838           SmallVector<const SCEV *, 4> NewOps;
2839           bool AnyFolded = false;
2840           for (const SCEV *AddOp : Add->operands()) {
2841             const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap,
2842                                          Depth + 1);
2843             if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
2844             NewOps.push_back(Mul);
2845           }
2846           if (AnyFolded)
2847             return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1);
2848         } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
2849           // Negation preserves a recurrence's no self-wrap property.
2850           SmallVector<const SCEV *, 4> Operands;
2851           for (const SCEV *AddRecOp : AddRec->operands())
2852             Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap,
2853                                           Depth + 1));
2854 
2855           return getAddRecExpr(Operands, AddRec->getLoop(),
2856                                AddRec->getNoWrapFlags(SCEV::FlagNW));
2857         }
2858       }
2859     }
2860 
2861     if (Ops.size() == 1)
2862       return Ops[0];
2863   }
2864 
2865   // Skip over the add expression until we get to a multiply.
2866   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2867     ++Idx;
2868 
2869   // If there are mul operands inline them all into this expression.
2870   if (Idx < Ops.size()) {
2871     bool DeletedMul = false;
2872     while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2873       if (Ops.size() > MulOpsInlineThreshold)
2874         break;
2875       // If we have an mul, expand the mul operands onto the end of the
2876       // operands list.
2877       Ops.erase(Ops.begin()+Idx);
2878       Ops.append(Mul->op_begin(), Mul->op_end());
2879       DeletedMul = true;
2880     }
2881 
2882     // If we deleted at least one mul, we added operands to the end of the
2883     // list, and they are not necessarily sorted.  Recurse to resort and
2884     // resimplify any operands we just acquired.
2885     if (DeletedMul)
2886       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2887   }
2888 
2889   // If there are any add recurrences in the operands list, see if any other
2890   // added values are loop invariant.  If so, we can fold them into the
2891   // recurrence.
2892   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2893     ++Idx;
2894 
2895   // Scan over all recurrences, trying to fold loop invariants into them.
2896   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2897     // Scan all of the other operands to this mul and add them to the vector
2898     // if they are loop invariant w.r.t. the recurrence.
2899     SmallVector<const SCEV *, 8> LIOps;
2900     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2901     const Loop *AddRecLoop = AddRec->getLoop();
2902     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2903       if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2904         LIOps.push_back(Ops[i]);
2905         Ops.erase(Ops.begin()+i);
2906         --i; --e;
2907       }
2908 
2909     // If we found some loop invariants, fold them into the recurrence.
2910     if (!LIOps.empty()) {
2911       //  NLI * LI * {Start,+,Step}  -->  NLI * {LI*Start,+,LI*Step}
2912       SmallVector<const SCEV *, 4> NewOps;
2913       NewOps.reserve(AddRec->getNumOperands());
2914       const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1);
2915       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
2916         NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
2917                                     SCEV::FlagAnyWrap, Depth + 1));
2918 
2919       // Build the new addrec. Propagate the NUW and NSW flags if both the
2920       // outer mul and the inner addrec are guaranteed to have no overflow.
2921       //
2922       // No self-wrap cannot be guaranteed after changing the step size, but
2923       // will be inferred if either NUW or NSW is true.
2924       Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW));
2925       const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
2926 
2927       // If all of the other operands were loop invariant, we are done.
2928       if (Ops.size() == 1) return NewRec;
2929 
2930       // Otherwise, multiply the folded AddRec by the non-invariant parts.
2931       for (unsigned i = 0;; ++i)
2932         if (Ops[i] == AddRec) {
2933           Ops[i] = NewRec;
2934           break;
2935         }
2936       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2937     }
2938 
2939     // Okay, if there weren't any loop invariants to be folded, check to see
2940     // if there are multiple AddRec's with the same loop induction variable
2941     // being multiplied together.  If so, we can fold them.
2942 
2943     // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
2944     // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
2945     //       choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
2946     //   ]]],+,...up to x=2n}.
2947     // Note that the arguments to choose() are always integers with values
2948     // known at compile time, never SCEV objects.
2949     //
2950     // The implementation avoids pointless extra computations when the two
2951     // addrec's are of different length (mathematically, it's equivalent to
2952     // an infinite stream of zeros on the right).
2953     bool OpsModified = false;
2954     for (unsigned OtherIdx = Idx+1;
2955          OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2956          ++OtherIdx) {
2957       const SCEVAddRecExpr *OtherAddRec =
2958         dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2959       if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
2960         continue;
2961 
2962       // Limit max number of arguments to avoid creation of unreasonably big
2963       // SCEVAddRecs with very complex operands.
2964       if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
2965           MaxAddRecSize)
2966         continue;
2967 
2968       bool Overflow = false;
2969       Type *Ty = AddRec->getType();
2970       bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
2971       SmallVector<const SCEV*, 7> AddRecOps;
2972       for (int x = 0, xe = AddRec->getNumOperands() +
2973              OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
2974         const SCEV *Term = getZero(Ty);
2975         for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
2976           uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
2977           for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
2978                  ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
2979                z < ze && !Overflow; ++z) {
2980             uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
2981             uint64_t Coeff;
2982             if (LargerThan64Bits)
2983               Coeff = umul_ov(Coeff1, Coeff2, Overflow);
2984             else
2985               Coeff = Coeff1*Coeff2;
2986             const SCEV *CoeffTerm = getConstant(Ty, Coeff);
2987             const SCEV *Term1 = AddRec->getOperand(y-z);
2988             const SCEV *Term2 = OtherAddRec->getOperand(z);
2989             Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1, Term2,
2990                                                SCEV::FlagAnyWrap, Depth + 1),
2991                               SCEV::FlagAnyWrap, Depth + 1);
2992           }
2993         }
2994         AddRecOps.push_back(Term);
2995       }
2996       if (!Overflow) {
2997         const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
2998                                               SCEV::FlagAnyWrap);
2999         if (Ops.size() == 2) return NewAddRec;
3000         Ops[Idx] = NewAddRec;
3001         Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
3002         OpsModified = true;
3003         AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
3004         if (!AddRec)
3005           break;
3006       }
3007     }
3008     if (OpsModified)
3009       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3010 
3011     // Otherwise couldn't fold anything into this recurrence.  Move onto the
3012     // next one.
3013   }
3014 
3015   // Okay, it looks like we really DO need an mul expr.  Check to see if we
3016   // already have one, otherwise create a new one.
3017   return getOrCreateMulExpr(Ops, Flags);
3018 }
3019 
3020 /// Represents an unsigned remainder expression based on unsigned division.
3021 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS,
3022                                          const SCEV *RHS) {
3023   assert(getEffectiveSCEVType(LHS->getType()) ==
3024          getEffectiveSCEVType(RHS->getType()) &&
3025          "SCEVURemExpr operand types don't match!");
3026 
3027   // Short-circuit easy cases
3028   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3029     // If constant is one, the result is trivial
3030     if (RHSC->getValue()->isOne())
3031       return getZero(LHS->getType()); // X urem 1 --> 0
3032 
3033     // If constant is a power of two, fold into a zext(trunc(LHS)).
3034     if (RHSC->getAPInt().isPowerOf2()) {
3035       Type *FullTy = LHS->getType();
3036       Type *TruncTy =
3037           IntegerType::get(getContext(), RHSC->getAPInt().logBase2());
3038       return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy);
3039     }
3040   }
3041 
3042   // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
3043   const SCEV *UDiv = getUDivExpr(LHS, RHS);
3044   const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW);
3045   return getMinusSCEV(LHS, Mult, SCEV::FlagNUW);
3046 }
3047 
3048 /// Get a canonical unsigned division expression, or something simpler if
3049 /// possible.
3050 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
3051                                          const SCEV *RHS) {
3052   assert(getEffectiveSCEVType(LHS->getType()) ==
3053          getEffectiveSCEVType(RHS->getType()) &&
3054          "SCEVUDivExpr operand types don't match!");
3055 
3056   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3057     if (RHSC->getValue()->isOne())
3058       return LHS;                               // X udiv 1 --> x
3059     // If the denominator is zero, the result of the udiv is undefined. Don't
3060     // try to analyze it, because the resolution chosen here may differ from
3061     // the resolution chosen in other parts of the compiler.
3062     if (!RHSC->getValue()->isZero()) {
3063       // Determine if the division can be folded into the operands of
3064       // its operands.
3065       // TODO: Generalize this to non-constants by using known-bits information.
3066       Type *Ty = LHS->getType();
3067       unsigned LZ = RHSC->getAPInt().countLeadingZeros();
3068       unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
3069       // For non-power-of-two values, effectively round the value up to the
3070       // nearest power of two.
3071       if (!RHSC->getAPInt().isPowerOf2())
3072         ++MaxShiftAmt;
3073       IntegerType *ExtTy =
3074         IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
3075       if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
3076         if (const SCEVConstant *Step =
3077             dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
3078           // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
3079           const APInt &StepInt = Step->getAPInt();
3080           const APInt &DivInt = RHSC->getAPInt();
3081           if (!StepInt.urem(DivInt) &&
3082               getZeroExtendExpr(AR, ExtTy) ==
3083               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3084                             getZeroExtendExpr(Step, ExtTy),
3085                             AR->getLoop(), SCEV::FlagAnyWrap)) {
3086             SmallVector<const SCEV *, 4> Operands;
3087             for (const SCEV *Op : AR->operands())
3088               Operands.push_back(getUDivExpr(Op, RHS));
3089             return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
3090           }
3091           /// Get a canonical UDivExpr for a recurrence.
3092           /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
3093           // We can currently only fold X%N if X is constant.
3094           const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
3095           if (StartC && !DivInt.urem(StepInt) &&
3096               getZeroExtendExpr(AR, ExtTy) ==
3097               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3098                             getZeroExtendExpr(Step, ExtTy),
3099                             AR->getLoop(), SCEV::FlagAnyWrap)) {
3100             const APInt &StartInt = StartC->getAPInt();
3101             const APInt &StartRem = StartInt.urem(StepInt);
3102             if (StartRem != 0)
3103               LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step,
3104                                   AR->getLoop(), SCEV::FlagNW);
3105           }
3106         }
3107       // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
3108       if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
3109         SmallVector<const SCEV *, 4> Operands;
3110         for (const SCEV *Op : M->operands())
3111           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3112         if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
3113           // Find an operand that's safely divisible.
3114           for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3115             const SCEV *Op = M->getOperand(i);
3116             const SCEV *Div = getUDivExpr(Op, RHSC);
3117             if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
3118               Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
3119                                                       M->op_end());
3120               Operands[i] = Div;
3121               return getMulExpr(Operands);
3122             }
3123           }
3124       }
3125       // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
3126       if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
3127         SmallVector<const SCEV *, 4> Operands;
3128         for (const SCEV *Op : A->operands())
3129           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3130         if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
3131           Operands.clear();
3132           for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
3133             const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
3134             if (isa<SCEVUDivExpr>(Op) ||
3135                 getMulExpr(Op, RHS) != A->getOperand(i))
3136               break;
3137             Operands.push_back(Op);
3138           }
3139           if (Operands.size() == A->getNumOperands())
3140             return getAddExpr(Operands);
3141         }
3142       }
3143 
3144       // Fold if both operands are constant.
3145       if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
3146         Constant *LHSCV = LHSC->getValue();
3147         Constant *RHSCV = RHSC->getValue();
3148         return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
3149                                                                    RHSCV)));
3150       }
3151     }
3152   }
3153 
3154   FoldingSetNodeID ID;
3155   ID.AddInteger(scUDivExpr);
3156   ID.AddPointer(LHS);
3157   ID.AddPointer(RHS);
3158   void *IP = nullptr;
3159   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3160   SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
3161                                              LHS, RHS);
3162   UniqueSCEVs.InsertNode(S, IP);
3163   addToLoopUseLists(S);
3164   return S;
3165 }
3166 
3167 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
3168   APInt A = C1->getAPInt().abs();
3169   APInt B = C2->getAPInt().abs();
3170   uint32_t ABW = A.getBitWidth();
3171   uint32_t BBW = B.getBitWidth();
3172 
3173   if (ABW > BBW)
3174     B = B.zext(ABW);
3175   else if (ABW < BBW)
3176     A = A.zext(BBW);
3177 
3178   return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B));
3179 }
3180 
3181 /// Get a canonical unsigned division expression, or something simpler if
3182 /// possible. There is no representation for an exact udiv in SCEV IR, but we
3183 /// can attempt to remove factors from the LHS and RHS.  We can't do this when
3184 /// it's not exact because the udiv may be clearing bits.
3185 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
3186                                               const SCEV *RHS) {
3187   // TODO: we could try to find factors in all sorts of things, but for now we
3188   // just deal with u/exact (multiply, constant). See SCEVDivision towards the
3189   // end of this file for inspiration.
3190 
3191   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
3192   if (!Mul || !Mul->hasNoUnsignedWrap())
3193     return getUDivExpr(LHS, RHS);
3194 
3195   if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
3196     // If the mulexpr multiplies by a constant, then that constant must be the
3197     // first element of the mulexpr.
3198     if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
3199       if (LHSCst == RHSCst) {
3200         SmallVector<const SCEV *, 2> Operands;
3201         Operands.append(Mul->op_begin() + 1, Mul->op_end());
3202         return getMulExpr(Operands);
3203       }
3204 
3205       // We can't just assume that LHSCst divides RHSCst cleanly, it could be
3206       // that there's a factor provided by one of the other terms. We need to
3207       // check.
3208       APInt Factor = gcd(LHSCst, RHSCst);
3209       if (!Factor.isIntN(1)) {
3210         LHSCst =
3211             cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
3212         RHSCst =
3213             cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
3214         SmallVector<const SCEV *, 2> Operands;
3215         Operands.push_back(LHSCst);
3216         Operands.append(Mul->op_begin() + 1, Mul->op_end());
3217         LHS = getMulExpr(Operands);
3218         RHS = RHSCst;
3219         Mul = dyn_cast<SCEVMulExpr>(LHS);
3220         if (!Mul)
3221           return getUDivExactExpr(LHS, RHS);
3222       }
3223     }
3224   }
3225 
3226   for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3227     if (Mul->getOperand(i) == RHS) {
3228       SmallVector<const SCEV *, 2> Operands;
3229       Operands.append(Mul->op_begin(), Mul->op_begin() + i);
3230       Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
3231       return getMulExpr(Operands);
3232     }
3233   }
3234 
3235   return getUDivExpr(LHS, RHS);
3236 }
3237 
3238 /// Get an add recurrence expression for the specified loop.  Simplify the
3239 /// expression as much as possible.
3240 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
3241                                            const Loop *L,
3242                                            SCEV::NoWrapFlags Flags) {
3243   SmallVector<const SCEV *, 4> Operands;
3244   Operands.push_back(Start);
3245   if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3246     if (StepChrec->getLoop() == L) {
3247       Operands.append(StepChrec->op_begin(), StepChrec->op_end());
3248       return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
3249     }
3250 
3251   Operands.push_back(Step);
3252   return getAddRecExpr(Operands, L, Flags);
3253 }
3254 
3255 /// Get an add recurrence expression for the specified loop.  Simplify the
3256 /// expression as much as possible.
3257 const SCEV *
3258 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
3259                                const Loop *L, SCEV::NoWrapFlags Flags) {
3260   if (Operands.size() == 1) return Operands[0];
3261 #ifndef NDEBUG
3262   Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
3263   for (unsigned i = 1, e = Operands.size(); i != e; ++i)
3264     assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
3265            "SCEVAddRecExpr operand types don't match!");
3266   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3267     assert(isLoopInvariant(Operands[i], L) &&
3268            "SCEVAddRecExpr operand is not loop-invariant!");
3269 #endif
3270 
3271   if (Operands.back()->isZero()) {
3272     Operands.pop_back();
3273     return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0}  -->  X
3274   }
3275 
3276   // It's tempting to want to call getMaxBackedgeTakenCount count here and
3277   // use that information to infer NUW and NSW flags. However, computing a
3278   // BE count requires calling getAddRecExpr, so we may not yet have a
3279   // meaningful BE count at this point (and if we don't, we'd be stuck
3280   // with a SCEVCouldNotCompute as the cached BE count).
3281 
3282   Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
3283 
3284   // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3285   if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3286     const Loop *NestedLoop = NestedAR->getLoop();
3287     if (L->contains(NestedLoop)
3288             ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3289             : (!NestedLoop->contains(L) &&
3290                DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3291       SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
3292                                                   NestedAR->op_end());
3293       Operands[0] = NestedAR->getStart();
3294       // AddRecs require their operands be loop-invariant with respect to their
3295       // loops. Don't perform this transformation if it would break this
3296       // requirement.
3297       bool AllInvariant = all_of(
3298           Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3299 
3300       if (AllInvariant) {
3301         // Create a recurrence for the outer loop with the same step size.
3302         //
3303         // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3304         // inner recurrence has the same property.
3305         SCEV::NoWrapFlags OuterFlags =
3306           maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3307 
3308         NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3309         AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3310           return isLoopInvariant(Op, NestedLoop);
3311         });
3312 
3313         if (AllInvariant) {
3314           // Ok, both add recurrences are valid after the transformation.
3315           //
3316           // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3317           // the outer recurrence has the same property.
3318           SCEV::NoWrapFlags InnerFlags =
3319             maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
3320           return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3321         }
3322       }
3323       // Reset Operands to its original state.
3324       Operands[0] = NestedAR;
3325     }
3326   }
3327 
3328   // Okay, it looks like we really DO need an addrec expr.  Check to see if we
3329   // already have one, otherwise create a new one.
3330   FoldingSetNodeID ID;
3331   ID.AddInteger(scAddRecExpr);
3332   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3333     ID.AddPointer(Operands[i]);
3334   ID.AddPointer(L);
3335   void *IP = nullptr;
3336   SCEVAddRecExpr *S =
3337     static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3338   if (!S) {
3339     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
3340     std::uninitialized_copy(Operands.begin(), Operands.end(), O);
3341     S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
3342                                            O, Operands.size(), L);
3343     UniqueSCEVs.InsertNode(S, IP);
3344     addToLoopUseLists(S);
3345   }
3346   S->setNoWrapFlags(Flags);
3347   return S;
3348 }
3349 
3350 const SCEV *
3351 ScalarEvolution::getGEPExpr(GEPOperator *GEP,
3352                             const SmallVectorImpl<const SCEV *> &IndexExprs) {
3353   const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3354   // getSCEV(Base)->getType() has the same address space as Base->getType()
3355   // because SCEV::getType() preserves the address space.
3356   Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType());
3357   // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP
3358   // instruction to its SCEV, because the Instruction may be guarded by control
3359   // flow and the no-overflow bits may not be valid for the expression in any
3360   // context. This can be fixed similarly to how these flags are handled for
3361   // adds.
3362   SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW
3363                                              : SCEV::FlagAnyWrap;
3364 
3365   const SCEV *TotalOffset = getZero(IntPtrTy);
3366   // The array size is unimportant. The first thing we do on CurTy is getting
3367   // its element type.
3368   Type *CurTy = ArrayType::get(GEP->getSourceElementType(), 0);
3369   for (const SCEV *IndexExpr : IndexExprs) {
3370     // Compute the (potentially symbolic) offset in bytes for this index.
3371     if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3372       // For a struct, add the member offset.
3373       ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3374       unsigned FieldNo = Index->getZExtValue();
3375       const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo);
3376 
3377       // Add the field offset to the running total offset.
3378       TotalOffset = getAddExpr(TotalOffset, FieldOffset);
3379 
3380       // Update CurTy to the type of the field at Index.
3381       CurTy = STy->getTypeAtIndex(Index);
3382     } else {
3383       // Update CurTy to its element type.
3384       CurTy = cast<SequentialType>(CurTy)->getElementType();
3385       // For an array, add the element offset, explicitly scaled.
3386       const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy);
3387       // Getelementptr indices are signed.
3388       IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy);
3389 
3390       // Multiply the index by the element size to compute the element offset.
3391       const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap);
3392 
3393       // Add the element offset to the running total offset.
3394       TotalOffset = getAddExpr(TotalOffset, LocalOffset);
3395     }
3396   }
3397 
3398   // Add the total offset from all the GEP indices to the base.
3399   return getAddExpr(BaseExpr, TotalOffset, Wrap);
3400 }
3401 
3402 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
3403                                          const SCEV *RHS) {
3404   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3405   return getSMaxExpr(Ops);
3406 }
3407 
3408 const SCEV *
3409 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3410   assert(!Ops.empty() && "Cannot get empty smax!");
3411   if (Ops.size() == 1) return Ops[0];
3412 #ifndef NDEBUG
3413   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3414   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3415     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3416            "SCEVSMaxExpr operand types don't match!");
3417 #endif
3418 
3419   // Sort by complexity, this groups all similar expression types together.
3420   GroupByComplexity(Ops, &LI, DT);
3421 
3422   // If there are any constants, fold them together.
3423   unsigned Idx = 0;
3424   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3425     ++Idx;
3426     assert(Idx < Ops.size());
3427     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3428       // We found two constants, fold them together!
3429       ConstantInt *Fold = ConstantInt::get(
3430           getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt()));
3431       Ops[0] = getConstant(Fold);
3432       Ops.erase(Ops.begin()+1);  // Erase the folded element
3433       if (Ops.size() == 1) return Ops[0];
3434       LHSC = cast<SCEVConstant>(Ops[0]);
3435     }
3436 
3437     // If we are left with a constant minimum-int, strip it off.
3438     if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
3439       Ops.erase(Ops.begin());
3440       --Idx;
3441     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
3442       // If we have an smax with a constant maximum-int, it will always be
3443       // maximum-int.
3444       return Ops[0];
3445     }
3446 
3447     if (Ops.size() == 1) return Ops[0];
3448   }
3449 
3450   // Find the first SMax
3451   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
3452     ++Idx;
3453 
3454   // Check to see if one of the operands is an SMax. If so, expand its operands
3455   // onto our operand list, and recurse to simplify.
3456   if (Idx < Ops.size()) {
3457     bool DeletedSMax = false;
3458     while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
3459       Ops.erase(Ops.begin()+Idx);
3460       Ops.append(SMax->op_begin(), SMax->op_end());
3461       DeletedSMax = true;
3462     }
3463 
3464     if (DeletedSMax)
3465       return getSMaxExpr(Ops);
3466   }
3467 
3468   // Okay, check to see if the same value occurs in the operand list twice.  If
3469   // so, delete one.  Since we sorted the list, these values are required to
3470   // be adjacent.
3471   for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
3472     //  X smax Y smax Y  -->  X smax Y
3473     //  X smax Y         -->  X, if X is always greater than Y
3474     if (Ops[i] == Ops[i+1] ||
3475         isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
3476       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3477       --i; --e;
3478     } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
3479       Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3480       --i; --e;
3481     }
3482 
3483   if (Ops.size() == 1) return Ops[0];
3484 
3485   assert(!Ops.empty() && "Reduced smax down to nothing!");
3486 
3487   // Okay, it looks like we really DO need an smax expr.  Check to see if we
3488   // already have one, otherwise create a new one.
3489   FoldingSetNodeID ID;
3490   ID.AddInteger(scSMaxExpr);
3491   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3492     ID.AddPointer(Ops[i]);
3493   void *IP = nullptr;
3494   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3495   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3496   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3497   SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
3498                                              O, Ops.size());
3499   UniqueSCEVs.InsertNode(S, IP);
3500   addToLoopUseLists(S);
3501   return S;
3502 }
3503 
3504 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
3505                                          const SCEV *RHS) {
3506   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3507   return getUMaxExpr(Ops);
3508 }
3509 
3510 const SCEV *
3511 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3512   assert(!Ops.empty() && "Cannot get empty umax!");
3513   if (Ops.size() == 1) return Ops[0];
3514 #ifndef NDEBUG
3515   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3516   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3517     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3518            "SCEVUMaxExpr operand types don't match!");
3519 #endif
3520 
3521   // Sort by complexity, this groups all similar expression types together.
3522   GroupByComplexity(Ops, &LI, DT);
3523 
3524   // If there are any constants, fold them together.
3525   unsigned Idx = 0;
3526   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3527     ++Idx;
3528     assert(Idx < Ops.size());
3529     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3530       // We found two constants, fold them together!
3531       ConstantInt *Fold = ConstantInt::get(
3532           getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt()));
3533       Ops[0] = getConstant(Fold);
3534       Ops.erase(Ops.begin()+1);  // Erase the folded element
3535       if (Ops.size() == 1) return Ops[0];
3536       LHSC = cast<SCEVConstant>(Ops[0]);
3537     }
3538 
3539     // If we are left with a constant minimum-int, strip it off.
3540     if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
3541       Ops.erase(Ops.begin());
3542       --Idx;
3543     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
3544       // If we have an umax with a constant maximum-int, it will always be
3545       // maximum-int.
3546       return Ops[0];
3547     }
3548 
3549     if (Ops.size() == 1) return Ops[0];
3550   }
3551 
3552   // Find the first UMax
3553   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
3554     ++Idx;
3555 
3556   // Check to see if one of the operands is a UMax. If so, expand its operands
3557   // onto our operand list, and recurse to simplify.
3558   if (Idx < Ops.size()) {
3559     bool DeletedUMax = false;
3560     while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
3561       Ops.erase(Ops.begin()+Idx);
3562       Ops.append(UMax->op_begin(), UMax->op_end());
3563       DeletedUMax = true;
3564     }
3565 
3566     if (DeletedUMax)
3567       return getUMaxExpr(Ops);
3568   }
3569 
3570   // Okay, check to see if the same value occurs in the operand list twice.  If
3571   // so, delete one.  Since we sorted the list, these values are required to
3572   // be adjacent.
3573   for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
3574     //  X umax Y umax Y  -->  X umax Y
3575     //  X umax Y         -->  X, if X is always greater than Y
3576     if (Ops[i] == Ops[i+1] ||
3577         isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
3578       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3579       --i; --e;
3580     } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
3581       Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3582       --i; --e;
3583     }
3584 
3585   if (Ops.size() == 1) return Ops[0];
3586 
3587   assert(!Ops.empty() && "Reduced umax down to nothing!");
3588 
3589   // Okay, it looks like we really DO need a umax expr.  Check to see if we
3590   // already have one, otherwise create a new one.
3591   FoldingSetNodeID ID;
3592   ID.AddInteger(scUMaxExpr);
3593   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3594     ID.AddPointer(Ops[i]);
3595   void *IP = nullptr;
3596   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3597   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3598   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3599   SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
3600                                              O, Ops.size());
3601   UniqueSCEVs.InsertNode(S, IP);
3602   addToLoopUseLists(S);
3603   return S;
3604 }
3605 
3606 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
3607                                          const SCEV *RHS) {
3608   // ~smax(~x, ~y) == smin(x, y).
3609   return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3610 }
3611 
3612 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
3613                                          const SCEV *RHS) {
3614   // ~umax(~x, ~y) == umin(x, y)
3615   return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3616 }
3617 
3618 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
3619   // We can bypass creating a target-independent
3620   // constant expression and then folding it back into a ConstantInt.
3621   // This is just a compile-time optimization.
3622   return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
3623 }
3624 
3625 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
3626                                              StructType *STy,
3627                                              unsigned FieldNo) {
3628   // We can bypass creating a target-independent
3629   // constant expression and then folding it back into a ConstantInt.
3630   // This is just a compile-time optimization.
3631   return getConstant(
3632       IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
3633 }
3634 
3635 const SCEV *ScalarEvolution::getUnknown(Value *V) {
3636   // Don't attempt to do anything other than create a SCEVUnknown object
3637   // here.  createSCEV only calls getUnknown after checking for all other
3638   // interesting possibilities, and any other code that calls getUnknown
3639   // is doing so in order to hide a value from SCEV canonicalization.
3640 
3641   FoldingSetNodeID ID;
3642   ID.AddInteger(scUnknown);
3643   ID.AddPointer(V);
3644   void *IP = nullptr;
3645   if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3646     assert(cast<SCEVUnknown>(S)->getValue() == V &&
3647            "Stale SCEVUnknown in uniquing map!");
3648     return S;
3649   }
3650   SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3651                                             FirstUnknown);
3652   FirstUnknown = cast<SCEVUnknown>(S);
3653   UniqueSCEVs.InsertNode(S, IP);
3654   return S;
3655 }
3656 
3657 //===----------------------------------------------------------------------===//
3658 //            Basic SCEV Analysis and PHI Idiom Recognition Code
3659 //
3660 
3661 /// Test if values of the given type are analyzable within the SCEV
3662 /// framework. This primarily includes integer types, and it can optionally
3663 /// include pointer types if the ScalarEvolution class has access to
3664 /// target-specific information.
3665 bool ScalarEvolution::isSCEVable(Type *Ty) const {
3666   // Integers and pointers are always SCEVable.
3667   return Ty->isIntegerTy() || Ty->isPointerTy();
3668 }
3669 
3670 /// Return the size in bits of the specified type, for which isSCEVable must
3671 /// return true.
3672 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
3673   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3674   if (Ty->isPointerTy())
3675     return getDataLayout().getIndexTypeSizeInBits(Ty);
3676   return getDataLayout().getTypeSizeInBits(Ty);
3677 }
3678 
3679 /// Return a type with the same bitwidth as the given type and which represents
3680 /// how SCEV will treat the given type, for which isSCEVable must return
3681 /// true. For pointer types, this is the pointer-sized integer type.
3682 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
3683   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3684 
3685   if (Ty->isIntegerTy())
3686     return Ty;
3687 
3688   // The only other support type is pointer.
3689   assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
3690   return getDataLayout().getIntPtrType(Ty);
3691 }
3692 
3693 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const {
3694   return  getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
3695 }
3696 
3697 const SCEV *ScalarEvolution::getCouldNotCompute() {
3698   return CouldNotCompute.get();
3699 }
3700 
3701 bool ScalarEvolution::checkValidity(const SCEV *S) const {
3702   bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
3703     auto *SU = dyn_cast<SCEVUnknown>(S);
3704     return SU && SU->getValue() == nullptr;
3705   });
3706 
3707   return !ContainsNulls;
3708 }
3709 
3710 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
3711   HasRecMapType::iterator I = HasRecMap.find(S);
3712   if (I != HasRecMap.end())
3713     return I->second;
3714 
3715   bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>);
3716   HasRecMap.insert({S, FoundAddRec});
3717   return FoundAddRec;
3718 }
3719 
3720 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}.
3721 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an
3722 /// offset I, then return {S', I}, else return {\p S, nullptr}.
3723 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) {
3724   const auto *Add = dyn_cast<SCEVAddExpr>(S);
3725   if (!Add)
3726     return {S, nullptr};
3727 
3728   if (Add->getNumOperands() != 2)
3729     return {S, nullptr};
3730 
3731   auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0));
3732   if (!ConstOp)
3733     return {S, nullptr};
3734 
3735   return {Add->getOperand(1), ConstOp->getValue()};
3736 }
3737 
3738 /// Return the ValueOffsetPair set for \p S. \p S can be represented
3739 /// by the value and offset from any ValueOffsetPair in the set.
3740 SetVector<ScalarEvolution::ValueOffsetPair> *
3741 ScalarEvolution::getSCEVValues(const SCEV *S) {
3742   ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
3743   if (SI == ExprValueMap.end())
3744     return nullptr;
3745 #ifndef NDEBUG
3746   if (VerifySCEVMap) {
3747     // Check there is no dangling Value in the set returned.
3748     for (const auto &VE : SI->second)
3749       assert(ValueExprMap.count(VE.first));
3750   }
3751 #endif
3752   return &SI->second;
3753 }
3754 
3755 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
3756 /// cannot be used separately. eraseValueFromMap should be used to remove
3757 /// V from ValueExprMap and ExprValueMap at the same time.
3758 void ScalarEvolution::eraseValueFromMap(Value *V) {
3759   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3760   if (I != ValueExprMap.end()) {
3761     const SCEV *S = I->second;
3762     // Remove {V, 0} from the set of ExprValueMap[S]
3763     if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S))
3764       SV->remove({V, nullptr});
3765 
3766     // Remove {V, Offset} from the set of ExprValueMap[Stripped]
3767     const SCEV *Stripped;
3768     ConstantInt *Offset;
3769     std::tie(Stripped, Offset) = splitAddExpr(S);
3770     if (Offset != nullptr) {
3771       if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped))
3772         SV->remove({V, Offset});
3773     }
3774     ValueExprMap.erase(V);
3775   }
3776 }
3777 
3778 /// Check whether value has nuw/nsw/exact set but SCEV does not.
3779 /// TODO: In reality it is better to check the poison recursevely
3780 /// but this is better than nothing.
3781 static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) {
3782   if (auto *I = dyn_cast<Instruction>(V)) {
3783     if (isa<OverflowingBinaryOperator>(I)) {
3784       if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) {
3785         if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap())
3786           return true;
3787         if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap())
3788           return true;
3789       }
3790     } else if (isa<PossiblyExactOperator>(I) && I->isExact())
3791       return true;
3792   }
3793   return false;
3794 }
3795 
3796 /// Return an existing SCEV if it exists, otherwise analyze the expression and
3797 /// create a new one.
3798 const SCEV *ScalarEvolution::getSCEV(Value *V) {
3799   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3800 
3801   const SCEV *S = getExistingSCEV(V);
3802   if (S == nullptr) {
3803     S = createSCEV(V);
3804     // During PHI resolution, it is possible to create two SCEVs for the same
3805     // V, so it is needed to double check whether V->S is inserted into
3806     // ValueExprMap before insert S->{V, 0} into ExprValueMap.
3807     std::pair<ValueExprMapType::iterator, bool> Pair =
3808         ValueExprMap.insert({SCEVCallbackVH(V, this), S});
3809     if (Pair.second && !SCEVLostPoisonFlags(S, V)) {
3810       ExprValueMap[S].insert({V, nullptr});
3811 
3812       // If S == Stripped + Offset, add Stripped -> {V, Offset} into
3813       // ExprValueMap.
3814       const SCEV *Stripped = S;
3815       ConstantInt *Offset = nullptr;
3816       std::tie(Stripped, Offset) = splitAddExpr(S);
3817       // If stripped is SCEVUnknown, don't bother to save
3818       // Stripped -> {V, offset}. It doesn't simplify and sometimes even
3819       // increase the complexity of the expansion code.
3820       // If V is GetElementPtrInst, don't save Stripped -> {V, offset}
3821       // because it may generate add/sub instead of GEP in SCEV expansion.
3822       if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) &&
3823           !isa<GetElementPtrInst>(V))
3824         ExprValueMap[Stripped].insert({V, Offset});
3825     }
3826   }
3827   return S;
3828 }
3829 
3830 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
3831   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3832 
3833   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3834   if (I != ValueExprMap.end()) {
3835     const SCEV *S = I->second;
3836     if (checkValidity(S))
3837       return S;
3838     eraseValueFromMap(V);
3839     forgetMemoizedResults(S);
3840   }
3841   return nullptr;
3842 }
3843 
3844 /// Return a SCEV corresponding to -V = -1*V
3845 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
3846                                              SCEV::NoWrapFlags Flags) {
3847   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3848     return getConstant(
3849                cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
3850 
3851   Type *Ty = V->getType();
3852   Ty = getEffectiveSCEVType(Ty);
3853   return getMulExpr(
3854       V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags);
3855 }
3856 
3857 /// Return a SCEV corresponding to ~V = -1-V
3858 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
3859   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3860     return getConstant(
3861                 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
3862 
3863   Type *Ty = V->getType();
3864   Ty = getEffectiveSCEVType(Ty);
3865   const SCEV *AllOnes =
3866                    getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
3867   return getMinusSCEV(AllOnes, V);
3868 }
3869 
3870 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
3871                                           SCEV::NoWrapFlags Flags,
3872                                           unsigned Depth) {
3873   // Fast path: X - X --> 0.
3874   if (LHS == RHS)
3875     return getZero(LHS->getType());
3876 
3877   // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
3878   // makes it so that we cannot make much use of NUW.
3879   auto AddFlags = SCEV::FlagAnyWrap;
3880   const bool RHSIsNotMinSigned =
3881       !getSignedRangeMin(RHS).isMinSignedValue();
3882   if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) {
3883     // Let M be the minimum representable signed value. Then (-1)*RHS
3884     // signed-wraps if and only if RHS is M. That can happen even for
3885     // a NSW subtraction because e.g. (-1)*M signed-wraps even though
3886     // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
3887     // (-1)*RHS, we need to prove that RHS != M.
3888     //
3889     // If LHS is non-negative and we know that LHS - RHS does not
3890     // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
3891     // either by proving that RHS > M or that LHS >= 0.
3892     if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
3893       AddFlags = SCEV::FlagNSW;
3894     }
3895   }
3896 
3897   // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
3898   // RHS is NSW and LHS >= 0.
3899   //
3900   // The difficulty here is that the NSW flag may have been proven
3901   // relative to a loop that is to be found in a recurrence in LHS and
3902   // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
3903   // larger scope than intended.
3904   auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3905 
3906   return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
3907 }
3908 
3909 const SCEV *
3910 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) {
3911   Type *SrcTy = V->getType();
3912   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3913          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3914          "Cannot truncate or zero extend with non-integer arguments!");
3915   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3916     return V;  // No conversion
3917   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
3918     return getTruncateExpr(V, Ty);
3919   return getZeroExtendExpr(V, Ty);
3920 }
3921 
3922 const SCEV *
3923 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
3924                                          Type *Ty) {
3925   Type *SrcTy = V->getType();
3926   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3927          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3928          "Cannot truncate or zero extend with non-integer arguments!");
3929   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3930     return V;  // No conversion
3931   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
3932     return getTruncateExpr(V, Ty);
3933   return getSignExtendExpr(V, Ty);
3934 }
3935 
3936 const SCEV *
3937 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
3938   Type *SrcTy = V->getType();
3939   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3940          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3941          "Cannot noop or zero extend with non-integer arguments!");
3942   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3943          "getNoopOrZeroExtend cannot truncate!");
3944   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3945     return V;  // No conversion
3946   return getZeroExtendExpr(V, Ty);
3947 }
3948 
3949 const SCEV *
3950 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
3951   Type *SrcTy = V->getType();
3952   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3953          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3954          "Cannot noop or sign extend with non-integer arguments!");
3955   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3956          "getNoopOrSignExtend cannot truncate!");
3957   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3958     return V;  // No conversion
3959   return getSignExtendExpr(V, Ty);
3960 }
3961 
3962 const SCEV *
3963 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
3964   Type *SrcTy = V->getType();
3965   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3966          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3967          "Cannot noop or any extend with non-integer arguments!");
3968   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3969          "getNoopOrAnyExtend cannot truncate!");
3970   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3971     return V;  // No conversion
3972   return getAnyExtendExpr(V, Ty);
3973 }
3974 
3975 const SCEV *
3976 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
3977   Type *SrcTy = V->getType();
3978   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3979          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3980          "Cannot truncate or noop with non-integer arguments!");
3981   assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
3982          "getTruncateOrNoop cannot extend!");
3983   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3984     return V;  // No conversion
3985   return getTruncateExpr(V, Ty);
3986 }
3987 
3988 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
3989                                                         const SCEV *RHS) {
3990   const SCEV *PromotedLHS = LHS;
3991   const SCEV *PromotedRHS = RHS;
3992 
3993   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3994     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3995   else
3996     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3997 
3998   return getUMaxExpr(PromotedLHS, PromotedRHS);
3999 }
4000 
4001 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
4002                                                         const SCEV *RHS) {
4003   const SCEV *PromotedLHS = LHS;
4004   const SCEV *PromotedRHS = RHS;
4005 
4006   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
4007     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
4008   else
4009     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
4010 
4011   return getUMinExpr(PromotedLHS, PromotedRHS);
4012 }
4013 
4014 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
4015   // A pointer operand may evaluate to a nonpointer expression, such as null.
4016   if (!V->getType()->isPointerTy())
4017     return V;
4018 
4019   if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
4020     return getPointerBase(Cast->getOperand());
4021   } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
4022     const SCEV *PtrOp = nullptr;
4023     for (const SCEV *NAryOp : NAry->operands()) {
4024       if (NAryOp->getType()->isPointerTy()) {
4025         // Cannot find the base of an expression with multiple pointer operands.
4026         if (PtrOp)
4027           return V;
4028         PtrOp = NAryOp;
4029       }
4030     }
4031     if (!PtrOp)
4032       return V;
4033     return getPointerBase(PtrOp);
4034   }
4035   return V;
4036 }
4037 
4038 /// Push users of the given Instruction onto the given Worklist.
4039 static void
4040 PushDefUseChildren(Instruction *I,
4041                    SmallVectorImpl<Instruction *> &Worklist) {
4042   // Push the def-use children onto the Worklist stack.
4043   for (User *U : I->users())
4044     Worklist.push_back(cast<Instruction>(U));
4045 }
4046 
4047 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) {
4048   SmallVector<Instruction *, 16> Worklist;
4049   PushDefUseChildren(PN, Worklist);
4050 
4051   SmallPtrSet<Instruction *, 8> Visited;
4052   Visited.insert(PN);
4053   while (!Worklist.empty()) {
4054     Instruction *I = Worklist.pop_back_val();
4055     if (!Visited.insert(I).second)
4056       continue;
4057 
4058     auto It = ValueExprMap.find_as(static_cast<Value *>(I));
4059     if (It != ValueExprMap.end()) {
4060       const SCEV *Old = It->second;
4061 
4062       // Short-circuit the def-use traversal if the symbolic name
4063       // ceases to appear in expressions.
4064       if (Old != SymName && !hasOperand(Old, SymName))
4065         continue;
4066 
4067       // SCEVUnknown for a PHI either means that it has an unrecognized
4068       // structure, it's a PHI that's in the progress of being computed
4069       // by createNodeForPHI, or it's a single-value PHI. In the first case,
4070       // additional loop trip count information isn't going to change anything.
4071       // In the second case, createNodeForPHI will perform the necessary
4072       // updates on its own when it gets to that point. In the third, we do
4073       // want to forget the SCEVUnknown.
4074       if (!isa<PHINode>(I) ||
4075           !isa<SCEVUnknown>(Old) ||
4076           (I != PN && Old == SymName)) {
4077         eraseValueFromMap(It->first);
4078         forgetMemoizedResults(Old);
4079       }
4080     }
4081 
4082     PushDefUseChildren(I, Worklist);
4083   }
4084 }
4085 
4086 namespace {
4087 
4088 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start
4089 /// expression in case its Loop is L. If it is not L then
4090 /// if IgnoreOtherLoops is true then use AddRec itself
4091 /// otherwise rewrite cannot be done.
4092 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4093 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
4094 public:
4095   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
4096                              bool IgnoreOtherLoops = true) {
4097     SCEVInitRewriter Rewriter(L, SE);
4098     const SCEV *Result = Rewriter.visit(S);
4099     if (Rewriter.hasSeenLoopVariantSCEVUnknown())
4100       return SE.getCouldNotCompute();
4101     return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops
4102                ? SE.getCouldNotCompute()
4103                : Result;
4104   }
4105 
4106   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4107     if (!SE.isLoopInvariant(Expr, L))
4108       SeenLoopVariantSCEVUnknown = true;
4109     return Expr;
4110   }
4111 
4112   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4113     // Only re-write AddRecExprs for this loop.
4114     if (Expr->getLoop() == L)
4115       return Expr->getStart();
4116     SeenOtherLoops = true;
4117     return Expr;
4118   }
4119 
4120   bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4121 
4122   bool hasSeenOtherLoops() { return SeenOtherLoops; }
4123 
4124 private:
4125   explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
4126       : SCEVRewriteVisitor(SE), L(L) {}
4127 
4128   const Loop *L;
4129   bool SeenLoopVariantSCEVUnknown = false;
4130   bool SeenOtherLoops = false;
4131 };
4132 
4133 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post
4134 /// increment expression in case its Loop is L. If it is not L then
4135 /// use AddRec itself.
4136 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4137 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> {
4138 public:
4139   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) {
4140     SCEVPostIncRewriter Rewriter(L, SE);
4141     const SCEV *Result = Rewriter.visit(S);
4142     return Rewriter.hasSeenLoopVariantSCEVUnknown()
4143         ? SE.getCouldNotCompute()
4144         : Result;
4145   }
4146 
4147   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4148     if (!SE.isLoopInvariant(Expr, L))
4149       SeenLoopVariantSCEVUnknown = true;
4150     return Expr;
4151   }
4152 
4153   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4154     // Only re-write AddRecExprs for this loop.
4155     if (Expr->getLoop() == L)
4156       return Expr->getPostIncExpr(SE);
4157     SeenOtherLoops = true;
4158     return Expr;
4159   }
4160 
4161   bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4162 
4163   bool hasSeenOtherLoops() { return SeenOtherLoops; }
4164 
4165 private:
4166   explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE)
4167       : SCEVRewriteVisitor(SE), L(L) {}
4168 
4169   const Loop *L;
4170   bool SeenLoopVariantSCEVUnknown = false;
4171   bool SeenOtherLoops = false;
4172 };
4173 
4174 /// This class evaluates the compare condition by matching it against the
4175 /// condition of loop latch. If there is a match we assume a true value
4176 /// for the condition while building SCEV nodes.
4177 class SCEVBackedgeConditionFolder
4178     : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> {
4179 public:
4180   static const SCEV *rewrite(const SCEV *S, const Loop *L,
4181                              ScalarEvolution &SE) {
4182     bool IsPosBECond = false;
4183     Value *BECond = nullptr;
4184     if (BasicBlock *Latch = L->getLoopLatch()) {
4185       BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator());
4186       if (BI && BI->isConditional()) {
4187         assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
4188                "Both outgoing branches should not target same header!");
4189         BECond = BI->getCondition();
4190         IsPosBECond = BI->getSuccessor(0) == L->getHeader();
4191       } else {
4192         return S;
4193       }
4194     }
4195     SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE);
4196     return Rewriter.visit(S);
4197   }
4198 
4199   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4200     const SCEV *Result = Expr;
4201     bool InvariantF = SE.isLoopInvariant(Expr, L);
4202 
4203     if (!InvariantF) {
4204       Instruction *I = cast<Instruction>(Expr->getValue());
4205       switch (I->getOpcode()) {
4206       case Instruction::Select: {
4207         SelectInst *SI = cast<SelectInst>(I);
4208         Optional<const SCEV *> Res =
4209             compareWithBackedgeCondition(SI->getCondition());
4210         if (Res.hasValue()) {
4211           bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne();
4212           Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue());
4213         }
4214         break;
4215       }
4216       default: {
4217         Optional<const SCEV *> Res = compareWithBackedgeCondition(I);
4218         if (Res.hasValue())
4219           Result = Res.getValue();
4220         break;
4221       }
4222       }
4223     }
4224     return Result;
4225   }
4226 
4227 private:
4228   explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond,
4229                                        bool IsPosBECond, ScalarEvolution &SE)
4230       : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond),
4231         IsPositiveBECond(IsPosBECond) {}
4232 
4233   Optional<const SCEV *> compareWithBackedgeCondition(Value *IC);
4234 
4235   const Loop *L;
4236   /// Loop back condition.
4237   Value *BackedgeCond = nullptr;
4238   /// Set to true if loop back is on positive branch condition.
4239   bool IsPositiveBECond;
4240 };
4241 
4242 Optional<const SCEV *>
4243 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) {
4244 
4245   // If value matches the backedge condition for loop latch,
4246   // then return a constant evolution node based on loopback
4247   // branch taken.
4248   if (BackedgeCond == IC)
4249     return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext()))
4250                             : SE.getZero(Type::getInt1Ty(SE.getContext()));
4251   return None;
4252 }
4253 
4254 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
4255 public:
4256   static const SCEV *rewrite(const SCEV *S, const Loop *L,
4257                              ScalarEvolution &SE) {
4258     SCEVShiftRewriter Rewriter(L, SE);
4259     const SCEV *Result = Rewriter.visit(S);
4260     return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
4261   }
4262 
4263   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4264     // Only allow AddRecExprs for this loop.
4265     if (!SE.isLoopInvariant(Expr, L))
4266       Valid = false;
4267     return Expr;
4268   }
4269 
4270   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4271     if (Expr->getLoop() == L && Expr->isAffine())
4272       return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
4273     Valid = false;
4274     return Expr;
4275   }
4276 
4277   bool isValid() { return Valid; }
4278 
4279 private:
4280   explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
4281       : SCEVRewriteVisitor(SE), L(L) {}
4282 
4283   const Loop *L;
4284   bool Valid = true;
4285 };
4286 
4287 } // end anonymous namespace
4288 
4289 SCEV::NoWrapFlags
4290 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
4291   if (!AR->isAffine())
4292     return SCEV::FlagAnyWrap;
4293 
4294   using OBO = OverflowingBinaryOperator;
4295 
4296   SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
4297 
4298   if (!AR->hasNoSignedWrap()) {
4299     ConstantRange AddRecRange = getSignedRange(AR);
4300     ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
4301 
4302     auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4303         Instruction::Add, IncRange, OBO::NoSignedWrap);
4304     if (NSWRegion.contains(AddRecRange))
4305       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
4306   }
4307 
4308   if (!AR->hasNoUnsignedWrap()) {
4309     ConstantRange AddRecRange = getUnsignedRange(AR);
4310     ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
4311 
4312     auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4313         Instruction::Add, IncRange, OBO::NoUnsignedWrap);
4314     if (NUWRegion.contains(AddRecRange))
4315       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
4316   }
4317 
4318   return Result;
4319 }
4320 
4321 namespace {
4322 
4323 /// Represents an abstract binary operation.  This may exist as a
4324 /// normal instruction or constant expression, or may have been
4325 /// derived from an expression tree.
4326 struct BinaryOp {
4327   unsigned Opcode;
4328   Value *LHS;
4329   Value *RHS;
4330   bool IsNSW = false;
4331   bool IsNUW = false;
4332 
4333   /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
4334   /// constant expression.
4335   Operator *Op = nullptr;
4336 
4337   explicit BinaryOp(Operator *Op)
4338       : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
4339         Op(Op) {
4340     if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
4341       IsNSW = OBO->hasNoSignedWrap();
4342       IsNUW = OBO->hasNoUnsignedWrap();
4343     }
4344   }
4345 
4346   explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
4347                     bool IsNUW = false)
4348       : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {}
4349 };
4350 
4351 } // end anonymous namespace
4352 
4353 /// Try to map \p V into a BinaryOp, and return \c None on failure.
4354 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) {
4355   auto *Op = dyn_cast<Operator>(V);
4356   if (!Op)
4357     return None;
4358 
4359   // Implementation detail: all the cleverness here should happen without
4360   // creating new SCEV expressions -- our caller knowns tricks to avoid creating
4361   // SCEV expressions when possible, and we should not break that.
4362 
4363   switch (Op->getOpcode()) {
4364   case Instruction::Add:
4365   case Instruction::Sub:
4366   case Instruction::Mul:
4367   case Instruction::UDiv:
4368   case Instruction::URem:
4369   case Instruction::And:
4370   case Instruction::Or:
4371   case Instruction::AShr:
4372   case Instruction::Shl:
4373     return BinaryOp(Op);
4374 
4375   case Instruction::Xor:
4376     if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
4377       // If the RHS of the xor is a signmask, then this is just an add.
4378       // Instcombine turns add of signmask into xor as a strength reduction step.
4379       if (RHSC->getValue().isSignMask())
4380         return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
4381     return BinaryOp(Op);
4382 
4383   case Instruction::LShr:
4384     // Turn logical shift right of a constant into a unsigned divide.
4385     if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
4386       uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
4387 
4388       // If the shift count is not less than the bitwidth, the result of
4389       // the shift is undefined. Don't try to analyze it, because the
4390       // resolution chosen here may differ from the resolution chosen in
4391       // other parts of the compiler.
4392       if (SA->getValue().ult(BitWidth)) {
4393         Constant *X =
4394             ConstantInt::get(SA->getContext(),
4395                              APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
4396         return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
4397       }
4398     }
4399     return BinaryOp(Op);
4400 
4401   case Instruction::ExtractValue: {
4402     auto *EVI = cast<ExtractValueInst>(Op);
4403     if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
4404       break;
4405 
4406     auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand());
4407     if (!CI)
4408       break;
4409 
4410     if (auto *F = CI->getCalledFunction())
4411       switch (F->getIntrinsicID()) {
4412       case Intrinsic::sadd_with_overflow:
4413       case Intrinsic::uadd_with_overflow:
4414         if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT))
4415           return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4416                           CI->getArgOperand(1));
4417 
4418         // Now that we know that all uses of the arithmetic-result component of
4419         // CI are guarded by the overflow check, we can go ahead and pretend
4420         // that the arithmetic is non-overflowing.
4421         if (F->getIntrinsicID() == Intrinsic::sadd_with_overflow)
4422           return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4423                           CI->getArgOperand(1), /* IsNSW = */ true,
4424                           /* IsNUW = */ false);
4425         else
4426           return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4427                           CI->getArgOperand(1), /* IsNSW = */ false,
4428                           /* IsNUW*/ true);
4429       case Intrinsic::ssub_with_overflow:
4430       case Intrinsic::usub_with_overflow:
4431         if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT))
4432           return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
4433                           CI->getArgOperand(1));
4434 
4435         // The same reasoning as sadd/uadd above.
4436         if (F->getIntrinsicID() == Intrinsic::ssub_with_overflow)
4437           return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
4438                           CI->getArgOperand(1), /* IsNSW = */ true,
4439                           /* IsNUW = */ false);
4440         else
4441           return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
4442                           CI->getArgOperand(1), /* IsNSW = */ false,
4443                           /* IsNUW = */ true);
4444       case Intrinsic::smul_with_overflow:
4445       case Intrinsic::umul_with_overflow:
4446         return BinaryOp(Instruction::Mul, CI->getArgOperand(0),
4447                         CI->getArgOperand(1));
4448       default:
4449         break;
4450       }
4451     break;
4452   }
4453 
4454   default:
4455     break;
4456   }
4457 
4458   return None;
4459 }
4460 
4461 /// Helper function to createAddRecFromPHIWithCasts. We have a phi
4462 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
4463 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
4464 /// way. This function checks if \p Op, an operand of this SCEVAddExpr,
4465 /// follows one of the following patterns:
4466 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4467 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4468 /// If the SCEV expression of \p Op conforms with one of the expected patterns
4469 /// we return the type of the truncation operation, and indicate whether the
4470 /// truncated type should be treated as signed/unsigned by setting
4471 /// \p Signed to true/false, respectively.
4472 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
4473                                bool &Signed, ScalarEvolution &SE) {
4474   // The case where Op == SymbolicPHI (that is, with no type conversions on
4475   // the way) is handled by the regular add recurrence creating logic and
4476   // would have already been triggered in createAddRecForPHI. Reaching it here
4477   // means that createAddRecFromPHI had failed for this PHI before (e.g.,
4478   // because one of the other operands of the SCEVAddExpr updating this PHI is
4479   // not invariant).
4480   //
4481   // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
4482   // this case predicates that allow us to prove that Op == SymbolicPHI will
4483   // be added.
4484   if (Op == SymbolicPHI)
4485     return nullptr;
4486 
4487   unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
4488   unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
4489   if (SourceBits != NewBits)
4490     return nullptr;
4491 
4492   const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op);
4493   const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op);
4494   if (!SExt && !ZExt)
4495     return nullptr;
4496   const SCEVTruncateExpr *Trunc =
4497       SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand())
4498            : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand());
4499   if (!Trunc)
4500     return nullptr;
4501   const SCEV *X = Trunc->getOperand();
4502   if (X != SymbolicPHI)
4503     return nullptr;
4504   Signed = SExt != nullptr;
4505   return Trunc->getType();
4506 }
4507 
4508 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
4509   if (!PN->getType()->isIntegerTy())
4510     return nullptr;
4511   const Loop *L = LI.getLoopFor(PN->getParent());
4512   if (!L || L->getHeader() != PN->getParent())
4513     return nullptr;
4514   return L;
4515 }
4516 
4517 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
4518 // computation that updates the phi follows the following pattern:
4519 //   (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
4520 // which correspond to a phi->trunc->sext/zext->add->phi update chain.
4521 // If so, try to see if it can be rewritten as an AddRecExpr under some
4522 // Predicates. If successful, return them as a pair. Also cache the results
4523 // of the analysis.
4524 //
4525 // Example usage scenario:
4526 //    Say the Rewriter is called for the following SCEV:
4527 //         8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4528 //    where:
4529 //         %X = phi i64 (%Start, %BEValue)
4530 //    It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
4531 //    and call this function with %SymbolicPHI = %X.
4532 //
4533 //    The analysis will find that the value coming around the backedge has
4534 //    the following SCEV:
4535 //         BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4536 //    Upon concluding that this matches the desired pattern, the function
4537 //    will return the pair {NewAddRec, SmallPredsVec} where:
4538 //         NewAddRec = {%Start,+,%Step}
4539 //         SmallPredsVec = {P1, P2, P3} as follows:
4540 //           P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
4541 //           P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
4542 //           P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
4543 //    The returned pair means that SymbolicPHI can be rewritten into NewAddRec
4544 //    under the predicates {P1,P2,P3}.
4545 //    This predicated rewrite will be cached in PredicatedSCEVRewrites:
4546 //         PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
4547 //
4548 // TODO's:
4549 //
4550 // 1) Extend the Induction descriptor to also support inductions that involve
4551 //    casts: When needed (namely, when we are called in the context of the
4552 //    vectorizer induction analysis), a Set of cast instructions will be
4553 //    populated by this method, and provided back to isInductionPHI. This is
4554 //    needed to allow the vectorizer to properly record them to be ignored by
4555 //    the cost model and to avoid vectorizing them (otherwise these casts,
4556 //    which are redundant under the runtime overflow checks, will be
4557 //    vectorized, which can be costly).
4558 //
4559 // 2) Support additional induction/PHISCEV patterns: We also want to support
4560 //    inductions where the sext-trunc / zext-trunc operations (partly) occur
4561 //    after the induction update operation (the induction increment):
4562 //
4563 //      (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
4564 //    which correspond to a phi->add->trunc->sext/zext->phi update chain.
4565 //
4566 //      (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
4567 //    which correspond to a phi->trunc->add->sext/zext->phi update chain.
4568 //
4569 // 3) Outline common code with createAddRecFromPHI to avoid duplication.
4570 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4571 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
4572   SmallVector<const SCEVPredicate *, 3> Predicates;
4573 
4574   // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
4575   // return an AddRec expression under some predicate.
4576 
4577   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
4578   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
4579   assert(L && "Expecting an integer loop header phi");
4580 
4581   // The loop may have multiple entrances or multiple exits; we can analyze
4582   // this phi as an addrec if it has a unique entry value and a unique
4583   // backedge value.
4584   Value *BEValueV = nullptr, *StartValueV = nullptr;
4585   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4586     Value *V = PN->getIncomingValue(i);
4587     if (L->contains(PN->getIncomingBlock(i))) {
4588       if (!BEValueV) {
4589         BEValueV = V;
4590       } else if (BEValueV != V) {
4591         BEValueV = nullptr;
4592         break;
4593       }
4594     } else if (!StartValueV) {
4595       StartValueV = V;
4596     } else if (StartValueV != V) {
4597       StartValueV = nullptr;
4598       break;
4599     }
4600   }
4601   if (!BEValueV || !StartValueV)
4602     return None;
4603 
4604   const SCEV *BEValue = getSCEV(BEValueV);
4605 
4606   // If the value coming around the backedge is an add with the symbolic
4607   // value we just inserted, possibly with casts that we can ignore under
4608   // an appropriate runtime guard, then we found a simple induction variable!
4609   const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
4610   if (!Add)
4611     return None;
4612 
4613   // If there is a single occurrence of the symbolic value, possibly
4614   // casted, replace it with a recurrence.
4615   unsigned FoundIndex = Add->getNumOperands();
4616   Type *TruncTy = nullptr;
4617   bool Signed;
4618   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4619     if ((TruncTy =
4620              isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
4621       if (FoundIndex == e) {
4622         FoundIndex = i;
4623         break;
4624       }
4625 
4626   if (FoundIndex == Add->getNumOperands())
4627     return None;
4628 
4629   // Create an add with everything but the specified operand.
4630   SmallVector<const SCEV *, 8> Ops;
4631   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4632     if (i != FoundIndex)
4633       Ops.push_back(Add->getOperand(i));
4634   const SCEV *Accum = getAddExpr(Ops);
4635 
4636   // The runtime checks will not be valid if the step amount is
4637   // varying inside the loop.
4638   if (!isLoopInvariant(Accum, L))
4639     return None;
4640 
4641   // *** Part2: Create the predicates
4642 
4643   // Analysis was successful: we have a phi-with-cast pattern for which we
4644   // can return an AddRec expression under the following predicates:
4645   //
4646   // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
4647   //     fits within the truncated type (does not overflow) for i = 0 to n-1.
4648   // P2: An Equal predicate that guarantees that
4649   //     Start = (Ext ix (Trunc iy (Start) to ix) to iy)
4650   // P3: An Equal predicate that guarantees that
4651   //     Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
4652   //
4653   // As we next prove, the above predicates guarantee that:
4654   //     Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
4655   //
4656   //
4657   // More formally, we want to prove that:
4658   //     Expr(i+1) = Start + (i+1) * Accum
4659   //               = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4660   //
4661   // Given that:
4662   // 1) Expr(0) = Start
4663   // 2) Expr(1) = Start + Accum
4664   //            = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
4665   // 3) Induction hypothesis (step i):
4666   //    Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
4667   //
4668   // Proof:
4669   //  Expr(i+1) =
4670   //   = Start + (i+1)*Accum
4671   //   = (Start + i*Accum) + Accum
4672   //   = Expr(i) + Accum
4673   //   = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
4674   //                                                             :: from step i
4675   //
4676   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
4677   //
4678   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
4679   //     + (Ext ix (Trunc iy (Accum) to ix) to iy)
4680   //     + Accum                                                     :: from P3
4681   //
4682   //   = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
4683   //     + Accum                            :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
4684   //
4685   //   = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
4686   //   = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4687   //
4688   // By induction, the same applies to all iterations 1<=i<n:
4689   //
4690 
4691   // Create a truncated addrec for which we will add a no overflow check (P1).
4692   const SCEV *StartVal = getSCEV(StartValueV);
4693   const SCEV *PHISCEV =
4694       getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
4695                     getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap);
4696 
4697   // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
4698   // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
4699   // will be constant.
4700   //
4701   //  If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
4702   // add P1.
4703   if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
4704     SCEVWrapPredicate::IncrementWrapFlags AddedFlags =
4705         Signed ? SCEVWrapPredicate::IncrementNSSW
4706                : SCEVWrapPredicate::IncrementNUSW;
4707     const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
4708     Predicates.push_back(AddRecPred);
4709   }
4710 
4711   // Create the Equal Predicates P2,P3:
4712 
4713   // It is possible that the predicates P2 and/or P3 are computable at
4714   // compile time due to StartVal and/or Accum being constants.
4715   // If either one is, then we can check that now and escape if either P2
4716   // or P3 is false.
4717 
4718   // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
4719   // for each of StartVal and Accum
4720   auto getExtendedExpr = [&](const SCEV *Expr,
4721                              bool CreateSignExtend) -> const SCEV * {
4722     assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant");
4723     const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
4724     const SCEV *ExtendedExpr =
4725         CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType())
4726                          : getZeroExtendExpr(TruncatedExpr, Expr->getType());
4727     return ExtendedExpr;
4728   };
4729 
4730   // Given:
4731   //  ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
4732   //               = getExtendedExpr(Expr)
4733   // Determine whether the predicate P: Expr == ExtendedExpr
4734   // is known to be false at compile time
4735   auto PredIsKnownFalse = [&](const SCEV *Expr,
4736                               const SCEV *ExtendedExpr) -> bool {
4737     return Expr != ExtendedExpr &&
4738            isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr);
4739   };
4740 
4741   const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
4742   if (PredIsKnownFalse(StartVal, StartExtended)) {
4743     DEBUG(dbgs() << "P2 is compile-time false\n";);
4744     return None;
4745   }
4746 
4747   // The Step is always Signed (because the overflow checks are either
4748   // NSSW or NUSW)
4749   const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true);
4750   if (PredIsKnownFalse(Accum, AccumExtended)) {
4751     DEBUG(dbgs() << "P3 is compile-time false\n";);
4752     return None;
4753   }
4754 
4755   auto AppendPredicate = [&](const SCEV *Expr,
4756                              const SCEV *ExtendedExpr) -> void {
4757     if (Expr != ExtendedExpr &&
4758         !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
4759       const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
4760       DEBUG (dbgs() << "Added Predicate: " << *Pred);
4761       Predicates.push_back(Pred);
4762     }
4763   };
4764 
4765   AppendPredicate(StartVal, StartExtended);
4766   AppendPredicate(Accum, AccumExtended);
4767 
4768   // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
4769   // which the casts had been folded away. The caller can rewrite SymbolicPHI
4770   // into NewAR if it will also add the runtime overflow checks specified in
4771   // Predicates.
4772   auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap);
4773 
4774   std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
4775       std::make_pair(NewAR, Predicates);
4776   // Remember the result of the analysis for this SCEV at this locayyytion.
4777   PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
4778   return PredRewrite;
4779 }
4780 
4781 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4782 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) {
4783   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
4784   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
4785   if (!L)
4786     return None;
4787 
4788   // Check to see if we already analyzed this PHI.
4789   auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
4790   if (I != PredicatedSCEVRewrites.end()) {
4791     std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
4792         I->second;
4793     // Analysis was done before and failed to create an AddRec:
4794     if (Rewrite.first == SymbolicPHI)
4795       return None;
4796     // Analysis was done before and succeeded to create an AddRec under
4797     // a predicate:
4798     assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec");
4799     assert(!(Rewrite.second).empty() && "Expected to find Predicates");
4800     return Rewrite;
4801   }
4802 
4803   Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4804     Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
4805 
4806   // Record in the cache that the analysis failed
4807   if (!Rewrite) {
4808     SmallVector<const SCEVPredicate *, 3> Predicates;
4809     PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
4810     return None;
4811   }
4812 
4813   return Rewrite;
4814 }
4815 
4816 // FIXME: This utility is currently required because the Rewriter currently
4817 // does not rewrite this expression:
4818 // {0, +, (sext ix (trunc iy to ix) to iy)}
4819 // into {0, +, %step},
4820 // even when the following Equal predicate exists:
4821 // "%step == (sext ix (trunc iy to ix) to iy)".
4822 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds(
4823     const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const {
4824   if (AR1 == AR2)
4825     return true;
4826 
4827   auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool {
4828     if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) &&
4829         !Preds.implies(SE.getEqualPredicate(Expr2, Expr1)))
4830       return false;
4831     return true;
4832   };
4833 
4834   if (!areExprsEqual(AR1->getStart(), AR2->getStart()) ||
4835       !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE)))
4836     return false;
4837   return true;
4838 }
4839 
4840 /// A helper function for createAddRecFromPHI to handle simple cases.
4841 ///
4842 /// This function tries to find an AddRec expression for the simplest (yet most
4843 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
4844 /// If it fails, createAddRecFromPHI will use a more general, but slow,
4845 /// technique for finding the AddRec expression.
4846 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
4847                                                       Value *BEValueV,
4848                                                       Value *StartValueV) {
4849   const Loop *L = LI.getLoopFor(PN->getParent());
4850   assert(L && L->getHeader() == PN->getParent());
4851   assert(BEValueV && StartValueV);
4852 
4853   auto BO = MatchBinaryOp(BEValueV, DT);
4854   if (!BO)
4855     return nullptr;
4856 
4857   if (BO->Opcode != Instruction::Add)
4858     return nullptr;
4859 
4860   const SCEV *Accum = nullptr;
4861   if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
4862     Accum = getSCEV(BO->RHS);
4863   else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
4864     Accum = getSCEV(BO->LHS);
4865 
4866   if (!Accum)
4867     return nullptr;
4868 
4869   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4870   if (BO->IsNUW)
4871     Flags = setFlags(Flags, SCEV::FlagNUW);
4872   if (BO->IsNSW)
4873     Flags = setFlags(Flags, SCEV::FlagNSW);
4874 
4875   const SCEV *StartVal = getSCEV(StartValueV);
4876   const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
4877 
4878   ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
4879 
4880   // We can add Flags to the post-inc expression only if we
4881   // know that it is *undefined behavior* for BEValueV to
4882   // overflow.
4883   if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
4884     if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
4885       (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
4886 
4887   return PHISCEV;
4888 }
4889 
4890 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
4891   const Loop *L = LI.getLoopFor(PN->getParent());
4892   if (!L || L->getHeader() != PN->getParent())
4893     return nullptr;
4894 
4895   // The loop may have multiple entrances or multiple exits; we can analyze
4896   // this phi as an addrec if it has a unique entry value and a unique
4897   // backedge value.
4898   Value *BEValueV = nullptr, *StartValueV = nullptr;
4899   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4900     Value *V = PN->getIncomingValue(i);
4901     if (L->contains(PN->getIncomingBlock(i))) {
4902       if (!BEValueV) {
4903         BEValueV = V;
4904       } else if (BEValueV != V) {
4905         BEValueV = nullptr;
4906         break;
4907       }
4908     } else if (!StartValueV) {
4909       StartValueV = V;
4910     } else if (StartValueV != V) {
4911       StartValueV = nullptr;
4912       break;
4913     }
4914   }
4915   if (!BEValueV || !StartValueV)
4916     return nullptr;
4917 
4918   assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
4919          "PHI node already processed?");
4920 
4921   // First, try to find AddRec expression without creating a fictituos symbolic
4922   // value for PN.
4923   if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
4924     return S;
4925 
4926   // Handle PHI node value symbolically.
4927   const SCEV *SymbolicName = getUnknown(PN);
4928   ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName});
4929 
4930   // Using this symbolic name for the PHI, analyze the value coming around
4931   // the back-edge.
4932   const SCEV *BEValue = getSCEV(BEValueV);
4933 
4934   // NOTE: If BEValue is loop invariant, we know that the PHI node just
4935   // has a special value for the first iteration of the loop.
4936 
4937   // If the value coming around the backedge is an add with the symbolic
4938   // value we just inserted, then we found a simple induction variable!
4939   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
4940     // If there is a single occurrence of the symbolic value, replace it
4941     // with a recurrence.
4942     unsigned FoundIndex = Add->getNumOperands();
4943     for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4944       if (Add->getOperand(i) == SymbolicName)
4945         if (FoundIndex == e) {
4946           FoundIndex = i;
4947           break;
4948         }
4949 
4950     if (FoundIndex != Add->getNumOperands()) {
4951       // Create an add with everything but the specified operand.
4952       SmallVector<const SCEV *, 8> Ops;
4953       for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4954         if (i != FoundIndex)
4955           Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i),
4956                                                              L, *this));
4957       const SCEV *Accum = getAddExpr(Ops);
4958 
4959       // This is not a valid addrec if the step amount is varying each
4960       // loop iteration, but is not itself an addrec in this loop.
4961       if (isLoopInvariant(Accum, L) ||
4962           (isa<SCEVAddRecExpr>(Accum) &&
4963            cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
4964         SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4965 
4966         if (auto BO = MatchBinaryOp(BEValueV, DT)) {
4967           if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
4968             if (BO->IsNUW)
4969               Flags = setFlags(Flags, SCEV::FlagNUW);
4970             if (BO->IsNSW)
4971               Flags = setFlags(Flags, SCEV::FlagNSW);
4972           }
4973         } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
4974           // If the increment is an inbounds GEP, then we know the address
4975           // space cannot be wrapped around. We cannot make any guarantee
4976           // about signed or unsigned overflow because pointers are
4977           // unsigned but we may have a negative index from the base
4978           // pointer. We can guarantee that no unsigned wrap occurs if the
4979           // indices form a positive value.
4980           if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
4981             Flags = setFlags(Flags, SCEV::FlagNW);
4982 
4983             const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
4984             if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
4985               Flags = setFlags(Flags, SCEV::FlagNUW);
4986           }
4987 
4988           // We cannot transfer nuw and nsw flags from subtraction
4989           // operations -- sub nuw X, Y is not the same as add nuw X, -Y
4990           // for instance.
4991         }
4992 
4993         const SCEV *StartVal = getSCEV(StartValueV);
4994         const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
4995 
4996         // Okay, for the entire analysis of this edge we assumed the PHI
4997         // to be symbolic.  We now need to go back and purge all of the
4998         // entries for the scalars that use the symbolic expression.
4999         forgetSymbolicName(PN, SymbolicName);
5000         ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
5001 
5002         // We can add Flags to the post-inc expression only if we
5003         // know that it is *undefined behavior* for BEValueV to
5004         // overflow.
5005         if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5006           if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5007             (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5008 
5009         return PHISCEV;
5010       }
5011     }
5012   } else {
5013     // Otherwise, this could be a loop like this:
5014     //     i = 0;  for (j = 1; ..; ++j) { ....  i = j; }
5015     // In this case, j = {1,+,1}  and BEValue is j.
5016     // Because the other in-value of i (0) fits the evolution of BEValue
5017     // i really is an addrec evolution.
5018     //
5019     // We can generalize this saying that i is the shifted value of BEValue
5020     // by one iteration:
5021     //   PHI(f(0), f({1,+,1})) --> f({0,+,1})
5022     const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
5023     const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false);
5024     if (Shifted != getCouldNotCompute() &&
5025         Start != getCouldNotCompute()) {
5026       const SCEV *StartVal = getSCEV(StartValueV);
5027       if (Start == StartVal) {
5028         // Okay, for the entire analysis of this edge we assumed the PHI
5029         // to be symbolic.  We now need to go back and purge all of the
5030         // entries for the scalars that use the symbolic expression.
5031         forgetSymbolicName(PN, SymbolicName);
5032         ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted;
5033         return Shifted;
5034       }
5035     }
5036   }
5037 
5038   // Remove the temporary PHI node SCEV that has been inserted while intending
5039   // to create an AddRecExpr for this PHI node. We can not keep this temporary
5040   // as it will prevent later (possibly simpler) SCEV expressions to be added
5041   // to the ValueExprMap.
5042   eraseValueFromMap(PN);
5043 
5044   return nullptr;
5045 }
5046 
5047 // Checks if the SCEV S is available at BB.  S is considered available at BB
5048 // if S can be materialized at BB without introducing a fault.
5049 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
5050                                BasicBlock *BB) {
5051   struct CheckAvailable {
5052     bool TraversalDone = false;
5053     bool Available = true;
5054 
5055     const Loop *L = nullptr;  // The loop BB is in (can be nullptr)
5056     BasicBlock *BB = nullptr;
5057     DominatorTree &DT;
5058 
5059     CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
5060       : L(L), BB(BB), DT(DT) {}
5061 
5062     bool setUnavailable() {
5063       TraversalDone = true;
5064       Available = false;
5065       return false;
5066     }
5067 
5068     bool follow(const SCEV *S) {
5069       switch (S->getSCEVType()) {
5070       case scConstant: case scTruncate: case scZeroExtend: case scSignExtend:
5071       case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr:
5072         // These expressions are available if their operand(s) is/are.
5073         return true;
5074 
5075       case scAddRecExpr: {
5076         // We allow add recurrences that are on the loop BB is in, or some
5077         // outer loop.  This guarantees availability because the value of the
5078         // add recurrence at BB is simply the "current" value of the induction
5079         // variable.  We can relax this in the future; for instance an add
5080         // recurrence on a sibling dominating loop is also available at BB.
5081         const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
5082         if (L && (ARLoop == L || ARLoop->contains(L)))
5083           return true;
5084 
5085         return setUnavailable();
5086       }
5087 
5088       case scUnknown: {
5089         // For SCEVUnknown, we check for simple dominance.
5090         const auto *SU = cast<SCEVUnknown>(S);
5091         Value *V = SU->getValue();
5092 
5093         if (isa<Argument>(V))
5094           return false;
5095 
5096         if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
5097           return false;
5098 
5099         return setUnavailable();
5100       }
5101 
5102       case scUDivExpr:
5103       case scCouldNotCompute:
5104         // We do not try to smart about these at all.
5105         return setUnavailable();
5106       }
5107       llvm_unreachable("switch should be fully covered!");
5108     }
5109 
5110     bool isDone() { return TraversalDone; }
5111   };
5112 
5113   CheckAvailable CA(L, BB, DT);
5114   SCEVTraversal<CheckAvailable> ST(CA);
5115 
5116   ST.visitAll(S);
5117   return CA.Available;
5118 }
5119 
5120 // Try to match a control flow sequence that branches out at BI and merges back
5121 // at Merge into a "C ? LHS : RHS" select pattern.  Return true on a successful
5122 // match.
5123 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
5124                           Value *&C, Value *&LHS, Value *&RHS) {
5125   C = BI->getCondition();
5126 
5127   BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
5128   BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
5129 
5130   if (!LeftEdge.isSingleEdge())
5131     return false;
5132 
5133   assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
5134 
5135   Use &LeftUse = Merge->getOperandUse(0);
5136   Use &RightUse = Merge->getOperandUse(1);
5137 
5138   if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
5139     LHS = LeftUse;
5140     RHS = RightUse;
5141     return true;
5142   }
5143 
5144   if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
5145     LHS = RightUse;
5146     RHS = LeftUse;
5147     return true;
5148   }
5149 
5150   return false;
5151 }
5152 
5153 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
5154   auto IsReachable =
5155       [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
5156   if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
5157     const Loop *L = LI.getLoopFor(PN->getParent());
5158 
5159     // We don't want to break LCSSA, even in a SCEV expression tree.
5160     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
5161       if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
5162         return nullptr;
5163 
5164     // Try to match
5165     //
5166     //  br %cond, label %left, label %right
5167     // left:
5168     //  br label %merge
5169     // right:
5170     //  br label %merge
5171     // merge:
5172     //  V = phi [ %x, %left ], [ %y, %right ]
5173     //
5174     // as "select %cond, %x, %y"
5175 
5176     BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
5177     assert(IDom && "At least the entry block should dominate PN");
5178 
5179     auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
5180     Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
5181 
5182     if (BI && BI->isConditional() &&
5183         BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
5184         IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
5185         IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
5186       return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
5187   }
5188 
5189   return nullptr;
5190 }
5191 
5192 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
5193   if (const SCEV *S = createAddRecFromPHI(PN))
5194     return S;
5195 
5196   if (const SCEV *S = createNodeFromSelectLikePHI(PN))
5197     return S;
5198 
5199   // If the PHI has a single incoming value, follow that value, unless the
5200   // PHI's incoming blocks are in a different loop, in which case doing so
5201   // risks breaking LCSSA form. Instcombine would normally zap these, but
5202   // it doesn't have DominatorTree information, so it may miss cases.
5203   if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC}))
5204     if (LI.replacementPreservesLCSSAForm(PN, V))
5205       return getSCEV(V);
5206 
5207   // If it's not a loop phi, we can't handle it yet.
5208   return getUnknown(PN);
5209 }
5210 
5211 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I,
5212                                                       Value *Cond,
5213                                                       Value *TrueVal,
5214                                                       Value *FalseVal) {
5215   // Handle "constant" branch or select. This can occur for instance when a
5216   // loop pass transforms an inner loop and moves on to process the outer loop.
5217   if (auto *CI = dyn_cast<ConstantInt>(Cond))
5218     return getSCEV(CI->isOne() ? TrueVal : FalseVal);
5219 
5220   // Try to match some simple smax or umax patterns.
5221   auto *ICI = dyn_cast<ICmpInst>(Cond);
5222   if (!ICI)
5223     return getUnknown(I);
5224 
5225   Value *LHS = ICI->getOperand(0);
5226   Value *RHS = ICI->getOperand(1);
5227 
5228   switch (ICI->getPredicate()) {
5229   case ICmpInst::ICMP_SLT:
5230   case ICmpInst::ICMP_SLE:
5231     std::swap(LHS, RHS);
5232     LLVM_FALLTHROUGH;
5233   case ICmpInst::ICMP_SGT:
5234   case ICmpInst::ICMP_SGE:
5235     // a >s b ? a+x : b+x  ->  smax(a, b)+x
5236     // a >s b ? b+x : a+x  ->  smin(a, b)+x
5237     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5238       const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType());
5239       const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType());
5240       const SCEV *LA = getSCEV(TrueVal);
5241       const SCEV *RA = getSCEV(FalseVal);
5242       const SCEV *LDiff = getMinusSCEV(LA, LS);
5243       const SCEV *RDiff = getMinusSCEV(RA, RS);
5244       if (LDiff == RDiff)
5245         return getAddExpr(getSMaxExpr(LS, RS), LDiff);
5246       LDiff = getMinusSCEV(LA, RS);
5247       RDiff = getMinusSCEV(RA, LS);
5248       if (LDiff == RDiff)
5249         return getAddExpr(getSMinExpr(LS, RS), LDiff);
5250     }
5251     break;
5252   case ICmpInst::ICMP_ULT:
5253   case ICmpInst::ICMP_ULE:
5254     std::swap(LHS, RHS);
5255     LLVM_FALLTHROUGH;
5256   case ICmpInst::ICMP_UGT:
5257   case ICmpInst::ICMP_UGE:
5258     // a >u b ? a+x : b+x  ->  umax(a, b)+x
5259     // a >u b ? b+x : a+x  ->  umin(a, b)+x
5260     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5261       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5262       const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType());
5263       const SCEV *LA = getSCEV(TrueVal);
5264       const SCEV *RA = getSCEV(FalseVal);
5265       const SCEV *LDiff = getMinusSCEV(LA, LS);
5266       const SCEV *RDiff = getMinusSCEV(RA, RS);
5267       if (LDiff == RDiff)
5268         return getAddExpr(getUMaxExpr(LS, RS), LDiff);
5269       LDiff = getMinusSCEV(LA, RS);
5270       RDiff = getMinusSCEV(RA, LS);
5271       if (LDiff == RDiff)
5272         return getAddExpr(getUMinExpr(LS, RS), LDiff);
5273     }
5274     break;
5275   case ICmpInst::ICMP_NE:
5276     // n != 0 ? n+x : 1+x  ->  umax(n, 1)+x
5277     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5278         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5279       const SCEV *One = getOne(I->getType());
5280       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5281       const SCEV *LA = getSCEV(TrueVal);
5282       const SCEV *RA = getSCEV(FalseVal);
5283       const SCEV *LDiff = getMinusSCEV(LA, LS);
5284       const SCEV *RDiff = getMinusSCEV(RA, One);
5285       if (LDiff == RDiff)
5286         return getAddExpr(getUMaxExpr(One, LS), LDiff);
5287     }
5288     break;
5289   case ICmpInst::ICMP_EQ:
5290     // n == 0 ? 1+x : n+x  ->  umax(n, 1)+x
5291     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5292         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5293       const SCEV *One = getOne(I->getType());
5294       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5295       const SCEV *LA = getSCEV(TrueVal);
5296       const SCEV *RA = getSCEV(FalseVal);
5297       const SCEV *LDiff = getMinusSCEV(LA, One);
5298       const SCEV *RDiff = getMinusSCEV(RA, LS);
5299       if (LDiff == RDiff)
5300         return getAddExpr(getUMaxExpr(One, LS), LDiff);
5301     }
5302     break;
5303   default:
5304     break;
5305   }
5306 
5307   return getUnknown(I);
5308 }
5309 
5310 /// Expand GEP instructions into add and multiply operations. This allows them
5311 /// to be analyzed by regular SCEV code.
5312 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
5313   // Don't attempt to analyze GEPs over unsized objects.
5314   if (!GEP->getSourceElementType()->isSized())
5315     return getUnknown(GEP);
5316 
5317   SmallVector<const SCEV *, 4> IndexExprs;
5318   for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
5319     IndexExprs.push_back(getSCEV(*Index));
5320   return getGEPExpr(GEP, IndexExprs);
5321 }
5322 
5323 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) {
5324   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5325     return C->getAPInt().countTrailingZeros();
5326 
5327   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
5328     return std::min(GetMinTrailingZeros(T->getOperand()),
5329                     (uint32_t)getTypeSizeInBits(T->getType()));
5330 
5331   if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
5332     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5333     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5334                ? getTypeSizeInBits(E->getType())
5335                : OpRes;
5336   }
5337 
5338   if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
5339     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5340     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5341                ? getTypeSizeInBits(E->getType())
5342                : OpRes;
5343   }
5344 
5345   if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
5346     // The result is the min of all operands results.
5347     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5348     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5349       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5350     return MinOpRes;
5351   }
5352 
5353   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
5354     // The result is the sum of all operands results.
5355     uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
5356     uint32_t BitWidth = getTypeSizeInBits(M->getType());
5357     for (unsigned i = 1, e = M->getNumOperands();
5358          SumOpRes != BitWidth && i != e; ++i)
5359       SumOpRes =
5360           std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth);
5361     return SumOpRes;
5362   }
5363 
5364   if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
5365     // The result is the min of all operands results.
5366     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5367     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5368       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5369     return MinOpRes;
5370   }
5371 
5372   if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
5373     // The result is the min of all operands results.
5374     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5375     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5376       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5377     return MinOpRes;
5378   }
5379 
5380   if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
5381     // The result is the min of all operands results.
5382     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5383     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5384       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5385     return MinOpRes;
5386   }
5387 
5388   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5389     // For a SCEVUnknown, ask ValueTracking.
5390     KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT);
5391     return Known.countMinTrailingZeros();
5392   }
5393 
5394   // SCEVUDivExpr
5395   return 0;
5396 }
5397 
5398 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
5399   auto I = MinTrailingZerosCache.find(S);
5400   if (I != MinTrailingZerosCache.end())
5401     return I->second;
5402 
5403   uint32_t Result = GetMinTrailingZerosImpl(S);
5404   auto InsertPair = MinTrailingZerosCache.insert({S, Result});
5405   assert(InsertPair.second && "Should insert a new key");
5406   return InsertPair.first->second;
5407 }
5408 
5409 /// Helper method to assign a range to V from metadata present in the IR.
5410 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
5411   if (Instruction *I = dyn_cast<Instruction>(V))
5412     if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
5413       return getConstantRangeFromMetadata(*MD);
5414 
5415   return None;
5416 }
5417 
5418 /// Determine the range for a particular SCEV.  If SignHint is
5419 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
5420 /// with a "cleaner" unsigned (resp. signed) representation.
5421 const ConstantRange &
5422 ScalarEvolution::getRangeRef(const SCEV *S,
5423                              ScalarEvolution::RangeSignHint SignHint) {
5424   DenseMap<const SCEV *, ConstantRange> &Cache =
5425       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
5426                                                        : SignedRanges;
5427 
5428   // See if we've computed this range already.
5429   DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
5430   if (I != Cache.end())
5431     return I->second;
5432 
5433   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5434     return setRange(C, SignHint, ConstantRange(C->getAPInt()));
5435 
5436   unsigned BitWidth = getTypeSizeInBits(S->getType());
5437   ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
5438 
5439   // If the value has known zeros, the maximum value will have those known zeros
5440   // as well.
5441   uint32_t TZ = GetMinTrailingZeros(S);
5442   if (TZ != 0) {
5443     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
5444       ConservativeResult =
5445           ConstantRange(APInt::getMinValue(BitWidth),
5446                         APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
5447     else
5448       ConservativeResult = ConstantRange(
5449           APInt::getSignedMinValue(BitWidth),
5450           APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
5451   }
5452 
5453   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
5454     ConstantRange X = getRangeRef(Add->getOperand(0), SignHint);
5455     for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
5456       X = X.add(getRangeRef(Add->getOperand(i), SignHint));
5457     return setRange(Add, SignHint, ConservativeResult.intersectWith(X));
5458   }
5459 
5460   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
5461     ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint);
5462     for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
5463       X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint));
5464     return setRange(Mul, SignHint, ConservativeResult.intersectWith(X));
5465   }
5466 
5467   if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
5468     ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint);
5469     for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
5470       X = X.smax(getRangeRef(SMax->getOperand(i), SignHint));
5471     return setRange(SMax, SignHint, ConservativeResult.intersectWith(X));
5472   }
5473 
5474   if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
5475     ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint);
5476     for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
5477       X = X.umax(getRangeRef(UMax->getOperand(i), SignHint));
5478     return setRange(UMax, SignHint, ConservativeResult.intersectWith(X));
5479   }
5480 
5481   if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
5482     ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint);
5483     ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint);
5484     return setRange(UDiv, SignHint,
5485                     ConservativeResult.intersectWith(X.udiv(Y)));
5486   }
5487 
5488   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
5489     ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint);
5490     return setRange(ZExt, SignHint,
5491                     ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
5492   }
5493 
5494   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
5495     ConstantRange X = getRangeRef(SExt->getOperand(), SignHint);
5496     return setRange(SExt, SignHint,
5497                     ConservativeResult.intersectWith(X.signExtend(BitWidth)));
5498   }
5499 
5500   if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
5501     ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint);
5502     return setRange(Trunc, SignHint,
5503                     ConservativeResult.intersectWith(X.truncate(BitWidth)));
5504   }
5505 
5506   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
5507     // If there's no unsigned wrap, the value will never be less than its
5508     // initial value.
5509     if (AddRec->hasNoUnsignedWrap())
5510       if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
5511         if (!C->getValue()->isZero())
5512           ConservativeResult = ConservativeResult.intersectWith(
5513               ConstantRange(C->getAPInt(), APInt(BitWidth, 0)));
5514 
5515     // If there's no signed wrap, and all the operands have the same sign or
5516     // zero, the value won't ever change sign.
5517     if (AddRec->hasNoSignedWrap()) {
5518       bool AllNonNeg = true;
5519       bool AllNonPos = true;
5520       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
5521         if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
5522         if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
5523       }
5524       if (AllNonNeg)
5525         ConservativeResult = ConservativeResult.intersectWith(
5526           ConstantRange(APInt(BitWidth, 0),
5527                         APInt::getSignedMinValue(BitWidth)));
5528       else if (AllNonPos)
5529         ConservativeResult = ConservativeResult.intersectWith(
5530           ConstantRange(APInt::getSignedMinValue(BitWidth),
5531                         APInt(BitWidth, 1)));
5532     }
5533 
5534     // TODO: non-affine addrec
5535     if (AddRec->isAffine()) {
5536       const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
5537       if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
5538           getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
5539         auto RangeFromAffine = getRangeForAffineAR(
5540             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
5541             BitWidth);
5542         if (!RangeFromAffine.isFullSet())
5543           ConservativeResult =
5544               ConservativeResult.intersectWith(RangeFromAffine);
5545 
5546         auto RangeFromFactoring = getRangeViaFactoring(
5547             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
5548             BitWidth);
5549         if (!RangeFromFactoring.isFullSet())
5550           ConservativeResult =
5551               ConservativeResult.intersectWith(RangeFromFactoring);
5552       }
5553     }
5554 
5555     return setRange(AddRec, SignHint, std::move(ConservativeResult));
5556   }
5557 
5558   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5559     // Check if the IR explicitly contains !range metadata.
5560     Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
5561     if (MDRange.hasValue())
5562       ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue());
5563 
5564     // Split here to avoid paying the compile-time cost of calling both
5565     // computeKnownBits and ComputeNumSignBits.  This restriction can be lifted
5566     // if needed.
5567     const DataLayout &DL = getDataLayout();
5568     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
5569       // For a SCEVUnknown, ask ValueTracking.
5570       KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
5571       if (Known.One != ~Known.Zero + 1)
5572         ConservativeResult =
5573             ConservativeResult.intersectWith(ConstantRange(Known.One,
5574                                                            ~Known.Zero + 1));
5575     } else {
5576       assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED &&
5577              "generalize as needed!");
5578       unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
5579       if (NS > 1)
5580         ConservativeResult = ConservativeResult.intersectWith(
5581             ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
5582                           APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1));
5583     }
5584 
5585     // A range of Phi is a subset of union of all ranges of its input.
5586     if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) {
5587       // Make sure that we do not run over cycled Phis.
5588       if (PendingPhiRanges.insert(Phi).second) {
5589         ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false);
5590         for (auto &Op : Phi->operands()) {
5591           auto OpRange = getRangeRef(getSCEV(Op), SignHint);
5592           RangeFromOps = RangeFromOps.unionWith(OpRange);
5593           // No point to continue if we already have a full set.
5594           if (RangeFromOps.isFullSet())
5595             break;
5596         }
5597         ConservativeResult = ConservativeResult.intersectWith(RangeFromOps);
5598         bool Erased = PendingPhiRanges.erase(Phi);
5599         assert(Erased && "Failed to erase Phi properly?");
5600         (void) Erased;
5601       }
5602     }
5603 
5604     return setRange(U, SignHint, std::move(ConservativeResult));
5605   }
5606 
5607   return setRange(S, SignHint, std::move(ConservativeResult));
5608 }
5609 
5610 // Given a StartRange, Step and MaxBECount for an expression compute a range of
5611 // values that the expression can take. Initially, the expression has a value
5612 // from StartRange and then is changed by Step up to MaxBECount times. Signed
5613 // argument defines if we treat Step as signed or unsigned.
5614 static ConstantRange getRangeForAffineARHelper(APInt Step,
5615                                                const ConstantRange &StartRange,
5616                                                const APInt &MaxBECount,
5617                                                unsigned BitWidth, bool Signed) {
5618   // If either Step or MaxBECount is 0, then the expression won't change, and we
5619   // just need to return the initial range.
5620   if (Step == 0 || MaxBECount == 0)
5621     return StartRange;
5622 
5623   // If we don't know anything about the initial value (i.e. StartRange is
5624   // FullRange), then we don't know anything about the final range either.
5625   // Return FullRange.
5626   if (StartRange.isFullSet())
5627     return ConstantRange(BitWidth, /* isFullSet = */ true);
5628 
5629   // If Step is signed and negative, then we use its absolute value, but we also
5630   // note that we're moving in the opposite direction.
5631   bool Descending = Signed && Step.isNegative();
5632 
5633   if (Signed)
5634     // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
5635     // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
5636     // This equations hold true due to the well-defined wrap-around behavior of
5637     // APInt.
5638     Step = Step.abs();
5639 
5640   // Check if Offset is more than full span of BitWidth. If it is, the
5641   // expression is guaranteed to overflow.
5642   if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
5643     return ConstantRange(BitWidth, /* isFullSet = */ true);
5644 
5645   // Offset is by how much the expression can change. Checks above guarantee no
5646   // overflow here.
5647   APInt Offset = Step * MaxBECount;
5648 
5649   // Minimum value of the final range will match the minimal value of StartRange
5650   // if the expression is increasing and will be decreased by Offset otherwise.
5651   // Maximum value of the final range will match the maximal value of StartRange
5652   // if the expression is decreasing and will be increased by Offset otherwise.
5653   APInt StartLower = StartRange.getLower();
5654   APInt StartUpper = StartRange.getUpper() - 1;
5655   APInt MovedBoundary = Descending ? (StartLower - std::move(Offset))
5656                                    : (StartUpper + std::move(Offset));
5657 
5658   // It's possible that the new minimum/maximum value will fall into the initial
5659   // range (due to wrap around). This means that the expression can take any
5660   // value in this bitwidth, and we have to return full range.
5661   if (StartRange.contains(MovedBoundary))
5662     return ConstantRange(BitWidth, /* isFullSet = */ true);
5663 
5664   APInt NewLower =
5665       Descending ? std::move(MovedBoundary) : std::move(StartLower);
5666   APInt NewUpper =
5667       Descending ? std::move(StartUpper) : std::move(MovedBoundary);
5668   NewUpper += 1;
5669 
5670   // If we end up with full range, return a proper full range.
5671   if (NewLower == NewUpper)
5672     return ConstantRange(BitWidth, /* isFullSet = */ true);
5673 
5674   // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
5675   return ConstantRange(std::move(NewLower), std::move(NewUpper));
5676 }
5677 
5678 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
5679                                                    const SCEV *Step,
5680                                                    const SCEV *MaxBECount,
5681                                                    unsigned BitWidth) {
5682   assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&
5683          getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
5684          "Precondition!");
5685 
5686   MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType());
5687   APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount);
5688 
5689   // First, consider step signed.
5690   ConstantRange StartSRange = getSignedRange(Start);
5691   ConstantRange StepSRange = getSignedRange(Step);
5692 
5693   // If Step can be both positive and negative, we need to find ranges for the
5694   // maximum absolute step values in both directions and union them.
5695   ConstantRange SR =
5696       getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange,
5697                                 MaxBECountValue, BitWidth, /* Signed = */ true);
5698   SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(),
5699                                               StartSRange, MaxBECountValue,
5700                                               BitWidth, /* Signed = */ true));
5701 
5702   // Next, consider step unsigned.
5703   ConstantRange UR = getRangeForAffineARHelper(
5704       getUnsignedRangeMax(Step), getUnsignedRange(Start),
5705       MaxBECountValue, BitWidth, /* Signed = */ false);
5706 
5707   // Finally, intersect signed and unsigned ranges.
5708   return SR.intersectWith(UR);
5709 }
5710 
5711 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
5712                                                     const SCEV *Step,
5713                                                     const SCEV *MaxBECount,
5714                                                     unsigned BitWidth) {
5715   //    RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
5716   // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
5717 
5718   struct SelectPattern {
5719     Value *Condition = nullptr;
5720     APInt TrueValue;
5721     APInt FalseValue;
5722 
5723     explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
5724                            const SCEV *S) {
5725       Optional<unsigned> CastOp;
5726       APInt Offset(BitWidth, 0);
5727 
5728       assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&
5729              "Should be!");
5730 
5731       // Peel off a constant offset:
5732       if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
5733         // In the future we could consider being smarter here and handle
5734         // {Start+Step,+,Step} too.
5735         if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
5736           return;
5737 
5738         Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
5739         S = SA->getOperand(1);
5740       }
5741 
5742       // Peel off a cast operation
5743       if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) {
5744         CastOp = SCast->getSCEVType();
5745         S = SCast->getOperand();
5746       }
5747 
5748       using namespace llvm::PatternMatch;
5749 
5750       auto *SU = dyn_cast<SCEVUnknown>(S);
5751       const APInt *TrueVal, *FalseVal;
5752       if (!SU ||
5753           !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
5754                                           m_APInt(FalseVal)))) {
5755         Condition = nullptr;
5756         return;
5757       }
5758 
5759       TrueValue = *TrueVal;
5760       FalseValue = *FalseVal;
5761 
5762       // Re-apply the cast we peeled off earlier
5763       if (CastOp.hasValue())
5764         switch (*CastOp) {
5765         default:
5766           llvm_unreachable("Unknown SCEV cast type!");
5767 
5768         case scTruncate:
5769           TrueValue = TrueValue.trunc(BitWidth);
5770           FalseValue = FalseValue.trunc(BitWidth);
5771           break;
5772         case scZeroExtend:
5773           TrueValue = TrueValue.zext(BitWidth);
5774           FalseValue = FalseValue.zext(BitWidth);
5775           break;
5776         case scSignExtend:
5777           TrueValue = TrueValue.sext(BitWidth);
5778           FalseValue = FalseValue.sext(BitWidth);
5779           break;
5780         }
5781 
5782       // Re-apply the constant offset we peeled off earlier
5783       TrueValue += Offset;
5784       FalseValue += Offset;
5785     }
5786 
5787     bool isRecognized() { return Condition != nullptr; }
5788   };
5789 
5790   SelectPattern StartPattern(*this, BitWidth, Start);
5791   if (!StartPattern.isRecognized())
5792     return ConstantRange(BitWidth, /* isFullSet = */ true);
5793 
5794   SelectPattern StepPattern(*this, BitWidth, Step);
5795   if (!StepPattern.isRecognized())
5796     return ConstantRange(BitWidth, /* isFullSet = */ true);
5797 
5798   if (StartPattern.Condition != StepPattern.Condition) {
5799     // We don't handle this case today; but we could, by considering four
5800     // possibilities below instead of two. I'm not sure if there are cases where
5801     // that will help over what getRange already does, though.
5802     return ConstantRange(BitWidth, /* isFullSet = */ true);
5803   }
5804 
5805   // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
5806   // construct arbitrary general SCEV expressions here.  This function is called
5807   // from deep in the call stack, and calling getSCEV (on a sext instruction,
5808   // say) can end up caching a suboptimal value.
5809 
5810   // FIXME: without the explicit `this` receiver below, MSVC errors out with
5811   // C2352 and C2512 (otherwise it isn't needed).
5812 
5813   const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
5814   const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
5815   const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
5816   const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
5817 
5818   ConstantRange TrueRange =
5819       this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
5820   ConstantRange FalseRange =
5821       this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
5822 
5823   return TrueRange.unionWith(FalseRange);
5824 }
5825 
5826 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
5827   if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
5828   const BinaryOperator *BinOp = cast<BinaryOperator>(V);
5829 
5830   // Return early if there are no flags to propagate to the SCEV.
5831   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5832   if (BinOp->hasNoUnsignedWrap())
5833     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
5834   if (BinOp->hasNoSignedWrap())
5835     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
5836   if (Flags == SCEV::FlagAnyWrap)
5837     return SCEV::FlagAnyWrap;
5838 
5839   return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
5840 }
5841 
5842 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
5843   // Here we check that I is in the header of the innermost loop containing I,
5844   // since we only deal with instructions in the loop header. The actual loop we
5845   // need to check later will come from an add recurrence, but getting that
5846   // requires computing the SCEV of the operands, which can be expensive. This
5847   // check we can do cheaply to rule out some cases early.
5848   Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent());
5849   if (InnermostContainingLoop == nullptr ||
5850       InnermostContainingLoop->getHeader() != I->getParent())
5851     return false;
5852 
5853   // Only proceed if we can prove that I does not yield poison.
5854   if (!programUndefinedIfFullPoison(I))
5855     return false;
5856 
5857   // At this point we know that if I is executed, then it does not wrap
5858   // according to at least one of NSW or NUW. If I is not executed, then we do
5859   // not know if the calculation that I represents would wrap. Multiple
5860   // instructions can map to the same SCEV. If we apply NSW or NUW from I to
5861   // the SCEV, we must guarantee no wrapping for that SCEV also when it is
5862   // derived from other instructions that map to the same SCEV. We cannot make
5863   // that guarantee for cases where I is not executed. So we need to find the
5864   // loop that I is considered in relation to and prove that I is executed for
5865   // every iteration of that loop. That implies that the value that I
5866   // calculates does not wrap anywhere in the loop, so then we can apply the
5867   // flags to the SCEV.
5868   //
5869   // We check isLoopInvariant to disambiguate in case we are adding recurrences
5870   // from different loops, so that we know which loop to prove that I is
5871   // executed in.
5872   for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) {
5873     // I could be an extractvalue from a call to an overflow intrinsic.
5874     // TODO: We can do better here in some cases.
5875     if (!isSCEVable(I->getOperand(OpIndex)->getType()))
5876       return false;
5877     const SCEV *Op = getSCEV(I->getOperand(OpIndex));
5878     if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
5879       bool AllOtherOpsLoopInvariant = true;
5880       for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands();
5881            ++OtherOpIndex) {
5882         if (OtherOpIndex != OpIndex) {
5883           const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex));
5884           if (!isLoopInvariant(OtherOp, AddRec->getLoop())) {
5885             AllOtherOpsLoopInvariant = false;
5886             break;
5887           }
5888         }
5889       }
5890       if (AllOtherOpsLoopInvariant &&
5891           isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop()))
5892         return true;
5893     }
5894   }
5895   return false;
5896 }
5897 
5898 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
5899   // If we know that \c I can never be poison period, then that's enough.
5900   if (isSCEVExprNeverPoison(I))
5901     return true;
5902 
5903   // For an add recurrence specifically, we assume that infinite loops without
5904   // side effects are undefined behavior, and then reason as follows:
5905   //
5906   // If the add recurrence is poison in any iteration, it is poison on all
5907   // future iterations (since incrementing poison yields poison). If the result
5908   // of the add recurrence is fed into the loop latch condition and the loop
5909   // does not contain any throws or exiting blocks other than the latch, we now
5910   // have the ability to "choose" whether the backedge is taken or not (by
5911   // choosing a sufficiently evil value for the poison feeding into the branch)
5912   // for every iteration including and after the one in which \p I first became
5913   // poison.  There are two possibilities (let's call the iteration in which \p
5914   // I first became poison as K):
5915   //
5916   //  1. In the set of iterations including and after K, the loop body executes
5917   //     no side effects.  In this case executing the backege an infinte number
5918   //     of times will yield undefined behavior.
5919   //
5920   //  2. In the set of iterations including and after K, the loop body executes
5921   //     at least one side effect.  In this case, that specific instance of side
5922   //     effect is control dependent on poison, which also yields undefined
5923   //     behavior.
5924 
5925   auto *ExitingBB = L->getExitingBlock();
5926   auto *LatchBB = L->getLoopLatch();
5927   if (!ExitingBB || !LatchBB || ExitingBB != LatchBB)
5928     return false;
5929 
5930   SmallPtrSet<const Instruction *, 16> Pushed;
5931   SmallVector<const Instruction *, 8> PoisonStack;
5932 
5933   // We start by assuming \c I, the post-inc add recurrence, is poison.  Only
5934   // things that are known to be fully poison under that assumption go on the
5935   // PoisonStack.
5936   Pushed.insert(I);
5937   PoisonStack.push_back(I);
5938 
5939   bool LatchControlDependentOnPoison = false;
5940   while (!PoisonStack.empty() && !LatchControlDependentOnPoison) {
5941     const Instruction *Poison = PoisonStack.pop_back_val();
5942 
5943     for (auto *PoisonUser : Poison->users()) {
5944       if (propagatesFullPoison(cast<Instruction>(PoisonUser))) {
5945         if (Pushed.insert(cast<Instruction>(PoisonUser)).second)
5946           PoisonStack.push_back(cast<Instruction>(PoisonUser));
5947       } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) {
5948         assert(BI->isConditional() && "Only possibility!");
5949         if (BI->getParent() == LatchBB) {
5950           LatchControlDependentOnPoison = true;
5951           break;
5952         }
5953       }
5954     }
5955   }
5956 
5957   return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L);
5958 }
5959 
5960 ScalarEvolution::LoopProperties
5961 ScalarEvolution::getLoopProperties(const Loop *L) {
5962   using LoopProperties = ScalarEvolution::LoopProperties;
5963 
5964   auto Itr = LoopPropertiesCache.find(L);
5965   if (Itr == LoopPropertiesCache.end()) {
5966     auto HasSideEffects = [](Instruction *I) {
5967       if (auto *SI = dyn_cast<StoreInst>(I))
5968         return !SI->isSimple();
5969 
5970       return I->mayHaveSideEffects();
5971     };
5972 
5973     LoopProperties LP = {/* HasNoAbnormalExits */ true,
5974                          /*HasNoSideEffects*/ true};
5975 
5976     for (auto *BB : L->getBlocks())
5977       for (auto &I : *BB) {
5978         if (!isGuaranteedToTransferExecutionToSuccessor(&I))
5979           LP.HasNoAbnormalExits = false;
5980         if (HasSideEffects(&I))
5981           LP.HasNoSideEffects = false;
5982         if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
5983           break; // We're already as pessimistic as we can get.
5984       }
5985 
5986     auto InsertPair = LoopPropertiesCache.insert({L, LP});
5987     assert(InsertPair.second && "We just checked!");
5988     Itr = InsertPair.first;
5989   }
5990 
5991   return Itr->second;
5992 }
5993 
5994 const SCEV *ScalarEvolution::createSCEV(Value *V) {
5995   if (!isSCEVable(V->getType()))
5996     return getUnknown(V);
5997 
5998   if (Instruction *I = dyn_cast<Instruction>(V)) {
5999     // Don't attempt to analyze instructions in blocks that aren't
6000     // reachable. Such instructions don't matter, and they aren't required
6001     // to obey basic rules for definitions dominating uses which this
6002     // analysis depends on.
6003     if (!DT.isReachableFromEntry(I->getParent()))
6004       return getUnknown(V);
6005   } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
6006     return getConstant(CI);
6007   else if (isa<ConstantPointerNull>(V))
6008     return getZero(V->getType());
6009   else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
6010     return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee());
6011   else if (!isa<ConstantExpr>(V))
6012     return getUnknown(V);
6013 
6014   Operator *U = cast<Operator>(V);
6015   if (auto BO = MatchBinaryOp(U, DT)) {
6016     switch (BO->Opcode) {
6017     case Instruction::Add: {
6018       // The simple thing to do would be to just call getSCEV on both operands
6019       // and call getAddExpr with the result. However if we're looking at a
6020       // bunch of things all added together, this can be quite inefficient,
6021       // because it leads to N-1 getAddExpr calls for N ultimate operands.
6022       // Instead, gather up all the operands and make a single getAddExpr call.
6023       // LLVM IR canonical form means we need only traverse the left operands.
6024       SmallVector<const SCEV *, 4> AddOps;
6025       do {
6026         if (BO->Op) {
6027           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
6028             AddOps.push_back(OpSCEV);
6029             break;
6030           }
6031 
6032           // If a NUW or NSW flag can be applied to the SCEV for this
6033           // addition, then compute the SCEV for this addition by itself
6034           // with a separate call to getAddExpr. We need to do that
6035           // instead of pushing the operands of the addition onto AddOps,
6036           // since the flags are only known to apply to this particular
6037           // addition - they may not apply to other additions that can be
6038           // formed with operands from AddOps.
6039           const SCEV *RHS = getSCEV(BO->RHS);
6040           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
6041           if (Flags != SCEV::FlagAnyWrap) {
6042             const SCEV *LHS = getSCEV(BO->LHS);
6043             if (BO->Opcode == Instruction::Sub)
6044               AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
6045             else
6046               AddOps.push_back(getAddExpr(LHS, RHS, Flags));
6047             break;
6048           }
6049         }
6050 
6051         if (BO->Opcode == Instruction::Sub)
6052           AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
6053         else
6054           AddOps.push_back(getSCEV(BO->RHS));
6055 
6056         auto NewBO = MatchBinaryOp(BO->LHS, DT);
6057         if (!NewBO || (NewBO->Opcode != Instruction::Add &&
6058                        NewBO->Opcode != Instruction::Sub)) {
6059           AddOps.push_back(getSCEV(BO->LHS));
6060           break;
6061         }
6062         BO = NewBO;
6063       } while (true);
6064 
6065       return getAddExpr(AddOps);
6066     }
6067 
6068     case Instruction::Mul: {
6069       SmallVector<const SCEV *, 4> MulOps;
6070       do {
6071         if (BO->Op) {
6072           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
6073             MulOps.push_back(OpSCEV);
6074             break;
6075           }
6076 
6077           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
6078           if (Flags != SCEV::FlagAnyWrap) {
6079             MulOps.push_back(
6080                 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags));
6081             break;
6082           }
6083         }
6084 
6085         MulOps.push_back(getSCEV(BO->RHS));
6086         auto NewBO = MatchBinaryOp(BO->LHS, DT);
6087         if (!NewBO || NewBO->Opcode != Instruction::Mul) {
6088           MulOps.push_back(getSCEV(BO->LHS));
6089           break;
6090         }
6091         BO = NewBO;
6092       } while (true);
6093 
6094       return getMulExpr(MulOps);
6095     }
6096     case Instruction::UDiv:
6097       return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
6098     case Instruction::URem:
6099       return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
6100     case Instruction::Sub: {
6101       SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
6102       if (BO->Op)
6103         Flags = getNoWrapFlagsFromUB(BO->Op);
6104       return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags);
6105     }
6106     case Instruction::And:
6107       // For an expression like x&255 that merely masks off the high bits,
6108       // use zext(trunc(x)) as the SCEV expression.
6109       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6110         if (CI->isZero())
6111           return getSCEV(BO->RHS);
6112         if (CI->isMinusOne())
6113           return getSCEV(BO->LHS);
6114         const APInt &A = CI->getValue();
6115 
6116         // Instcombine's ShrinkDemandedConstant may strip bits out of
6117         // constants, obscuring what would otherwise be a low-bits mask.
6118         // Use computeKnownBits to compute what ShrinkDemandedConstant
6119         // knew about to reconstruct a low-bits mask value.
6120         unsigned LZ = A.countLeadingZeros();
6121         unsigned TZ = A.countTrailingZeros();
6122         unsigned BitWidth = A.getBitWidth();
6123         KnownBits Known(BitWidth);
6124         computeKnownBits(BO->LHS, Known, getDataLayout(),
6125                          0, &AC, nullptr, &DT);
6126 
6127         APInt EffectiveMask =
6128             APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
6129         if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
6130           const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
6131           const SCEV *LHS = getSCEV(BO->LHS);
6132           const SCEV *ShiftedLHS = nullptr;
6133           if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
6134             if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
6135               // For an expression like (x * 8) & 8, simplify the multiply.
6136               unsigned MulZeros = OpC->getAPInt().countTrailingZeros();
6137               unsigned GCD = std::min(MulZeros, TZ);
6138               APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
6139               SmallVector<const SCEV*, 4> MulOps;
6140               MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD)));
6141               MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end());
6142               auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
6143               ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
6144             }
6145           }
6146           if (!ShiftedLHS)
6147             ShiftedLHS = getUDivExpr(LHS, MulCount);
6148           return getMulExpr(
6149               getZeroExtendExpr(
6150                   getTruncateExpr(ShiftedLHS,
6151                       IntegerType::get(getContext(), BitWidth - LZ - TZ)),
6152                   BO->LHS->getType()),
6153               MulCount);
6154         }
6155       }
6156       break;
6157 
6158     case Instruction::Or:
6159       // If the RHS of the Or is a constant, we may have something like:
6160       // X*4+1 which got turned into X*4|1.  Handle this as an Add so loop
6161       // optimizations will transparently handle this case.
6162       //
6163       // In order for this transformation to be safe, the LHS must be of the
6164       // form X*(2^n) and the Or constant must be less than 2^n.
6165       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6166         const SCEV *LHS = getSCEV(BO->LHS);
6167         const APInt &CIVal = CI->getValue();
6168         if (GetMinTrailingZeros(LHS) >=
6169             (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
6170           // Build a plain add SCEV.
6171           const SCEV *S = getAddExpr(LHS, getSCEV(CI));
6172           // If the LHS of the add was an addrec and it has no-wrap flags,
6173           // transfer the no-wrap flags, since an or won't introduce a wrap.
6174           if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
6175             const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
6176             const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags(
6177                 OldAR->getNoWrapFlags());
6178           }
6179           return S;
6180         }
6181       }
6182       break;
6183 
6184     case Instruction::Xor:
6185       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6186         // If the RHS of xor is -1, then this is a not operation.
6187         if (CI->isMinusOne())
6188           return getNotSCEV(getSCEV(BO->LHS));
6189 
6190         // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
6191         // This is a variant of the check for xor with -1, and it handles
6192         // the case where instcombine has trimmed non-demanded bits out
6193         // of an xor with -1.
6194         if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
6195           if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
6196             if (LBO->getOpcode() == Instruction::And &&
6197                 LCI->getValue() == CI->getValue())
6198               if (const SCEVZeroExtendExpr *Z =
6199                       dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
6200                 Type *UTy = BO->LHS->getType();
6201                 const SCEV *Z0 = Z->getOperand();
6202                 Type *Z0Ty = Z0->getType();
6203                 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
6204 
6205                 // If C is a low-bits mask, the zero extend is serving to
6206                 // mask off the high bits. Complement the operand and
6207                 // re-apply the zext.
6208                 if (CI->getValue().isMask(Z0TySize))
6209                   return getZeroExtendExpr(getNotSCEV(Z0), UTy);
6210 
6211                 // If C is a single bit, it may be in the sign-bit position
6212                 // before the zero-extend. In this case, represent the xor
6213                 // using an add, which is equivalent, and re-apply the zext.
6214                 APInt Trunc = CI->getValue().trunc(Z0TySize);
6215                 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
6216                     Trunc.isSignMask())
6217                   return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
6218                                            UTy);
6219               }
6220       }
6221       break;
6222 
6223   case Instruction::Shl:
6224     // Turn shift left of a constant amount into a multiply.
6225     if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
6226       uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
6227 
6228       // If the shift count is not less than the bitwidth, the result of
6229       // the shift is undefined. Don't try to analyze it, because the
6230       // resolution chosen here may differ from the resolution chosen in
6231       // other parts of the compiler.
6232       if (SA->getValue().uge(BitWidth))
6233         break;
6234 
6235       // It is currently not resolved how to interpret NSW for left
6236       // shift by BitWidth - 1, so we avoid applying flags in that
6237       // case. Remove this check (or this comment) once the situation
6238       // is resolved. See
6239       // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html
6240       // and http://reviews.llvm.org/D8890 .
6241       auto Flags = SCEV::FlagAnyWrap;
6242       if (BO->Op && SA->getValue().ult(BitWidth - 1))
6243         Flags = getNoWrapFlagsFromUB(BO->Op);
6244 
6245       Constant *X = ConstantInt::get(getContext(),
6246         APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
6247       return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags);
6248     }
6249     break;
6250 
6251     case Instruction::AShr: {
6252       // AShr X, C, where C is a constant.
6253       ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
6254       if (!CI)
6255         break;
6256 
6257       Type *OuterTy = BO->LHS->getType();
6258       uint64_t BitWidth = getTypeSizeInBits(OuterTy);
6259       // If the shift count is not less than the bitwidth, the result of
6260       // the shift is undefined. Don't try to analyze it, because the
6261       // resolution chosen here may differ from the resolution chosen in
6262       // other parts of the compiler.
6263       if (CI->getValue().uge(BitWidth))
6264         break;
6265 
6266       if (CI->isZero())
6267         return getSCEV(BO->LHS); // shift by zero --> noop
6268 
6269       uint64_t AShrAmt = CI->getZExtValue();
6270       Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
6271 
6272       Operator *L = dyn_cast<Operator>(BO->LHS);
6273       if (L && L->getOpcode() == Instruction::Shl) {
6274         // X = Shl A, n
6275         // Y = AShr X, m
6276         // Both n and m are constant.
6277 
6278         const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
6279         if (L->getOperand(1) == BO->RHS)
6280           // For a two-shift sext-inreg, i.e. n = m,
6281           // use sext(trunc(x)) as the SCEV expression.
6282           return getSignExtendExpr(
6283               getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy);
6284 
6285         ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
6286         if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) {
6287           uint64_t ShlAmt = ShlAmtCI->getZExtValue();
6288           if (ShlAmt > AShrAmt) {
6289             // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
6290             // expression. We already checked that ShlAmt < BitWidth, so
6291             // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
6292             // ShlAmt - AShrAmt < Amt.
6293             APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
6294                                             ShlAmt - AShrAmt);
6295             return getSignExtendExpr(
6296                 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy),
6297                 getConstant(Mul)), OuterTy);
6298           }
6299         }
6300       }
6301       break;
6302     }
6303     }
6304   }
6305 
6306   switch (U->getOpcode()) {
6307   case Instruction::Trunc:
6308     return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
6309 
6310   case Instruction::ZExt:
6311     return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
6312 
6313   case Instruction::SExt:
6314     if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) {
6315       // The NSW flag of a subtract does not always survive the conversion to
6316       // A + (-1)*B.  By pushing sign extension onto its operands we are much
6317       // more likely to preserve NSW and allow later AddRec optimisations.
6318       //
6319       // NOTE: This is effectively duplicating this logic from getSignExtend:
6320       //   sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
6321       // but by that point the NSW information has potentially been lost.
6322       if (BO->Opcode == Instruction::Sub && BO->IsNSW) {
6323         Type *Ty = U->getType();
6324         auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty);
6325         auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty);
6326         return getMinusSCEV(V1, V2, SCEV::FlagNSW);
6327       }
6328     }
6329     return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
6330 
6331   case Instruction::BitCast:
6332     // BitCasts are no-op casts so we just eliminate the cast.
6333     if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
6334       return getSCEV(U->getOperand(0));
6335     break;
6336 
6337   // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
6338   // lead to pointer expressions which cannot safely be expanded to GEPs,
6339   // because ScalarEvolution doesn't respect the GEP aliasing rules when
6340   // simplifying integer expressions.
6341 
6342   case Instruction::GetElementPtr:
6343     return createNodeForGEP(cast<GEPOperator>(U));
6344 
6345   case Instruction::PHI:
6346     return createNodeForPHI(cast<PHINode>(U));
6347 
6348   case Instruction::Select:
6349     // U can also be a select constant expr, which let fall through.  Since
6350     // createNodeForSelect only works for a condition that is an `ICmpInst`, and
6351     // constant expressions cannot have instructions as operands, we'd have
6352     // returned getUnknown for a select constant expressions anyway.
6353     if (isa<Instruction>(U))
6354       return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0),
6355                                       U->getOperand(1), U->getOperand(2));
6356     break;
6357 
6358   case Instruction::Call:
6359   case Instruction::Invoke:
6360     if (Value *RV = CallSite(U).getReturnedArgOperand())
6361       return getSCEV(RV);
6362     break;
6363   }
6364 
6365   return getUnknown(V);
6366 }
6367 
6368 //===----------------------------------------------------------------------===//
6369 //                   Iteration Count Computation Code
6370 //
6371 
6372 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
6373   if (!ExitCount)
6374     return 0;
6375 
6376   ConstantInt *ExitConst = ExitCount->getValue();
6377 
6378   // Guard against huge trip counts.
6379   if (ExitConst->getValue().getActiveBits() > 32)
6380     return 0;
6381 
6382   // In case of integer overflow, this returns 0, which is correct.
6383   return ((unsigned)ExitConst->getZExtValue()) + 1;
6384 }
6385 
6386 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) {
6387   if (BasicBlock *ExitingBB = L->getExitingBlock())
6388     return getSmallConstantTripCount(L, ExitingBB);
6389 
6390   // No trip count information for multiple exits.
6391   return 0;
6392 }
6393 
6394 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L,
6395                                                     BasicBlock *ExitingBlock) {
6396   assert(ExitingBlock && "Must pass a non-null exiting block!");
6397   assert(L->isLoopExiting(ExitingBlock) &&
6398          "Exiting block must actually branch out of the loop!");
6399   const SCEVConstant *ExitCount =
6400       dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
6401   return getConstantTripCount(ExitCount);
6402 }
6403 
6404 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) {
6405   const auto *MaxExitCount =
6406       dyn_cast<SCEVConstant>(getMaxBackedgeTakenCount(L));
6407   return getConstantTripCount(MaxExitCount);
6408 }
6409 
6410 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) {
6411   if (BasicBlock *ExitingBB = L->getExitingBlock())
6412     return getSmallConstantTripMultiple(L, ExitingBB);
6413 
6414   // No trip multiple information for multiple exits.
6415   return 0;
6416 }
6417 
6418 /// Returns the largest constant divisor of the trip count of this loop as a
6419 /// normal unsigned value, if possible. This means that the actual trip count is
6420 /// always a multiple of the returned value (don't forget the trip count could
6421 /// very well be zero as well!).
6422 ///
6423 /// Returns 1 if the trip count is unknown or not guaranteed to be the
6424 /// multiple of a constant (which is also the case if the trip count is simply
6425 /// constant, use getSmallConstantTripCount for that case), Will also return 1
6426 /// if the trip count is very large (>= 2^32).
6427 ///
6428 /// As explained in the comments for getSmallConstantTripCount, this assumes
6429 /// that control exits the loop via ExitingBlock.
6430 unsigned
6431 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
6432                                               BasicBlock *ExitingBlock) {
6433   assert(ExitingBlock && "Must pass a non-null exiting block!");
6434   assert(L->isLoopExiting(ExitingBlock) &&
6435          "Exiting block must actually branch out of the loop!");
6436   const SCEV *ExitCount = getExitCount(L, ExitingBlock);
6437   if (ExitCount == getCouldNotCompute())
6438     return 1;
6439 
6440   // Get the trip count from the BE count by adding 1.
6441   const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType()));
6442 
6443   const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr);
6444   if (!TC)
6445     // Attempt to factor more general cases. Returns the greatest power of
6446     // two divisor. If overflow happens, the trip count expression is still
6447     // divisible by the greatest power of 2 divisor returned.
6448     return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr));
6449 
6450   ConstantInt *Result = TC->getValue();
6451 
6452   // Guard against huge trip counts (this requires checking
6453   // for zero to handle the case where the trip count == -1 and the
6454   // addition wraps).
6455   if (!Result || Result->getValue().getActiveBits() > 32 ||
6456       Result->getValue().getActiveBits() == 0)
6457     return 1;
6458 
6459   return (unsigned)Result->getZExtValue();
6460 }
6461 
6462 /// Get the expression for the number of loop iterations for which this loop is
6463 /// guaranteed not to exit via ExitingBlock. Otherwise return
6464 /// SCEVCouldNotCompute.
6465 const SCEV *ScalarEvolution::getExitCount(const Loop *L,
6466                                           BasicBlock *ExitingBlock) {
6467   return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
6468 }
6469 
6470 const SCEV *
6471 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
6472                                                  SCEVUnionPredicate &Preds) {
6473   return getPredicatedBackedgeTakenInfo(L).getExact(this, &Preds);
6474 }
6475 
6476 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
6477   return getBackedgeTakenInfo(L).getExact(this);
6478 }
6479 
6480 /// Similar to getBackedgeTakenCount, except return the least SCEV value that is
6481 /// known never to be less than the actual backedge taken count.
6482 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
6483   return getBackedgeTakenInfo(L).getMax(this);
6484 }
6485 
6486 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) {
6487   return getBackedgeTakenInfo(L).isMaxOrZero(this);
6488 }
6489 
6490 /// Push PHI nodes in the header of the given loop onto the given Worklist.
6491 static void
6492 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
6493   BasicBlock *Header = L->getHeader();
6494 
6495   // Push all Loop-header PHIs onto the Worklist stack.
6496   for (PHINode &PN : Header->phis())
6497     Worklist.push_back(&PN);
6498 }
6499 
6500 const ScalarEvolution::BackedgeTakenInfo &
6501 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
6502   auto &BTI = getBackedgeTakenInfo(L);
6503   if (BTI.hasFullInfo())
6504     return BTI;
6505 
6506   auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
6507 
6508   if (!Pair.second)
6509     return Pair.first->second;
6510 
6511   BackedgeTakenInfo Result =
6512       computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
6513 
6514   return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
6515 }
6516 
6517 const ScalarEvolution::BackedgeTakenInfo &
6518 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
6519   // Initially insert an invalid entry for this loop. If the insertion
6520   // succeeds, proceed to actually compute a backedge-taken count and
6521   // update the value. The temporary CouldNotCompute value tells SCEV
6522   // code elsewhere that it shouldn't attempt to request a new
6523   // backedge-taken count, which could result in infinite recursion.
6524   std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
6525       BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
6526   if (!Pair.second)
6527     return Pair.first->second;
6528 
6529   // computeBackedgeTakenCount may allocate memory for its result. Inserting it
6530   // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
6531   // must be cleared in this scope.
6532   BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
6533 
6534   if (Result.getExact(this) != getCouldNotCompute()) {
6535     assert(isLoopInvariant(Result.getExact(this), L) &&
6536            isLoopInvariant(Result.getMax(this), L) &&
6537            "Computed backedge-taken count isn't loop invariant for loop!");
6538     ++NumTripCountsComputed;
6539   }
6540   else if (Result.getMax(this) == getCouldNotCompute() &&
6541            isa<PHINode>(L->getHeader()->begin())) {
6542     // Only count loops that have phi nodes as not being computable.
6543     ++NumTripCountsNotComputed;
6544   }
6545 
6546   // Now that we know more about the trip count for this loop, forget any
6547   // existing SCEV values for PHI nodes in this loop since they are only
6548   // conservative estimates made without the benefit of trip count
6549   // information. This is similar to the code in forgetLoop, except that
6550   // it handles SCEVUnknown PHI nodes specially.
6551   if (Result.hasAnyInfo()) {
6552     SmallVector<Instruction *, 16> Worklist;
6553     PushLoopPHIs(L, Worklist);
6554 
6555     SmallPtrSet<Instruction *, 8> Discovered;
6556     while (!Worklist.empty()) {
6557       Instruction *I = Worklist.pop_back_val();
6558 
6559       ValueExprMapType::iterator It =
6560         ValueExprMap.find_as(static_cast<Value *>(I));
6561       if (It != ValueExprMap.end()) {
6562         const SCEV *Old = It->second;
6563 
6564         // SCEVUnknown for a PHI either means that it has an unrecognized
6565         // structure, or it's a PHI that's in the progress of being computed
6566         // by createNodeForPHI.  In the former case, additional loop trip
6567         // count information isn't going to change anything. In the later
6568         // case, createNodeForPHI will perform the necessary updates on its
6569         // own when it gets to that point.
6570         if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
6571           eraseValueFromMap(It->first);
6572           forgetMemoizedResults(Old);
6573         }
6574         if (PHINode *PN = dyn_cast<PHINode>(I))
6575           ConstantEvolutionLoopExitValue.erase(PN);
6576       }
6577 
6578       // Since we don't need to invalidate anything for correctness and we're
6579       // only invalidating to make SCEV's results more precise, we get to stop
6580       // early to avoid invalidating too much.  This is especially important in
6581       // cases like:
6582       //
6583       //   %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node
6584       // loop0:
6585       //   %pn0 = phi
6586       //   ...
6587       // loop1:
6588       //   %pn1 = phi
6589       //   ...
6590       //
6591       // where both loop0 and loop1's backedge taken count uses the SCEV
6592       // expression for %v.  If we don't have the early stop below then in cases
6593       // like the above, getBackedgeTakenInfo(loop1) will clear out the trip
6594       // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip
6595       // count for loop1, effectively nullifying SCEV's trip count cache.
6596       for (auto *U : I->users())
6597         if (auto *I = dyn_cast<Instruction>(U)) {
6598           auto *LoopForUser = LI.getLoopFor(I->getParent());
6599           if (LoopForUser && L->contains(LoopForUser) &&
6600               Discovered.insert(I).second)
6601             Worklist.push_back(I);
6602         }
6603     }
6604   }
6605 
6606   // Re-lookup the insert position, since the call to
6607   // computeBackedgeTakenCount above could result in a
6608   // recusive call to getBackedgeTakenInfo (on a different
6609   // loop), which would invalidate the iterator computed
6610   // earlier.
6611   return BackedgeTakenCounts.find(L)->second = std::move(Result);
6612 }
6613 
6614 void ScalarEvolution::forgetLoop(const Loop *L) {
6615   // Drop any stored trip count value.
6616   auto RemoveLoopFromBackedgeMap =
6617       [](DenseMap<const Loop *, BackedgeTakenInfo> &Map, const Loop *L) {
6618         auto BTCPos = Map.find(L);
6619         if (BTCPos != Map.end()) {
6620           BTCPos->second.clear();
6621           Map.erase(BTCPos);
6622         }
6623       };
6624 
6625   SmallVector<const Loop *, 16> LoopWorklist(1, L);
6626   SmallVector<Instruction *, 32> Worklist;
6627   SmallPtrSet<Instruction *, 16> Visited;
6628 
6629   // Iterate over all the loops and sub-loops to drop SCEV information.
6630   while (!LoopWorklist.empty()) {
6631     auto *CurrL = LoopWorklist.pop_back_val();
6632 
6633     RemoveLoopFromBackedgeMap(BackedgeTakenCounts, CurrL);
6634     RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts, CurrL);
6635 
6636     // Drop information about predicated SCEV rewrites for this loop.
6637     for (auto I = PredicatedSCEVRewrites.begin();
6638          I != PredicatedSCEVRewrites.end();) {
6639       std::pair<const SCEV *, const Loop *> Entry = I->first;
6640       if (Entry.second == CurrL)
6641         PredicatedSCEVRewrites.erase(I++);
6642       else
6643         ++I;
6644     }
6645 
6646     auto LoopUsersItr = LoopUsers.find(CurrL);
6647     if (LoopUsersItr != LoopUsers.end()) {
6648       for (auto *S : LoopUsersItr->second)
6649         forgetMemoizedResults(S);
6650       LoopUsers.erase(LoopUsersItr);
6651     }
6652 
6653     // Drop information about expressions based on loop-header PHIs.
6654     PushLoopPHIs(CurrL, Worklist);
6655 
6656     while (!Worklist.empty()) {
6657       Instruction *I = Worklist.pop_back_val();
6658       if (!Visited.insert(I).second)
6659         continue;
6660 
6661       ValueExprMapType::iterator It =
6662           ValueExprMap.find_as(static_cast<Value *>(I));
6663       if (It != ValueExprMap.end()) {
6664         eraseValueFromMap(It->first);
6665         forgetMemoizedResults(It->second);
6666         if (PHINode *PN = dyn_cast<PHINode>(I))
6667           ConstantEvolutionLoopExitValue.erase(PN);
6668       }
6669 
6670       PushDefUseChildren(I, Worklist);
6671     }
6672 
6673     LoopPropertiesCache.erase(CurrL);
6674     // Forget all contained loops too, to avoid dangling entries in the
6675     // ValuesAtScopes map.
6676     LoopWorklist.append(CurrL->begin(), CurrL->end());
6677   }
6678 }
6679 
6680 void ScalarEvolution::forgetValue(Value *V) {
6681   Instruction *I = dyn_cast<Instruction>(V);
6682   if (!I) return;
6683 
6684   // Drop information about expressions based on loop-header PHIs.
6685   SmallVector<Instruction *, 16> Worklist;
6686   Worklist.push_back(I);
6687 
6688   SmallPtrSet<Instruction *, 8> Visited;
6689   while (!Worklist.empty()) {
6690     I = Worklist.pop_back_val();
6691     if (!Visited.insert(I).second)
6692       continue;
6693 
6694     ValueExprMapType::iterator It =
6695       ValueExprMap.find_as(static_cast<Value *>(I));
6696     if (It != ValueExprMap.end()) {
6697       eraseValueFromMap(It->first);
6698       forgetMemoizedResults(It->second);
6699       if (PHINode *PN = dyn_cast<PHINode>(I))
6700         ConstantEvolutionLoopExitValue.erase(PN);
6701     }
6702 
6703     PushDefUseChildren(I, Worklist);
6704   }
6705 }
6706 
6707 /// Get the exact loop backedge taken count considering all loop exits. A
6708 /// computable result can only be returned for loops with a single exit.
6709 /// Returning the minimum taken count among all exits is incorrect because one
6710 /// of the loop's exit limit's may have been skipped. howFarToZero assumes that
6711 /// the limit of each loop test is never skipped. This is a valid assumption as
6712 /// long as the loop exits via that test. For precise results, it is the
6713 /// caller's responsibility to specify the relevant loop exit using
6714 /// getExact(ExitingBlock, SE).
6715 const SCEV *
6716 ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE,
6717                                              SCEVUnionPredicate *Preds) const {
6718   // If any exits were not computable, the loop is not computable.
6719   if (!isComplete() || ExitNotTaken.empty())
6720     return SE->getCouldNotCompute();
6721 
6722   const SCEV *BECount = nullptr;
6723   for (auto &ENT : ExitNotTaken) {
6724     assert(ENT.ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV");
6725 
6726     if (!BECount)
6727       BECount = ENT.ExactNotTaken;
6728     else if (BECount != ENT.ExactNotTaken)
6729       return SE->getCouldNotCompute();
6730     if (Preds && !ENT.hasAlwaysTruePredicate())
6731       Preds->add(ENT.Predicate.get());
6732 
6733     assert((Preds || ENT.hasAlwaysTruePredicate()) &&
6734            "Predicate should be always true!");
6735   }
6736 
6737   assert(BECount && "Invalid not taken count for loop exit");
6738   return BECount;
6739 }
6740 
6741 /// Get the exact not taken count for this loop exit.
6742 const SCEV *
6743 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock,
6744                                              ScalarEvolution *SE) const {
6745   for (auto &ENT : ExitNotTaken)
6746     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
6747       return ENT.ExactNotTaken;
6748 
6749   return SE->getCouldNotCompute();
6750 }
6751 
6752 /// getMax - Get the max backedge taken count for the loop.
6753 const SCEV *
6754 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const {
6755   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
6756     return !ENT.hasAlwaysTruePredicate();
6757   };
6758 
6759   if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax())
6760     return SE->getCouldNotCompute();
6761 
6762   assert((isa<SCEVCouldNotCompute>(getMax()) || isa<SCEVConstant>(getMax())) &&
6763          "No point in having a non-constant max backedge taken count!");
6764   return getMax();
6765 }
6766 
6767 bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const {
6768   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
6769     return !ENT.hasAlwaysTruePredicate();
6770   };
6771   return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
6772 }
6773 
6774 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S,
6775                                                     ScalarEvolution *SE) const {
6776   if (getMax() && getMax() != SE->getCouldNotCompute() &&
6777       SE->hasOperand(getMax(), S))
6778     return true;
6779 
6780   for (auto &ENT : ExitNotTaken)
6781     if (ENT.ExactNotTaken != SE->getCouldNotCompute() &&
6782         SE->hasOperand(ENT.ExactNotTaken, S))
6783       return true;
6784 
6785   return false;
6786 }
6787 
6788 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E)
6789     : ExactNotTaken(E), MaxNotTaken(E) {
6790   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6791           isa<SCEVConstant>(MaxNotTaken)) &&
6792          "No point in having a non-constant max backedge taken count!");
6793 }
6794 
6795 ScalarEvolution::ExitLimit::ExitLimit(
6796     const SCEV *E, const SCEV *M, bool MaxOrZero,
6797     ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList)
6798     : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) {
6799   assert((isa<SCEVCouldNotCompute>(ExactNotTaken) ||
6800           !isa<SCEVCouldNotCompute>(MaxNotTaken)) &&
6801          "Exact is not allowed to be less precise than Max");
6802   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6803           isa<SCEVConstant>(MaxNotTaken)) &&
6804          "No point in having a non-constant max backedge taken count!");
6805   for (auto *PredSet : PredSetList)
6806     for (auto *P : *PredSet)
6807       addPredicate(P);
6808 }
6809 
6810 ScalarEvolution::ExitLimit::ExitLimit(
6811     const SCEV *E, const SCEV *M, bool MaxOrZero,
6812     const SmallPtrSetImpl<const SCEVPredicate *> &PredSet)
6813     : ExitLimit(E, M, MaxOrZero, {&PredSet}) {
6814   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6815           isa<SCEVConstant>(MaxNotTaken)) &&
6816          "No point in having a non-constant max backedge taken count!");
6817 }
6818 
6819 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M,
6820                                       bool MaxOrZero)
6821     : ExitLimit(E, M, MaxOrZero, None) {
6822   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6823           isa<SCEVConstant>(MaxNotTaken)) &&
6824          "No point in having a non-constant max backedge taken count!");
6825 }
6826 
6827 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
6828 /// computable exit into a persistent ExitNotTakenInfo array.
6829 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
6830     SmallVectorImpl<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo>
6831         &&ExitCounts,
6832     bool Complete, const SCEV *MaxCount, bool MaxOrZero)
6833     : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) {
6834   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
6835 
6836   ExitNotTaken.reserve(ExitCounts.size());
6837   std::transform(
6838       ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken),
6839       [&](const EdgeExitInfo &EEI) {
6840         BasicBlock *ExitBB = EEI.first;
6841         const ExitLimit &EL = EEI.second;
6842         if (EL.Predicates.empty())
6843           return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr);
6844 
6845         std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate);
6846         for (auto *Pred : EL.Predicates)
6847           Predicate->add(Pred);
6848 
6849         return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, std::move(Predicate));
6850       });
6851   assert((isa<SCEVCouldNotCompute>(MaxCount) || isa<SCEVConstant>(MaxCount)) &&
6852          "No point in having a non-constant max backedge taken count!");
6853 }
6854 
6855 /// Invalidate this result and free the ExitNotTakenInfo array.
6856 void ScalarEvolution::BackedgeTakenInfo::clear() {
6857   ExitNotTaken.clear();
6858 }
6859 
6860 /// Compute the number of times the backedge of the specified loop will execute.
6861 ScalarEvolution::BackedgeTakenInfo
6862 ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
6863                                            bool AllowPredicates) {
6864   SmallVector<BasicBlock *, 8> ExitingBlocks;
6865   L->getExitingBlocks(ExitingBlocks);
6866 
6867   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
6868 
6869   SmallVector<EdgeExitInfo, 4> ExitCounts;
6870   bool CouldComputeBECount = true;
6871   BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
6872   const SCEV *MustExitMaxBECount = nullptr;
6873   const SCEV *MayExitMaxBECount = nullptr;
6874   bool MustExitMaxOrZero = false;
6875 
6876   // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
6877   // and compute maxBECount.
6878   // Do a union of all the predicates here.
6879   for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
6880     BasicBlock *ExitBB = ExitingBlocks[i];
6881     ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
6882 
6883     assert((AllowPredicates || EL.Predicates.empty()) &&
6884            "Predicated exit limit when predicates are not allowed!");
6885 
6886     // 1. For each exit that can be computed, add an entry to ExitCounts.
6887     // CouldComputeBECount is true only if all exits can be computed.
6888     if (EL.ExactNotTaken == getCouldNotCompute())
6889       // We couldn't compute an exact value for this exit, so
6890       // we won't be able to compute an exact value for the loop.
6891       CouldComputeBECount = false;
6892     else
6893       ExitCounts.emplace_back(ExitBB, EL);
6894 
6895     // 2. Derive the loop's MaxBECount from each exit's max number of
6896     // non-exiting iterations. Partition the loop exits into two kinds:
6897     // LoopMustExits and LoopMayExits.
6898     //
6899     // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
6900     // is a LoopMayExit.  If any computable LoopMustExit is found, then
6901     // MaxBECount is the minimum EL.MaxNotTaken of computable
6902     // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
6903     // EL.MaxNotTaken, where CouldNotCompute is considered greater than any
6904     // computable EL.MaxNotTaken.
6905     if (EL.MaxNotTaken != getCouldNotCompute() && Latch &&
6906         DT.dominates(ExitBB, Latch)) {
6907       if (!MustExitMaxBECount) {
6908         MustExitMaxBECount = EL.MaxNotTaken;
6909         MustExitMaxOrZero = EL.MaxOrZero;
6910       } else {
6911         MustExitMaxBECount =
6912             getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken);
6913       }
6914     } else if (MayExitMaxBECount != getCouldNotCompute()) {
6915       if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute())
6916         MayExitMaxBECount = EL.MaxNotTaken;
6917       else {
6918         MayExitMaxBECount =
6919             getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken);
6920       }
6921     }
6922   }
6923   const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
6924     (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
6925   // The loop backedge will be taken the maximum or zero times if there's
6926   // a single exit that must be taken the maximum or zero times.
6927   bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
6928   return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
6929                            MaxBECount, MaxOrZero);
6930 }
6931 
6932 ScalarEvolution::ExitLimit
6933 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
6934                                       bool AllowPredicates) {
6935   // Okay, we've chosen an exiting block.  See what condition causes us to exit
6936   // at this block and remember the exit block and whether all other targets
6937   // lead to the loop header.
6938   bool MustExecuteLoopHeader = true;
6939   BasicBlock *Exit = nullptr;
6940   for (auto *SBB : successors(ExitingBlock))
6941     if (!L->contains(SBB)) {
6942       if (Exit) // Multiple exit successors.
6943         return getCouldNotCompute();
6944       Exit = SBB;
6945     } else if (SBB != L->getHeader()) {
6946       MustExecuteLoopHeader = false;
6947     }
6948 
6949   // At this point, we know we have a conditional branch that determines whether
6950   // the loop is exited.  However, we don't know if the branch is executed each
6951   // time through the loop.  If not, then the execution count of the branch will
6952   // not be equal to the trip count of the loop.
6953   //
6954   // Currently we check for this by checking to see if the Exit branch goes to
6955   // the loop header.  If so, we know it will always execute the same number of
6956   // times as the loop.  We also handle the case where the exit block *is* the
6957   // loop header.  This is common for un-rotated loops.
6958   //
6959   // If both of those tests fail, walk up the unique predecessor chain to the
6960   // header, stopping if there is an edge that doesn't exit the loop. If the
6961   // header is reached, the execution count of the branch will be equal to the
6962   // trip count of the loop.
6963   //
6964   //  More extensive analysis could be done to handle more cases here.
6965   //
6966   if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) {
6967     // The simple checks failed, try climbing the unique predecessor chain
6968     // up to the header.
6969     bool Ok = false;
6970     for (BasicBlock *BB = ExitingBlock; BB; ) {
6971       BasicBlock *Pred = BB->getUniquePredecessor();
6972       if (!Pred)
6973         return getCouldNotCompute();
6974       TerminatorInst *PredTerm = Pred->getTerminator();
6975       for (const BasicBlock *PredSucc : PredTerm->successors()) {
6976         if (PredSucc == BB)
6977           continue;
6978         // If the predecessor has a successor that isn't BB and isn't
6979         // outside the loop, assume the worst.
6980         if (L->contains(PredSucc))
6981           return getCouldNotCompute();
6982       }
6983       if (Pred == L->getHeader()) {
6984         Ok = true;
6985         break;
6986       }
6987       BB = Pred;
6988     }
6989     if (!Ok)
6990       return getCouldNotCompute();
6991   }
6992 
6993   bool IsOnlyExit = (L->getExitingBlock() != nullptr);
6994   TerminatorInst *Term = ExitingBlock->getTerminator();
6995   if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
6996     assert(BI->isConditional() && "If unconditional, it can't be in loop!");
6997     // Proceed to the next level to examine the exit condition expression.
6998     return computeExitLimitFromCond(
6999         L, BI->getCondition(), BI->getSuccessor(0), BI->getSuccessor(1),
7000         /*ControlsExit=*/IsOnlyExit, AllowPredicates);
7001   }
7002 
7003   if (SwitchInst *SI = dyn_cast<SwitchInst>(Term))
7004     return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
7005                                                 /*ControlsExit=*/IsOnlyExit);
7006 
7007   return getCouldNotCompute();
7008 }
7009 
7010 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond(
7011     const Loop *L, Value *ExitCond, BasicBlock *TBB, BasicBlock *FBB,
7012     bool ControlsExit, bool AllowPredicates) {
7013   ScalarEvolution::ExitLimitCacheTy Cache(L, TBB, FBB, AllowPredicates);
7014   return computeExitLimitFromCondCached(Cache, L, ExitCond, TBB, FBB,
7015                                         ControlsExit, AllowPredicates);
7016 }
7017 
7018 Optional<ScalarEvolution::ExitLimit>
7019 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
7020                                       BasicBlock *TBB, BasicBlock *FBB,
7021                                       bool ControlsExit, bool AllowPredicates) {
7022   (void)this->L;
7023   (void)this->TBB;
7024   (void)this->FBB;
7025   (void)this->AllowPredicates;
7026 
7027   assert(this->L == L && this->TBB == TBB && this->FBB == FBB &&
7028          this->AllowPredicates == AllowPredicates &&
7029          "Variance in assumed invariant key components!");
7030   auto Itr = TripCountMap.find({ExitCond, ControlsExit});
7031   if (Itr == TripCountMap.end())
7032     return None;
7033   return Itr->second;
7034 }
7035 
7036 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
7037                                              BasicBlock *TBB, BasicBlock *FBB,
7038                                              bool ControlsExit,
7039                                              bool AllowPredicates,
7040                                              const ExitLimit &EL) {
7041   assert(this->L == L && this->TBB == TBB && this->FBB == FBB &&
7042          this->AllowPredicates == AllowPredicates &&
7043          "Variance in assumed invariant key components!");
7044 
7045   auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL});
7046   assert(InsertResult.second && "Expected successful insertion!");
7047   (void)InsertResult;
7048 }
7049 
7050 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
7051     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, BasicBlock *TBB,
7052     BasicBlock *FBB, bool ControlsExit, bool AllowPredicates) {
7053 
7054   if (auto MaybeEL =
7055           Cache.find(L, ExitCond, TBB, FBB, ControlsExit, AllowPredicates))
7056     return *MaybeEL;
7057 
7058   ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, TBB, FBB,
7059                                               ControlsExit, AllowPredicates);
7060   Cache.insert(L, ExitCond, TBB, FBB, ControlsExit, AllowPredicates, EL);
7061   return EL;
7062 }
7063 
7064 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
7065     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, BasicBlock *TBB,
7066     BasicBlock *FBB, bool ControlsExit, bool AllowPredicates) {
7067   // Check if the controlling expression for this loop is an And or Or.
7068   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
7069     if (BO->getOpcode() == Instruction::And) {
7070       // Recurse on the operands of the and.
7071       bool EitherMayExit = L->contains(TBB);
7072       ExitLimit EL0 = computeExitLimitFromCondCached(
7073           Cache, L, BO->getOperand(0), TBB, FBB, ControlsExit && !EitherMayExit,
7074           AllowPredicates);
7075       ExitLimit EL1 = computeExitLimitFromCondCached(
7076           Cache, L, BO->getOperand(1), TBB, FBB, ControlsExit && !EitherMayExit,
7077           AllowPredicates);
7078       const SCEV *BECount = getCouldNotCompute();
7079       const SCEV *MaxBECount = getCouldNotCompute();
7080       if (EitherMayExit) {
7081         // Both conditions must be true for the loop to continue executing.
7082         // Choose the less conservative count.
7083         if (EL0.ExactNotTaken == getCouldNotCompute() ||
7084             EL1.ExactNotTaken == getCouldNotCompute())
7085           BECount = getCouldNotCompute();
7086         else
7087           BECount =
7088               getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
7089         if (EL0.MaxNotTaken == getCouldNotCompute())
7090           MaxBECount = EL1.MaxNotTaken;
7091         else if (EL1.MaxNotTaken == getCouldNotCompute())
7092           MaxBECount = EL0.MaxNotTaken;
7093         else
7094           MaxBECount =
7095               getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
7096       } else {
7097         // Both conditions must be true at the same time for the loop to exit.
7098         // For now, be conservative.
7099         assert(L->contains(FBB) && "Loop block has no successor in loop!");
7100         if (EL0.MaxNotTaken == EL1.MaxNotTaken)
7101           MaxBECount = EL0.MaxNotTaken;
7102         if (EL0.ExactNotTaken == EL1.ExactNotTaken)
7103           BECount = EL0.ExactNotTaken;
7104       }
7105 
7106       // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
7107       // to be more aggressive when computing BECount than when computing
7108       // MaxBECount.  In these cases it is possible for EL0.ExactNotTaken and
7109       // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
7110       // to not.
7111       if (isa<SCEVCouldNotCompute>(MaxBECount) &&
7112           !isa<SCEVCouldNotCompute>(BECount))
7113         MaxBECount = getConstant(getUnsignedRangeMax(BECount));
7114 
7115       return ExitLimit(BECount, MaxBECount, false,
7116                        {&EL0.Predicates, &EL1.Predicates});
7117     }
7118     if (BO->getOpcode() == Instruction::Or) {
7119       // Recurse on the operands of the or.
7120       bool EitherMayExit = L->contains(FBB);
7121       ExitLimit EL0 = computeExitLimitFromCondCached(
7122           Cache, L, BO->getOperand(0), TBB, FBB, ControlsExit && !EitherMayExit,
7123           AllowPredicates);
7124       ExitLimit EL1 = computeExitLimitFromCondCached(
7125           Cache, L, BO->getOperand(1), TBB, FBB, ControlsExit && !EitherMayExit,
7126           AllowPredicates);
7127       const SCEV *BECount = getCouldNotCompute();
7128       const SCEV *MaxBECount = getCouldNotCompute();
7129       if (EitherMayExit) {
7130         // Both conditions must be false for the loop to continue executing.
7131         // Choose the less conservative count.
7132         if (EL0.ExactNotTaken == getCouldNotCompute() ||
7133             EL1.ExactNotTaken == getCouldNotCompute())
7134           BECount = getCouldNotCompute();
7135         else
7136           BECount =
7137               getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
7138         if (EL0.MaxNotTaken == getCouldNotCompute())
7139           MaxBECount = EL1.MaxNotTaken;
7140         else if (EL1.MaxNotTaken == getCouldNotCompute())
7141           MaxBECount = EL0.MaxNotTaken;
7142         else
7143           MaxBECount =
7144               getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
7145       } else {
7146         // Both conditions must be false at the same time for the loop to exit.
7147         // For now, be conservative.
7148         assert(L->contains(TBB) && "Loop block has no successor in loop!");
7149         if (EL0.MaxNotTaken == EL1.MaxNotTaken)
7150           MaxBECount = EL0.MaxNotTaken;
7151         if (EL0.ExactNotTaken == EL1.ExactNotTaken)
7152           BECount = EL0.ExactNotTaken;
7153       }
7154 
7155       return ExitLimit(BECount, MaxBECount, false,
7156                        {&EL0.Predicates, &EL1.Predicates});
7157     }
7158   }
7159 
7160   // With an icmp, it may be feasible to compute an exact backedge-taken count.
7161   // Proceed to the next level to examine the icmp.
7162   if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
7163     ExitLimit EL =
7164         computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit);
7165     if (EL.hasFullInfo() || !AllowPredicates)
7166       return EL;
7167 
7168     // Try again, but use SCEV predicates this time.
7169     return computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit,
7170                                     /*AllowPredicates=*/true);
7171   }
7172 
7173   // Check for a constant condition. These are normally stripped out by
7174   // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
7175   // preserve the CFG and is temporarily leaving constant conditions
7176   // in place.
7177   if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
7178     if (L->contains(FBB) == !CI->getZExtValue())
7179       // The backedge is always taken.
7180       return getCouldNotCompute();
7181     else
7182       // The backedge is never taken.
7183       return getZero(CI->getType());
7184   }
7185 
7186   // If it's not an integer or pointer comparison then compute it the hard way.
7187   return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
7188 }
7189 
7190 ScalarEvolution::ExitLimit
7191 ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
7192                                           ICmpInst *ExitCond,
7193                                           BasicBlock *TBB,
7194                                           BasicBlock *FBB,
7195                                           bool ControlsExit,
7196                                           bool AllowPredicates) {
7197   // If the condition was exit on true, convert the condition to exit on false
7198   ICmpInst::Predicate Pred;
7199   if (!L->contains(FBB))
7200     Pred = ExitCond->getPredicate();
7201   else
7202     Pred = ExitCond->getInversePredicate();
7203   const ICmpInst::Predicate OriginalPred = Pred;
7204 
7205   // Handle common loops like: for (X = "string"; *X; ++X)
7206   if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
7207     if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
7208       ExitLimit ItCnt =
7209         computeLoadConstantCompareExitLimit(LI, RHS, L, Pred);
7210       if (ItCnt.hasAnyInfo())
7211         return ItCnt;
7212     }
7213 
7214   const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
7215   const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
7216 
7217   // Try to evaluate any dependencies out of the loop.
7218   LHS = getSCEVAtScope(LHS, L);
7219   RHS = getSCEVAtScope(RHS, L);
7220 
7221   // At this point, we would like to compute how many iterations of the
7222   // loop the predicate will return true for these inputs.
7223   if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
7224     // If there is a loop-invariant, force it into the RHS.
7225     std::swap(LHS, RHS);
7226     Pred = ICmpInst::getSwappedPredicate(Pred);
7227   }
7228 
7229   // Simplify the operands before analyzing them.
7230   (void)SimplifyICmpOperands(Pred, LHS, RHS);
7231 
7232   // If we have a comparison of a chrec against a constant, try to use value
7233   // ranges to answer this query.
7234   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
7235     if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
7236       if (AddRec->getLoop() == L) {
7237         // Form the constant range.
7238         ConstantRange CompRange =
7239             ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt());
7240 
7241         const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
7242         if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
7243       }
7244 
7245   switch (Pred) {
7246   case ICmpInst::ICMP_NE: {                     // while (X != Y)
7247     // Convert to: while (X-Y != 0)
7248     ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit,
7249                                 AllowPredicates);
7250     if (EL.hasAnyInfo()) return EL;
7251     break;
7252   }
7253   case ICmpInst::ICMP_EQ: {                     // while (X == Y)
7254     // Convert to: while (X-Y == 0)
7255     ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
7256     if (EL.hasAnyInfo()) return EL;
7257     break;
7258   }
7259   case ICmpInst::ICMP_SLT:
7260   case ICmpInst::ICMP_ULT: {                    // while (X < Y)
7261     bool IsSigned = Pred == ICmpInst::ICMP_SLT;
7262     ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit,
7263                                     AllowPredicates);
7264     if (EL.hasAnyInfo()) return EL;
7265     break;
7266   }
7267   case ICmpInst::ICMP_SGT:
7268   case ICmpInst::ICMP_UGT: {                    // while (X > Y)
7269     bool IsSigned = Pred == ICmpInst::ICMP_SGT;
7270     ExitLimit EL =
7271         howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
7272                             AllowPredicates);
7273     if (EL.hasAnyInfo()) return EL;
7274     break;
7275   }
7276   default:
7277     break;
7278   }
7279 
7280   auto *ExhaustiveCount =
7281       computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
7282 
7283   if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
7284     return ExhaustiveCount;
7285 
7286   return computeShiftCompareExitLimit(ExitCond->getOperand(0),
7287                                       ExitCond->getOperand(1), L, OriginalPred);
7288 }
7289 
7290 ScalarEvolution::ExitLimit
7291 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
7292                                                       SwitchInst *Switch,
7293                                                       BasicBlock *ExitingBlock,
7294                                                       bool ControlsExit) {
7295   assert(!L->contains(ExitingBlock) && "Not an exiting block!");
7296 
7297   // Give up if the exit is the default dest of a switch.
7298   if (Switch->getDefaultDest() == ExitingBlock)
7299     return getCouldNotCompute();
7300 
7301   assert(L->contains(Switch->getDefaultDest()) &&
7302          "Default case must not exit the loop!");
7303   const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
7304   const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
7305 
7306   // while (X != Y) --> while (X-Y != 0)
7307   ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
7308   if (EL.hasAnyInfo())
7309     return EL;
7310 
7311   return getCouldNotCompute();
7312 }
7313 
7314 static ConstantInt *
7315 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
7316                                 ScalarEvolution &SE) {
7317   const SCEV *InVal = SE.getConstant(C);
7318   const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
7319   assert(isa<SCEVConstant>(Val) &&
7320          "Evaluation of SCEV at constant didn't fold correctly?");
7321   return cast<SCEVConstant>(Val)->getValue();
7322 }
7323 
7324 /// Given an exit condition of 'icmp op load X, cst', try to see if we can
7325 /// compute the backedge execution count.
7326 ScalarEvolution::ExitLimit
7327 ScalarEvolution::computeLoadConstantCompareExitLimit(
7328   LoadInst *LI,
7329   Constant *RHS,
7330   const Loop *L,
7331   ICmpInst::Predicate predicate) {
7332   if (LI->isVolatile()) return getCouldNotCompute();
7333 
7334   // Check to see if the loaded pointer is a getelementptr of a global.
7335   // TODO: Use SCEV instead of manually grubbing with GEPs.
7336   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
7337   if (!GEP) return getCouldNotCompute();
7338 
7339   // Make sure that it is really a constant global we are gepping, with an
7340   // initializer, and make sure the first IDX is really 0.
7341   GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
7342   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
7343       GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
7344       !cast<Constant>(GEP->getOperand(1))->isNullValue())
7345     return getCouldNotCompute();
7346 
7347   // Okay, we allow one non-constant index into the GEP instruction.
7348   Value *VarIdx = nullptr;
7349   std::vector<Constant*> Indexes;
7350   unsigned VarIdxNum = 0;
7351   for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
7352     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
7353       Indexes.push_back(CI);
7354     } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
7355       if (VarIdx) return getCouldNotCompute();  // Multiple non-constant idx's.
7356       VarIdx = GEP->getOperand(i);
7357       VarIdxNum = i-2;
7358       Indexes.push_back(nullptr);
7359     }
7360 
7361   // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
7362   if (!VarIdx)
7363     return getCouldNotCompute();
7364 
7365   // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
7366   // Check to see if X is a loop variant variable value now.
7367   const SCEV *Idx = getSCEV(VarIdx);
7368   Idx = getSCEVAtScope(Idx, L);
7369 
7370   // We can only recognize very limited forms of loop index expressions, in
7371   // particular, only affine AddRec's like {C1,+,C2}.
7372   const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
7373   if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
7374       !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
7375       !isa<SCEVConstant>(IdxExpr->getOperand(1)))
7376     return getCouldNotCompute();
7377 
7378   unsigned MaxSteps = MaxBruteForceIterations;
7379   for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
7380     ConstantInt *ItCst = ConstantInt::get(
7381                            cast<IntegerType>(IdxExpr->getType()), IterationNum);
7382     ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
7383 
7384     // Form the GEP offset.
7385     Indexes[VarIdxNum] = Val;
7386 
7387     Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
7388                                                          Indexes);
7389     if (!Result) break;  // Cannot compute!
7390 
7391     // Evaluate the condition for this iteration.
7392     Result = ConstantExpr::getICmp(predicate, Result, RHS);
7393     if (!isa<ConstantInt>(Result)) break;  // Couldn't decide for sure
7394     if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
7395       ++NumArrayLenItCounts;
7396       return getConstant(ItCst);   // Found terminating iteration!
7397     }
7398   }
7399   return getCouldNotCompute();
7400 }
7401 
7402 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
7403     Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
7404   ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
7405   if (!RHS)
7406     return getCouldNotCompute();
7407 
7408   const BasicBlock *Latch = L->getLoopLatch();
7409   if (!Latch)
7410     return getCouldNotCompute();
7411 
7412   const BasicBlock *Predecessor = L->getLoopPredecessor();
7413   if (!Predecessor)
7414     return getCouldNotCompute();
7415 
7416   // Return true if V is of the form "LHS `shift_op` <positive constant>".
7417   // Return LHS in OutLHS and shift_opt in OutOpCode.
7418   auto MatchPositiveShift =
7419       [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
7420 
7421     using namespace PatternMatch;
7422 
7423     ConstantInt *ShiftAmt;
7424     if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7425       OutOpCode = Instruction::LShr;
7426     else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7427       OutOpCode = Instruction::AShr;
7428     else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7429       OutOpCode = Instruction::Shl;
7430     else
7431       return false;
7432 
7433     return ShiftAmt->getValue().isStrictlyPositive();
7434   };
7435 
7436   // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
7437   //
7438   // loop:
7439   //   %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
7440   //   %iv.shifted = lshr i32 %iv, <positive constant>
7441   //
7442   // Return true on a successful match.  Return the corresponding PHI node (%iv
7443   // above) in PNOut and the opcode of the shift operation in OpCodeOut.
7444   auto MatchShiftRecurrence =
7445       [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
7446     Optional<Instruction::BinaryOps> PostShiftOpCode;
7447 
7448     {
7449       Instruction::BinaryOps OpC;
7450       Value *V;
7451 
7452       // If we encounter a shift instruction, "peel off" the shift operation,
7453       // and remember that we did so.  Later when we inspect %iv's backedge
7454       // value, we will make sure that the backedge value uses the same
7455       // operation.
7456       //
7457       // Note: the peeled shift operation does not have to be the same
7458       // instruction as the one feeding into the PHI's backedge value.  We only
7459       // really care about it being the same *kind* of shift instruction --
7460       // that's all that is required for our later inferences to hold.
7461       if (MatchPositiveShift(LHS, V, OpC)) {
7462         PostShiftOpCode = OpC;
7463         LHS = V;
7464       }
7465     }
7466 
7467     PNOut = dyn_cast<PHINode>(LHS);
7468     if (!PNOut || PNOut->getParent() != L->getHeader())
7469       return false;
7470 
7471     Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
7472     Value *OpLHS;
7473 
7474     return
7475         // The backedge value for the PHI node must be a shift by a positive
7476         // amount
7477         MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
7478 
7479         // of the PHI node itself
7480         OpLHS == PNOut &&
7481 
7482         // and the kind of shift should be match the kind of shift we peeled
7483         // off, if any.
7484         (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut);
7485   };
7486 
7487   PHINode *PN;
7488   Instruction::BinaryOps OpCode;
7489   if (!MatchShiftRecurrence(LHS, PN, OpCode))
7490     return getCouldNotCompute();
7491 
7492   const DataLayout &DL = getDataLayout();
7493 
7494   // The key rationale for this optimization is that for some kinds of shift
7495   // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
7496   // within a finite number of iterations.  If the condition guarding the
7497   // backedge (in the sense that the backedge is taken if the condition is true)
7498   // is false for the value the shift recurrence stabilizes to, then we know
7499   // that the backedge is taken only a finite number of times.
7500 
7501   ConstantInt *StableValue = nullptr;
7502   switch (OpCode) {
7503   default:
7504     llvm_unreachable("Impossible case!");
7505 
7506   case Instruction::AShr: {
7507     // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
7508     // bitwidth(K) iterations.
7509     Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
7510     KnownBits Known = computeKnownBits(FirstValue, DL, 0, nullptr,
7511                                        Predecessor->getTerminator(), &DT);
7512     auto *Ty = cast<IntegerType>(RHS->getType());
7513     if (Known.isNonNegative())
7514       StableValue = ConstantInt::get(Ty, 0);
7515     else if (Known.isNegative())
7516       StableValue = ConstantInt::get(Ty, -1, true);
7517     else
7518       return getCouldNotCompute();
7519 
7520     break;
7521   }
7522   case Instruction::LShr:
7523   case Instruction::Shl:
7524     // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
7525     // stabilize to 0 in at most bitwidth(K) iterations.
7526     StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
7527     break;
7528   }
7529 
7530   auto *Result =
7531       ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
7532   assert(Result->getType()->isIntegerTy(1) &&
7533          "Otherwise cannot be an operand to a branch instruction");
7534 
7535   if (Result->isZeroValue()) {
7536     unsigned BitWidth = getTypeSizeInBits(RHS->getType());
7537     const SCEV *UpperBound =
7538         getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
7539     return ExitLimit(getCouldNotCompute(), UpperBound, false);
7540   }
7541 
7542   return getCouldNotCompute();
7543 }
7544 
7545 /// Return true if we can constant fold an instruction of the specified type,
7546 /// assuming that all operands were constants.
7547 static bool CanConstantFold(const Instruction *I) {
7548   if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
7549       isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
7550       isa<LoadInst>(I))
7551     return true;
7552 
7553   if (const CallInst *CI = dyn_cast<CallInst>(I))
7554     if (const Function *F = CI->getCalledFunction())
7555       return canConstantFoldCallTo(CI, F);
7556   return false;
7557 }
7558 
7559 /// Determine whether this instruction can constant evolve within this loop
7560 /// assuming its operands can all constant evolve.
7561 static bool canConstantEvolve(Instruction *I, const Loop *L) {
7562   // An instruction outside of the loop can't be derived from a loop PHI.
7563   if (!L->contains(I)) return false;
7564 
7565   if (isa<PHINode>(I)) {
7566     // We don't currently keep track of the control flow needed to evaluate
7567     // PHIs, so we cannot handle PHIs inside of loops.
7568     return L->getHeader() == I->getParent();
7569   }
7570 
7571   // If we won't be able to constant fold this expression even if the operands
7572   // are constants, bail early.
7573   return CanConstantFold(I);
7574 }
7575 
7576 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
7577 /// recursing through each instruction operand until reaching a loop header phi.
7578 static PHINode *
7579 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
7580                                DenseMap<Instruction *, PHINode *> &PHIMap,
7581                                unsigned Depth) {
7582   if (Depth > MaxConstantEvolvingDepth)
7583     return nullptr;
7584 
7585   // Otherwise, we can evaluate this instruction if all of its operands are
7586   // constant or derived from a PHI node themselves.
7587   PHINode *PHI = nullptr;
7588   for (Value *Op : UseInst->operands()) {
7589     if (isa<Constant>(Op)) continue;
7590 
7591     Instruction *OpInst = dyn_cast<Instruction>(Op);
7592     if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
7593 
7594     PHINode *P = dyn_cast<PHINode>(OpInst);
7595     if (!P)
7596       // If this operand is already visited, reuse the prior result.
7597       // We may have P != PHI if this is the deepest point at which the
7598       // inconsistent paths meet.
7599       P = PHIMap.lookup(OpInst);
7600     if (!P) {
7601       // Recurse and memoize the results, whether a phi is found or not.
7602       // This recursive call invalidates pointers into PHIMap.
7603       P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1);
7604       PHIMap[OpInst] = P;
7605     }
7606     if (!P)
7607       return nullptr;  // Not evolving from PHI
7608     if (PHI && PHI != P)
7609       return nullptr;  // Evolving from multiple different PHIs.
7610     PHI = P;
7611   }
7612   // This is a expression evolving from a constant PHI!
7613   return PHI;
7614 }
7615 
7616 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
7617 /// in the loop that V is derived from.  We allow arbitrary operations along the
7618 /// way, but the operands of an operation must either be constants or a value
7619 /// derived from a constant PHI.  If this expression does not fit with these
7620 /// constraints, return null.
7621 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
7622   Instruction *I = dyn_cast<Instruction>(V);
7623   if (!I || !canConstantEvolve(I, L)) return nullptr;
7624 
7625   if (PHINode *PN = dyn_cast<PHINode>(I))
7626     return PN;
7627 
7628   // Record non-constant instructions contained by the loop.
7629   DenseMap<Instruction *, PHINode *> PHIMap;
7630   return getConstantEvolvingPHIOperands(I, L, PHIMap, 0);
7631 }
7632 
7633 /// EvaluateExpression - Given an expression that passes the
7634 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
7635 /// in the loop has the value PHIVal.  If we can't fold this expression for some
7636 /// reason, return null.
7637 static Constant *EvaluateExpression(Value *V, const Loop *L,
7638                                     DenseMap<Instruction *, Constant *> &Vals,
7639                                     const DataLayout &DL,
7640                                     const TargetLibraryInfo *TLI) {
7641   // Convenient constant check, but redundant for recursive calls.
7642   if (Constant *C = dyn_cast<Constant>(V)) return C;
7643   Instruction *I = dyn_cast<Instruction>(V);
7644   if (!I) return nullptr;
7645 
7646   if (Constant *C = Vals.lookup(I)) return C;
7647 
7648   // An instruction inside the loop depends on a value outside the loop that we
7649   // weren't given a mapping for, or a value such as a call inside the loop.
7650   if (!canConstantEvolve(I, L)) return nullptr;
7651 
7652   // An unmapped PHI can be due to a branch or another loop inside this loop,
7653   // or due to this not being the initial iteration through a loop where we
7654   // couldn't compute the evolution of this particular PHI last time.
7655   if (isa<PHINode>(I)) return nullptr;
7656 
7657   std::vector<Constant*> Operands(I->getNumOperands());
7658 
7659   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
7660     Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
7661     if (!Operand) {
7662       Operands[i] = dyn_cast<Constant>(I->getOperand(i));
7663       if (!Operands[i]) return nullptr;
7664       continue;
7665     }
7666     Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
7667     Vals[Operand] = C;
7668     if (!C) return nullptr;
7669     Operands[i] = C;
7670   }
7671 
7672   if (CmpInst *CI = dyn_cast<CmpInst>(I))
7673     return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
7674                                            Operands[1], DL, TLI);
7675   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
7676     if (!LI->isVolatile())
7677       return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
7678   }
7679   return ConstantFoldInstOperands(I, Operands, DL, TLI);
7680 }
7681 
7682 
7683 // If every incoming value to PN except the one for BB is a specific Constant,
7684 // return that, else return nullptr.
7685 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
7686   Constant *IncomingVal = nullptr;
7687 
7688   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
7689     if (PN->getIncomingBlock(i) == BB)
7690       continue;
7691 
7692     auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
7693     if (!CurrentVal)
7694       return nullptr;
7695 
7696     if (IncomingVal != CurrentVal) {
7697       if (IncomingVal)
7698         return nullptr;
7699       IncomingVal = CurrentVal;
7700     }
7701   }
7702 
7703   return IncomingVal;
7704 }
7705 
7706 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
7707 /// in the header of its containing loop, we know the loop executes a
7708 /// constant number of times, and the PHI node is just a recurrence
7709 /// involving constants, fold it.
7710 Constant *
7711 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
7712                                                    const APInt &BEs,
7713                                                    const Loop *L) {
7714   auto I = ConstantEvolutionLoopExitValue.find(PN);
7715   if (I != ConstantEvolutionLoopExitValue.end())
7716     return I->second;
7717 
7718   if (BEs.ugt(MaxBruteForceIterations))
7719     return ConstantEvolutionLoopExitValue[PN] = nullptr;  // Not going to evaluate it.
7720 
7721   Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
7722 
7723   DenseMap<Instruction *, Constant *> CurrentIterVals;
7724   BasicBlock *Header = L->getHeader();
7725   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
7726 
7727   BasicBlock *Latch = L->getLoopLatch();
7728   if (!Latch)
7729     return nullptr;
7730 
7731   for (PHINode &PHI : Header->phis()) {
7732     if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
7733       CurrentIterVals[&PHI] = StartCST;
7734   }
7735   if (!CurrentIterVals.count(PN))
7736     return RetVal = nullptr;
7737 
7738   Value *BEValue = PN->getIncomingValueForBlock(Latch);
7739 
7740   // Execute the loop symbolically to determine the exit value.
7741   assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) &&
7742          "BEs is <= MaxBruteForceIterations which is an 'unsigned'!");
7743 
7744   unsigned NumIterations = BEs.getZExtValue(); // must be in range
7745   unsigned IterationNum = 0;
7746   const DataLayout &DL = getDataLayout();
7747   for (; ; ++IterationNum) {
7748     if (IterationNum == NumIterations)
7749       return RetVal = CurrentIterVals[PN];  // Got exit value!
7750 
7751     // Compute the value of the PHIs for the next iteration.
7752     // EvaluateExpression adds non-phi values to the CurrentIterVals map.
7753     DenseMap<Instruction *, Constant *> NextIterVals;
7754     Constant *NextPHI =
7755         EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
7756     if (!NextPHI)
7757       return nullptr;        // Couldn't evaluate!
7758     NextIterVals[PN] = NextPHI;
7759 
7760     bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
7761 
7762     // Also evaluate the other PHI nodes.  However, we don't get to stop if we
7763     // cease to be able to evaluate one of them or if they stop evolving,
7764     // because that doesn't necessarily prevent us from computing PN.
7765     SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
7766     for (const auto &I : CurrentIterVals) {
7767       PHINode *PHI = dyn_cast<PHINode>(I.first);
7768       if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
7769       PHIsToCompute.emplace_back(PHI, I.second);
7770     }
7771     // We use two distinct loops because EvaluateExpression may invalidate any
7772     // iterators into CurrentIterVals.
7773     for (const auto &I : PHIsToCompute) {
7774       PHINode *PHI = I.first;
7775       Constant *&NextPHI = NextIterVals[PHI];
7776       if (!NextPHI) {   // Not already computed.
7777         Value *BEValue = PHI->getIncomingValueForBlock(Latch);
7778         NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
7779       }
7780       if (NextPHI != I.second)
7781         StoppedEvolving = false;
7782     }
7783 
7784     // If all entries in CurrentIterVals == NextIterVals then we can stop
7785     // iterating, the loop can't continue to change.
7786     if (StoppedEvolving)
7787       return RetVal = CurrentIterVals[PN];
7788 
7789     CurrentIterVals.swap(NextIterVals);
7790   }
7791 }
7792 
7793 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
7794                                                           Value *Cond,
7795                                                           bool ExitWhen) {
7796   PHINode *PN = getConstantEvolvingPHI(Cond, L);
7797   if (!PN) return getCouldNotCompute();
7798 
7799   // If the loop is canonicalized, the PHI will have exactly two entries.
7800   // That's the only form we support here.
7801   if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
7802 
7803   DenseMap<Instruction *, Constant *> CurrentIterVals;
7804   BasicBlock *Header = L->getHeader();
7805   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
7806 
7807   BasicBlock *Latch = L->getLoopLatch();
7808   assert(Latch && "Should follow from NumIncomingValues == 2!");
7809 
7810   for (PHINode &PHI : Header->phis()) {
7811     if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
7812       CurrentIterVals[&PHI] = StartCST;
7813   }
7814   if (!CurrentIterVals.count(PN))
7815     return getCouldNotCompute();
7816 
7817   // Okay, we find a PHI node that defines the trip count of this loop.  Execute
7818   // the loop symbolically to determine when the condition gets a value of
7819   // "ExitWhen".
7820   unsigned MaxIterations = MaxBruteForceIterations;   // Limit analysis.
7821   const DataLayout &DL = getDataLayout();
7822   for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
7823     auto *CondVal = dyn_cast_or_null<ConstantInt>(
7824         EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
7825 
7826     // Couldn't symbolically evaluate.
7827     if (!CondVal) return getCouldNotCompute();
7828 
7829     if (CondVal->getValue() == uint64_t(ExitWhen)) {
7830       ++NumBruteForceTripCountsComputed;
7831       return getConstant(Type::getInt32Ty(getContext()), IterationNum);
7832     }
7833 
7834     // Update all the PHI nodes for the next iteration.
7835     DenseMap<Instruction *, Constant *> NextIterVals;
7836 
7837     // Create a list of which PHIs we need to compute. We want to do this before
7838     // calling EvaluateExpression on them because that may invalidate iterators
7839     // into CurrentIterVals.
7840     SmallVector<PHINode *, 8> PHIsToCompute;
7841     for (const auto &I : CurrentIterVals) {
7842       PHINode *PHI = dyn_cast<PHINode>(I.first);
7843       if (!PHI || PHI->getParent() != Header) continue;
7844       PHIsToCompute.push_back(PHI);
7845     }
7846     for (PHINode *PHI : PHIsToCompute) {
7847       Constant *&NextPHI = NextIterVals[PHI];
7848       if (NextPHI) continue;    // Already computed!
7849 
7850       Value *BEValue = PHI->getIncomingValueForBlock(Latch);
7851       NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
7852     }
7853     CurrentIterVals.swap(NextIterVals);
7854   }
7855 
7856   // Too many iterations were needed to evaluate.
7857   return getCouldNotCompute();
7858 }
7859 
7860 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
7861   SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
7862       ValuesAtScopes[V];
7863   // Check to see if we've folded this expression at this loop before.
7864   for (auto &LS : Values)
7865     if (LS.first == L)
7866       return LS.second ? LS.second : V;
7867 
7868   Values.emplace_back(L, nullptr);
7869 
7870   // Otherwise compute it.
7871   const SCEV *C = computeSCEVAtScope(V, L);
7872   for (auto &LS : reverse(ValuesAtScopes[V]))
7873     if (LS.first == L) {
7874       LS.second = C;
7875       break;
7876     }
7877   return C;
7878 }
7879 
7880 /// This builds up a Constant using the ConstantExpr interface.  That way, we
7881 /// will return Constants for objects which aren't represented by a
7882 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
7883 /// Returns NULL if the SCEV isn't representable as a Constant.
7884 static Constant *BuildConstantFromSCEV(const SCEV *V) {
7885   switch (static_cast<SCEVTypes>(V->getSCEVType())) {
7886     case scCouldNotCompute:
7887     case scAddRecExpr:
7888       break;
7889     case scConstant:
7890       return cast<SCEVConstant>(V)->getValue();
7891     case scUnknown:
7892       return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
7893     case scSignExtend: {
7894       const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
7895       if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
7896         return ConstantExpr::getSExt(CastOp, SS->getType());
7897       break;
7898     }
7899     case scZeroExtend: {
7900       const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
7901       if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
7902         return ConstantExpr::getZExt(CastOp, SZ->getType());
7903       break;
7904     }
7905     case scTruncate: {
7906       const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
7907       if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
7908         return ConstantExpr::getTrunc(CastOp, ST->getType());
7909       break;
7910     }
7911     case scAddExpr: {
7912       const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
7913       if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
7914         if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
7915           unsigned AS = PTy->getAddressSpace();
7916           Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
7917           C = ConstantExpr::getBitCast(C, DestPtrTy);
7918         }
7919         for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
7920           Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
7921           if (!C2) return nullptr;
7922 
7923           // First pointer!
7924           if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
7925             unsigned AS = C2->getType()->getPointerAddressSpace();
7926             std::swap(C, C2);
7927             Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
7928             // The offsets have been converted to bytes.  We can add bytes to an
7929             // i8* by GEP with the byte count in the first index.
7930             C = ConstantExpr::getBitCast(C, DestPtrTy);
7931           }
7932 
7933           // Don't bother trying to sum two pointers. We probably can't
7934           // statically compute a load that results from it anyway.
7935           if (C2->getType()->isPointerTy())
7936             return nullptr;
7937 
7938           if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
7939             if (PTy->getElementType()->isStructTy())
7940               C2 = ConstantExpr::getIntegerCast(
7941                   C2, Type::getInt32Ty(C->getContext()), true);
7942             C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2);
7943           } else
7944             C = ConstantExpr::getAdd(C, C2);
7945         }
7946         return C;
7947       }
7948       break;
7949     }
7950     case scMulExpr: {
7951       const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
7952       if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
7953         // Don't bother with pointers at all.
7954         if (C->getType()->isPointerTy()) return nullptr;
7955         for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
7956           Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
7957           if (!C2 || C2->getType()->isPointerTy()) return nullptr;
7958           C = ConstantExpr::getMul(C, C2);
7959         }
7960         return C;
7961       }
7962       break;
7963     }
7964     case scUDivExpr: {
7965       const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
7966       if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
7967         if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
7968           if (LHS->getType() == RHS->getType())
7969             return ConstantExpr::getUDiv(LHS, RHS);
7970       break;
7971     }
7972     case scSMaxExpr:
7973     case scUMaxExpr:
7974       break; // TODO: smax, umax.
7975   }
7976   return nullptr;
7977 }
7978 
7979 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
7980   if (isa<SCEVConstant>(V)) return V;
7981 
7982   // If this instruction is evolved from a constant-evolving PHI, compute the
7983   // exit value from the loop without using SCEVs.
7984   if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
7985     if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
7986       const Loop *LI = this->LI[I->getParent()];
7987       if (LI && LI->getParentLoop() == L)  // Looking for loop exit value.
7988         if (PHINode *PN = dyn_cast<PHINode>(I))
7989           if (PN->getParent() == LI->getHeader()) {
7990             // Okay, there is no closed form solution for the PHI node.  Check
7991             // to see if the loop that contains it has a known backedge-taken
7992             // count.  If so, we may be able to force computation of the exit
7993             // value.
7994             const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
7995             if (const SCEVConstant *BTCC =
7996                   dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
7997 
7998               // This trivial case can show up in some degenerate cases where
7999               // the incoming IR has not yet been fully simplified.
8000               if (BTCC->getValue()->isZero()) {
8001                 Value *InitValue = nullptr;
8002                 bool MultipleInitValues = false;
8003                 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
8004                   if (!LI->contains(PN->getIncomingBlock(i))) {
8005                     if (!InitValue)
8006                       InitValue = PN->getIncomingValue(i);
8007                     else if (InitValue != PN->getIncomingValue(i)) {
8008                       MultipleInitValues = true;
8009                       break;
8010                     }
8011                   }
8012                   if (!MultipleInitValues && InitValue)
8013                     return getSCEV(InitValue);
8014                 }
8015               }
8016               // Okay, we know how many times the containing loop executes.  If
8017               // this is a constant evolving PHI node, get the final value at
8018               // the specified iteration number.
8019               Constant *RV =
8020                   getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI);
8021               if (RV) return getSCEV(RV);
8022             }
8023           }
8024 
8025       // Okay, this is an expression that we cannot symbolically evaluate
8026       // into a SCEV.  Check to see if it's possible to symbolically evaluate
8027       // the arguments into constants, and if so, try to constant propagate the
8028       // result.  This is particularly useful for computing loop exit values.
8029       if (CanConstantFold(I)) {
8030         SmallVector<Constant *, 4> Operands;
8031         bool MadeImprovement = false;
8032         for (Value *Op : I->operands()) {
8033           if (Constant *C = dyn_cast<Constant>(Op)) {
8034             Operands.push_back(C);
8035             continue;
8036           }
8037 
8038           // If any of the operands is non-constant and if they are
8039           // non-integer and non-pointer, don't even try to analyze them
8040           // with scev techniques.
8041           if (!isSCEVable(Op->getType()))
8042             return V;
8043 
8044           const SCEV *OrigV = getSCEV(Op);
8045           const SCEV *OpV = getSCEVAtScope(OrigV, L);
8046           MadeImprovement |= OrigV != OpV;
8047 
8048           Constant *C = BuildConstantFromSCEV(OpV);
8049           if (!C) return V;
8050           if (C->getType() != Op->getType())
8051             C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
8052                                                               Op->getType(),
8053                                                               false),
8054                                       C, Op->getType());
8055           Operands.push_back(C);
8056         }
8057 
8058         // Check to see if getSCEVAtScope actually made an improvement.
8059         if (MadeImprovement) {
8060           Constant *C = nullptr;
8061           const DataLayout &DL = getDataLayout();
8062           if (const CmpInst *CI = dyn_cast<CmpInst>(I))
8063             C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
8064                                                 Operands[1], DL, &TLI);
8065           else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
8066             if (!LI->isVolatile())
8067               C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
8068           } else
8069             C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
8070           if (!C) return V;
8071           return getSCEV(C);
8072         }
8073       }
8074     }
8075 
8076     // This is some other type of SCEVUnknown, just return it.
8077     return V;
8078   }
8079 
8080   if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
8081     // Avoid performing the look-up in the common case where the specified
8082     // expression has no loop-variant portions.
8083     for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
8084       const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
8085       if (OpAtScope != Comm->getOperand(i)) {
8086         // Okay, at least one of these operands is loop variant but might be
8087         // foldable.  Build a new instance of the folded commutative expression.
8088         SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
8089                                             Comm->op_begin()+i);
8090         NewOps.push_back(OpAtScope);
8091 
8092         for (++i; i != e; ++i) {
8093           OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
8094           NewOps.push_back(OpAtScope);
8095         }
8096         if (isa<SCEVAddExpr>(Comm))
8097           return getAddExpr(NewOps);
8098         if (isa<SCEVMulExpr>(Comm))
8099           return getMulExpr(NewOps);
8100         if (isa<SCEVSMaxExpr>(Comm))
8101           return getSMaxExpr(NewOps);
8102         if (isa<SCEVUMaxExpr>(Comm))
8103           return getUMaxExpr(NewOps);
8104         llvm_unreachable("Unknown commutative SCEV type!");
8105       }
8106     }
8107     // If we got here, all operands are loop invariant.
8108     return Comm;
8109   }
8110 
8111   if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
8112     const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
8113     const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
8114     if (LHS == Div->getLHS() && RHS == Div->getRHS())
8115       return Div;   // must be loop invariant
8116     return getUDivExpr(LHS, RHS);
8117   }
8118 
8119   // If this is a loop recurrence for a loop that does not contain L, then we
8120   // are dealing with the final value computed by the loop.
8121   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
8122     // First, attempt to evaluate each operand.
8123     // Avoid performing the look-up in the common case where the specified
8124     // expression has no loop-variant portions.
8125     for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
8126       const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
8127       if (OpAtScope == AddRec->getOperand(i))
8128         continue;
8129 
8130       // Okay, at least one of these operands is loop variant but might be
8131       // foldable.  Build a new instance of the folded commutative expression.
8132       SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
8133                                           AddRec->op_begin()+i);
8134       NewOps.push_back(OpAtScope);
8135       for (++i; i != e; ++i)
8136         NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
8137 
8138       const SCEV *FoldedRec =
8139         getAddRecExpr(NewOps, AddRec->getLoop(),
8140                       AddRec->getNoWrapFlags(SCEV::FlagNW));
8141       AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
8142       // The addrec may be folded to a nonrecurrence, for example, if the
8143       // induction variable is multiplied by zero after constant folding. Go
8144       // ahead and return the folded value.
8145       if (!AddRec)
8146         return FoldedRec;
8147       break;
8148     }
8149 
8150     // If the scope is outside the addrec's loop, evaluate it by using the
8151     // loop exit value of the addrec.
8152     if (!AddRec->getLoop()->contains(L)) {
8153       // To evaluate this recurrence, we need to know how many times the AddRec
8154       // loop iterates.  Compute this now.
8155       const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
8156       if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
8157 
8158       // Then, evaluate the AddRec.
8159       return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
8160     }
8161 
8162     return AddRec;
8163   }
8164 
8165   if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
8166     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8167     if (Op == Cast->getOperand())
8168       return Cast;  // must be loop invariant
8169     return getZeroExtendExpr(Op, Cast->getType());
8170   }
8171 
8172   if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
8173     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8174     if (Op == Cast->getOperand())
8175       return Cast;  // must be loop invariant
8176     return getSignExtendExpr(Op, Cast->getType());
8177   }
8178 
8179   if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
8180     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8181     if (Op == Cast->getOperand())
8182       return Cast;  // must be loop invariant
8183     return getTruncateExpr(Op, Cast->getType());
8184   }
8185 
8186   llvm_unreachable("Unknown SCEV type!");
8187 }
8188 
8189 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
8190   return getSCEVAtScope(getSCEV(V), L);
8191 }
8192 
8193 /// Finds the minimum unsigned root of the following equation:
8194 ///
8195 ///     A * X = B (mod N)
8196 ///
8197 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
8198 /// A and B isn't important.
8199 ///
8200 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
8201 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B,
8202                                                ScalarEvolution &SE) {
8203   uint32_t BW = A.getBitWidth();
8204   assert(BW == SE.getTypeSizeInBits(B->getType()));
8205   assert(A != 0 && "A must be non-zero.");
8206 
8207   // 1. D = gcd(A, N)
8208   //
8209   // The gcd of A and N may have only one prime factor: 2. The number of
8210   // trailing zeros in A is its multiplicity
8211   uint32_t Mult2 = A.countTrailingZeros();
8212   // D = 2^Mult2
8213 
8214   // 2. Check if B is divisible by D.
8215   //
8216   // B is divisible by D if and only if the multiplicity of prime factor 2 for B
8217   // is not less than multiplicity of this prime factor for D.
8218   if (SE.GetMinTrailingZeros(B) < Mult2)
8219     return SE.getCouldNotCompute();
8220 
8221   // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
8222   // modulo (N / D).
8223   //
8224   // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
8225   // (N / D) in general. The inverse itself always fits into BW bits, though,
8226   // so we immediately truncate it.
8227   APInt AD = A.lshr(Mult2).zext(BW + 1);  // AD = A / D
8228   APInt Mod(BW + 1, 0);
8229   Mod.setBit(BW - Mult2);  // Mod = N / D
8230   APInt I = AD.multiplicativeInverse(Mod).trunc(BW);
8231 
8232   // 4. Compute the minimum unsigned root of the equation:
8233   // I * (B / D) mod (N / D)
8234   // To simplify the computation, we factor out the divide by D:
8235   // (I * B mod N) / D
8236   const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
8237   return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
8238 }
8239 
8240 /// Find the roots of the quadratic equation for the given quadratic chrec
8241 /// {L,+,M,+,N}.  This returns either the two roots (which might be the same) or
8242 /// two SCEVCouldNotCompute objects.
8243 static Optional<std::pair<const SCEVConstant *,const SCEVConstant *>>
8244 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
8245   assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
8246   const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
8247   const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
8248   const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
8249 
8250   // We currently can only solve this if the coefficients are constants.
8251   if (!LC || !MC || !NC)
8252     return None;
8253 
8254   uint32_t BitWidth = LC->getAPInt().getBitWidth();
8255   const APInt &L = LC->getAPInt();
8256   const APInt &M = MC->getAPInt();
8257   const APInt &N = NC->getAPInt();
8258   APInt Two(BitWidth, 2);
8259 
8260   // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
8261 
8262   // The A coefficient is N/2
8263   APInt A = N.sdiv(Two);
8264 
8265   // The B coefficient is M-N/2
8266   APInt B = M;
8267   B -= A; // A is the same as N/2.
8268 
8269   // The C coefficient is L.
8270   const APInt& C = L;
8271 
8272   // Compute the B^2-4ac term.
8273   APInt SqrtTerm = B;
8274   SqrtTerm *= B;
8275   SqrtTerm -= 4 * (A * C);
8276 
8277   if (SqrtTerm.isNegative()) {
8278     // The loop is provably infinite.
8279     return None;
8280   }
8281 
8282   // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
8283   // integer value or else APInt::sqrt() will assert.
8284   APInt SqrtVal = SqrtTerm.sqrt();
8285 
8286   // Compute the two solutions for the quadratic formula.
8287   // The divisions must be performed as signed divisions.
8288   APInt NegB = -std::move(B);
8289   APInt TwoA = std::move(A);
8290   TwoA <<= 1;
8291   if (TwoA.isNullValue())
8292     return None;
8293 
8294   LLVMContext &Context = SE.getContext();
8295 
8296   ConstantInt *Solution1 =
8297     ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
8298   ConstantInt *Solution2 =
8299     ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
8300 
8301   return std::make_pair(cast<SCEVConstant>(SE.getConstant(Solution1)),
8302                         cast<SCEVConstant>(SE.getConstant(Solution2)));
8303 }
8304 
8305 ScalarEvolution::ExitLimit
8306 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit,
8307                               bool AllowPredicates) {
8308 
8309   // This is only used for loops with a "x != y" exit test. The exit condition
8310   // is now expressed as a single expression, V = x-y. So the exit test is
8311   // effectively V != 0.  We know and take advantage of the fact that this
8312   // expression only being used in a comparison by zero context.
8313 
8314   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
8315   // If the value is a constant
8316   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
8317     // If the value is already zero, the branch will execute zero times.
8318     if (C->getValue()->isZero()) return C;
8319     return getCouldNotCompute();  // Otherwise it will loop infinitely.
8320   }
8321 
8322   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
8323   if (!AddRec && AllowPredicates)
8324     // Try to make this an AddRec using runtime tests, in the first X
8325     // iterations of this loop, where X is the SCEV expression found by the
8326     // algorithm below.
8327     AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
8328 
8329   if (!AddRec || AddRec->getLoop() != L)
8330     return getCouldNotCompute();
8331 
8332   // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
8333   // the quadratic equation to solve it.
8334   if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
8335     if (auto Roots = SolveQuadraticEquation(AddRec, *this)) {
8336       const SCEVConstant *R1 = Roots->first;
8337       const SCEVConstant *R2 = Roots->second;
8338       // Pick the smallest positive root value.
8339       if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
8340               CmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
8341         if (!CB->getZExtValue())
8342           std::swap(R1, R2); // R1 is the minimum root now.
8343 
8344         // We can only use this value if the chrec ends up with an exact zero
8345         // value at this index.  When solving for "X*X != 5", for example, we
8346         // should not accept a root of 2.
8347         const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
8348         if (Val->isZero())
8349           // We found a quadratic root!
8350           return ExitLimit(R1, R1, false, Predicates);
8351       }
8352     }
8353     return getCouldNotCompute();
8354   }
8355 
8356   // Otherwise we can only handle this if it is affine.
8357   if (!AddRec->isAffine())
8358     return getCouldNotCompute();
8359 
8360   // If this is an affine expression, the execution count of this branch is
8361   // the minimum unsigned root of the following equation:
8362   //
8363   //     Start + Step*N = 0 (mod 2^BW)
8364   //
8365   // equivalent to:
8366   //
8367   //             Step*N = -Start (mod 2^BW)
8368   //
8369   // where BW is the common bit width of Start and Step.
8370 
8371   // Get the initial value for the loop.
8372   const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
8373   const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
8374 
8375   // For now we handle only constant steps.
8376   //
8377   // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
8378   // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
8379   // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
8380   // We have not yet seen any such cases.
8381   const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
8382   if (!StepC || StepC->getValue()->isZero())
8383     return getCouldNotCompute();
8384 
8385   // For positive steps (counting up until unsigned overflow):
8386   //   N = -Start/Step (as unsigned)
8387   // For negative steps (counting down to zero):
8388   //   N = Start/-Step
8389   // First compute the unsigned distance from zero in the direction of Step.
8390   bool CountDown = StepC->getAPInt().isNegative();
8391   const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
8392 
8393   // Handle unitary steps, which cannot wraparound.
8394   // 1*N = -Start; -1*N = Start (mod 2^BW), so:
8395   //   N = Distance (as unsigned)
8396   if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) {
8397     APInt MaxBECount = getUnsignedRangeMax(Distance);
8398 
8399     // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
8400     // we end up with a loop whose backedge-taken count is n - 1.  Detect this
8401     // case, and see if we can improve the bound.
8402     //
8403     // Explicitly handling this here is necessary because getUnsignedRange
8404     // isn't context-sensitive; it doesn't know that we only care about the
8405     // range inside the loop.
8406     const SCEV *Zero = getZero(Distance->getType());
8407     const SCEV *One = getOne(Distance->getType());
8408     const SCEV *DistancePlusOne = getAddExpr(Distance, One);
8409     if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
8410       // If Distance + 1 doesn't overflow, we can compute the maximum distance
8411       // as "unsigned_max(Distance + 1) - 1".
8412       ConstantRange CR = getUnsignedRange(DistancePlusOne);
8413       MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1);
8414     }
8415     return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates);
8416   }
8417 
8418   // If the condition controls loop exit (the loop exits only if the expression
8419   // is true) and the addition is no-wrap we can use unsigned divide to
8420   // compute the backedge count.  In this case, the step may not divide the
8421   // distance, but we don't care because if the condition is "missed" the loop
8422   // will have undefined behavior due to wrapping.
8423   if (ControlsExit && AddRec->hasNoSelfWrap() &&
8424       loopHasNoAbnormalExits(AddRec->getLoop())) {
8425     const SCEV *Exact =
8426         getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
8427     const SCEV *Max =
8428         Exact == getCouldNotCompute()
8429             ? Exact
8430             : getConstant(getUnsignedRangeMax(Exact));
8431     return ExitLimit(Exact, Max, false, Predicates);
8432   }
8433 
8434   // Solve the general equation.
8435   const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(),
8436                                                getNegativeSCEV(Start), *this);
8437   const SCEV *M = E == getCouldNotCompute()
8438                       ? E
8439                       : getConstant(getUnsignedRangeMax(E));
8440   return ExitLimit(E, M, false, Predicates);
8441 }
8442 
8443 ScalarEvolution::ExitLimit
8444 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
8445   // Loops that look like: while (X == 0) are very strange indeed.  We don't
8446   // handle them yet except for the trivial case.  This could be expanded in the
8447   // future as needed.
8448 
8449   // If the value is a constant, check to see if it is known to be non-zero
8450   // already.  If so, the backedge will execute zero times.
8451   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
8452     if (!C->getValue()->isZero())
8453       return getZero(C->getType());
8454     return getCouldNotCompute();  // Otherwise it will loop infinitely.
8455   }
8456 
8457   // We could implement others, but I really doubt anyone writes loops like
8458   // this, and if they did, they would already be constant folded.
8459   return getCouldNotCompute();
8460 }
8461 
8462 std::pair<BasicBlock *, BasicBlock *>
8463 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
8464   // If the block has a unique predecessor, then there is no path from the
8465   // predecessor to the block that does not go through the direct edge
8466   // from the predecessor to the block.
8467   if (BasicBlock *Pred = BB->getSinglePredecessor())
8468     return {Pred, BB};
8469 
8470   // A loop's header is defined to be a block that dominates the loop.
8471   // If the header has a unique predecessor outside the loop, it must be
8472   // a block that has exactly one successor that can reach the loop.
8473   if (Loop *L = LI.getLoopFor(BB))
8474     return {L->getLoopPredecessor(), L->getHeader()};
8475 
8476   return {nullptr, nullptr};
8477 }
8478 
8479 /// SCEV structural equivalence is usually sufficient for testing whether two
8480 /// expressions are equal, however for the purposes of looking for a condition
8481 /// guarding a loop, it can be useful to be a little more general, since a
8482 /// front-end may have replicated the controlling expression.
8483 static bool HasSameValue(const SCEV *A, const SCEV *B) {
8484   // Quick check to see if they are the same SCEV.
8485   if (A == B) return true;
8486 
8487   auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
8488     // Not all instructions that are "identical" compute the same value.  For
8489     // instance, two distinct alloca instructions allocating the same type are
8490     // identical and do not read memory; but compute distinct values.
8491     return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
8492   };
8493 
8494   // Otherwise, if they're both SCEVUnknown, it's possible that they hold
8495   // two different instructions with the same value. Check for this case.
8496   if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
8497     if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
8498       if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
8499         if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
8500           if (ComputesEqualValues(AI, BI))
8501             return true;
8502 
8503   // Otherwise assume they may have a different value.
8504   return false;
8505 }
8506 
8507 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
8508                                            const SCEV *&LHS, const SCEV *&RHS,
8509                                            unsigned Depth) {
8510   bool Changed = false;
8511 
8512   // If we hit the max recursion limit bail out.
8513   if (Depth >= 3)
8514     return false;
8515 
8516   // Canonicalize a constant to the right side.
8517   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
8518     // Check for both operands constant.
8519     if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
8520       if (ConstantExpr::getICmp(Pred,
8521                                 LHSC->getValue(),
8522                                 RHSC->getValue())->isNullValue())
8523         goto trivially_false;
8524       else
8525         goto trivially_true;
8526     }
8527     // Otherwise swap the operands to put the constant on the right.
8528     std::swap(LHS, RHS);
8529     Pred = ICmpInst::getSwappedPredicate(Pred);
8530     Changed = true;
8531   }
8532 
8533   // If we're comparing an addrec with a value which is loop-invariant in the
8534   // addrec's loop, put the addrec on the left. Also make a dominance check,
8535   // as both operands could be addrecs loop-invariant in each other's loop.
8536   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
8537     const Loop *L = AR->getLoop();
8538     if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
8539       std::swap(LHS, RHS);
8540       Pred = ICmpInst::getSwappedPredicate(Pred);
8541       Changed = true;
8542     }
8543   }
8544 
8545   // If there's a constant operand, canonicalize comparisons with boundary
8546   // cases, and canonicalize *-or-equal comparisons to regular comparisons.
8547   if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
8548     const APInt &RA = RC->getAPInt();
8549 
8550     bool SimplifiedByConstantRange = false;
8551 
8552     if (!ICmpInst::isEquality(Pred)) {
8553       ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA);
8554       if (ExactCR.isFullSet())
8555         goto trivially_true;
8556       else if (ExactCR.isEmptySet())
8557         goto trivially_false;
8558 
8559       APInt NewRHS;
8560       CmpInst::Predicate NewPred;
8561       if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
8562           ICmpInst::isEquality(NewPred)) {
8563         // We were able to convert an inequality to an equality.
8564         Pred = NewPred;
8565         RHS = getConstant(NewRHS);
8566         Changed = SimplifiedByConstantRange = true;
8567       }
8568     }
8569 
8570     if (!SimplifiedByConstantRange) {
8571       switch (Pred) {
8572       default:
8573         break;
8574       case ICmpInst::ICMP_EQ:
8575       case ICmpInst::ICMP_NE:
8576         // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
8577         if (!RA)
8578           if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
8579             if (const SCEVMulExpr *ME =
8580                     dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
8581               if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
8582                   ME->getOperand(0)->isAllOnesValue()) {
8583                 RHS = AE->getOperand(1);
8584                 LHS = ME->getOperand(1);
8585                 Changed = true;
8586               }
8587         break;
8588 
8589 
8590         // The "Should have been caught earlier!" messages refer to the fact
8591         // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
8592         // should have fired on the corresponding cases, and canonicalized the
8593         // check to trivially_true or trivially_false.
8594 
8595       case ICmpInst::ICMP_UGE:
8596         assert(!RA.isMinValue() && "Should have been caught earlier!");
8597         Pred = ICmpInst::ICMP_UGT;
8598         RHS = getConstant(RA - 1);
8599         Changed = true;
8600         break;
8601       case ICmpInst::ICMP_ULE:
8602         assert(!RA.isMaxValue() && "Should have been caught earlier!");
8603         Pred = ICmpInst::ICMP_ULT;
8604         RHS = getConstant(RA + 1);
8605         Changed = true;
8606         break;
8607       case ICmpInst::ICMP_SGE:
8608         assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
8609         Pred = ICmpInst::ICMP_SGT;
8610         RHS = getConstant(RA - 1);
8611         Changed = true;
8612         break;
8613       case ICmpInst::ICMP_SLE:
8614         assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
8615         Pred = ICmpInst::ICMP_SLT;
8616         RHS = getConstant(RA + 1);
8617         Changed = true;
8618         break;
8619       }
8620     }
8621   }
8622 
8623   // Check for obvious equality.
8624   if (HasSameValue(LHS, RHS)) {
8625     if (ICmpInst::isTrueWhenEqual(Pred))
8626       goto trivially_true;
8627     if (ICmpInst::isFalseWhenEqual(Pred))
8628       goto trivially_false;
8629   }
8630 
8631   // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
8632   // adding or subtracting 1 from one of the operands.
8633   switch (Pred) {
8634   case ICmpInst::ICMP_SLE:
8635     if (!getSignedRangeMax(RHS).isMaxSignedValue()) {
8636       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
8637                        SCEV::FlagNSW);
8638       Pred = ICmpInst::ICMP_SLT;
8639       Changed = true;
8640     } else if (!getSignedRangeMin(LHS).isMinSignedValue()) {
8641       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
8642                        SCEV::FlagNSW);
8643       Pred = ICmpInst::ICMP_SLT;
8644       Changed = true;
8645     }
8646     break;
8647   case ICmpInst::ICMP_SGE:
8648     if (!getSignedRangeMin(RHS).isMinSignedValue()) {
8649       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
8650                        SCEV::FlagNSW);
8651       Pred = ICmpInst::ICMP_SGT;
8652       Changed = true;
8653     } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) {
8654       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
8655                        SCEV::FlagNSW);
8656       Pred = ICmpInst::ICMP_SGT;
8657       Changed = true;
8658     }
8659     break;
8660   case ICmpInst::ICMP_ULE:
8661     if (!getUnsignedRangeMax(RHS).isMaxValue()) {
8662       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
8663                        SCEV::FlagNUW);
8664       Pred = ICmpInst::ICMP_ULT;
8665       Changed = true;
8666     } else if (!getUnsignedRangeMin(LHS).isMinValue()) {
8667       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
8668       Pred = ICmpInst::ICMP_ULT;
8669       Changed = true;
8670     }
8671     break;
8672   case ICmpInst::ICMP_UGE:
8673     if (!getUnsignedRangeMin(RHS).isMinValue()) {
8674       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
8675       Pred = ICmpInst::ICMP_UGT;
8676       Changed = true;
8677     } else if (!getUnsignedRangeMax(LHS).isMaxValue()) {
8678       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
8679                        SCEV::FlagNUW);
8680       Pred = ICmpInst::ICMP_UGT;
8681       Changed = true;
8682     }
8683     break;
8684   default:
8685     break;
8686   }
8687 
8688   // TODO: More simplifications are possible here.
8689 
8690   // Recursively simplify until we either hit a recursion limit or nothing
8691   // changes.
8692   if (Changed)
8693     return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
8694 
8695   return Changed;
8696 
8697 trivially_true:
8698   // Return 0 == 0.
8699   LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
8700   Pred = ICmpInst::ICMP_EQ;
8701   return true;
8702 
8703 trivially_false:
8704   // Return 0 != 0.
8705   LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
8706   Pred = ICmpInst::ICMP_NE;
8707   return true;
8708 }
8709 
8710 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
8711   return getSignedRangeMax(S).isNegative();
8712 }
8713 
8714 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
8715   return getSignedRangeMin(S).isStrictlyPositive();
8716 }
8717 
8718 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
8719   return !getSignedRangeMin(S).isNegative();
8720 }
8721 
8722 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
8723   return !getSignedRangeMax(S).isStrictlyPositive();
8724 }
8725 
8726 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
8727   return isKnownNegative(S) || isKnownPositive(S);
8728 }
8729 
8730 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
8731                                        const SCEV *LHS, const SCEV *RHS) {
8732   // Canonicalize the inputs first.
8733   (void)SimplifyICmpOperands(Pred, LHS, RHS);
8734 
8735   // If LHS or RHS is an addrec, check to see if the condition is true in
8736   // every iteration of the loop.
8737   // If LHS and RHS are both addrec, both conditions must be true in
8738   // every iteration of the loop.
8739   const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
8740   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
8741   bool LeftGuarded = false;
8742   bool RightGuarded = false;
8743   if (LAR) {
8744     const Loop *L = LAR->getLoop();
8745     if (isAvailableAtLoopEntry(RHS, L) &&
8746         isKnownOnEveryIteration(Pred, LAR, RHS)) {
8747       if (!RAR) return true;
8748       LeftGuarded = true;
8749     }
8750   }
8751   if (RAR) {
8752     const Loop *L = RAR->getLoop();
8753     auto SwappedPred = ICmpInst::getSwappedPredicate(Pred);
8754     if (isAvailableAtLoopEntry(LHS, L) &&
8755         isKnownOnEveryIteration(SwappedPred, RAR, LHS)) {
8756       if (!LAR) return true;
8757       RightGuarded = true;
8758     }
8759   }
8760   if (LeftGuarded && RightGuarded)
8761     return true;
8762 
8763   if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
8764     return true;
8765 
8766   // Otherwise see what can be done with some simple reasoning.
8767   return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS);
8768 }
8769 
8770 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred,
8771                                               const SCEVAddRecExpr *LHS,
8772                                               const SCEV *RHS) {
8773   const Loop *L = LHS->getLoop();
8774   return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) &&
8775          isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS);
8776 }
8777 
8778 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS,
8779                                            ICmpInst::Predicate Pred,
8780                                            bool &Increasing) {
8781   bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing);
8782 
8783 #ifndef NDEBUG
8784   // Verify an invariant: inverting the predicate should turn a monotonically
8785   // increasing change to a monotonically decreasing one, and vice versa.
8786   bool IncreasingSwapped;
8787   bool ResultSwapped = isMonotonicPredicateImpl(
8788       LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped);
8789 
8790   assert(Result == ResultSwapped && "should be able to analyze both!");
8791   if (ResultSwapped)
8792     assert(Increasing == !IncreasingSwapped &&
8793            "monotonicity should flip as we flip the predicate");
8794 #endif
8795 
8796   return Result;
8797 }
8798 
8799 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS,
8800                                                ICmpInst::Predicate Pred,
8801                                                bool &Increasing) {
8802 
8803   // A zero step value for LHS means the induction variable is essentially a
8804   // loop invariant value. We don't really depend on the predicate actually
8805   // flipping from false to true (for increasing predicates, and the other way
8806   // around for decreasing predicates), all we care about is that *if* the
8807   // predicate changes then it only changes from false to true.
8808   //
8809   // A zero step value in itself is not very useful, but there may be places
8810   // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
8811   // as general as possible.
8812 
8813   switch (Pred) {
8814   default:
8815     return false; // Conservative answer
8816 
8817   case ICmpInst::ICMP_UGT:
8818   case ICmpInst::ICMP_UGE:
8819   case ICmpInst::ICMP_ULT:
8820   case ICmpInst::ICMP_ULE:
8821     if (!LHS->hasNoUnsignedWrap())
8822       return false;
8823 
8824     Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE;
8825     return true;
8826 
8827   case ICmpInst::ICMP_SGT:
8828   case ICmpInst::ICMP_SGE:
8829   case ICmpInst::ICMP_SLT:
8830   case ICmpInst::ICMP_SLE: {
8831     if (!LHS->hasNoSignedWrap())
8832       return false;
8833 
8834     const SCEV *Step = LHS->getStepRecurrence(*this);
8835 
8836     if (isKnownNonNegative(Step)) {
8837       Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE;
8838       return true;
8839     }
8840 
8841     if (isKnownNonPositive(Step)) {
8842       Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE;
8843       return true;
8844     }
8845 
8846     return false;
8847   }
8848 
8849   }
8850 
8851   llvm_unreachable("switch has default clause!");
8852 }
8853 
8854 bool ScalarEvolution::isLoopInvariantPredicate(
8855     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
8856     ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS,
8857     const SCEV *&InvariantRHS) {
8858 
8859   // If there is a loop-invariant, force it into the RHS, otherwise bail out.
8860   if (!isLoopInvariant(RHS, L)) {
8861     if (!isLoopInvariant(LHS, L))
8862       return false;
8863 
8864     std::swap(LHS, RHS);
8865     Pred = ICmpInst::getSwappedPredicate(Pred);
8866   }
8867 
8868   const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
8869   if (!ArLHS || ArLHS->getLoop() != L)
8870     return false;
8871 
8872   bool Increasing;
8873   if (!isMonotonicPredicate(ArLHS, Pred, Increasing))
8874     return false;
8875 
8876   // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
8877   // true as the loop iterates, and the backedge is control dependent on
8878   // "ArLHS `Pred` RHS" == true then we can reason as follows:
8879   //
8880   //   * if the predicate was false in the first iteration then the predicate
8881   //     is never evaluated again, since the loop exits without taking the
8882   //     backedge.
8883   //   * if the predicate was true in the first iteration then it will
8884   //     continue to be true for all future iterations since it is
8885   //     monotonically increasing.
8886   //
8887   // For both the above possibilities, we can replace the loop varying
8888   // predicate with its value on the first iteration of the loop (which is
8889   // loop invariant).
8890   //
8891   // A similar reasoning applies for a monotonically decreasing predicate, by
8892   // replacing true with false and false with true in the above two bullets.
8893 
8894   auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
8895 
8896   if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
8897     return false;
8898 
8899   InvariantPred = Pred;
8900   InvariantLHS = ArLHS->getStart();
8901   InvariantRHS = RHS;
8902   return true;
8903 }
8904 
8905 bool ScalarEvolution::isKnownPredicateViaConstantRanges(
8906     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
8907   if (HasSameValue(LHS, RHS))
8908     return ICmpInst::isTrueWhenEqual(Pred);
8909 
8910   // This code is split out from isKnownPredicate because it is called from
8911   // within isLoopEntryGuardedByCond.
8912 
8913   auto CheckRanges =
8914       [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) {
8915     return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS)
8916         .contains(RangeLHS);
8917   };
8918 
8919   // The check at the top of the function catches the case where the values are
8920   // known to be equal.
8921   if (Pred == CmpInst::ICMP_EQ)
8922     return false;
8923 
8924   if (Pred == CmpInst::ICMP_NE)
8925     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) ||
8926            CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) ||
8927            isKnownNonZero(getMinusSCEV(LHS, RHS));
8928 
8929   if (CmpInst::isSigned(Pred))
8930     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS));
8931 
8932   return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS));
8933 }
8934 
8935 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
8936                                                     const SCEV *LHS,
8937                                                     const SCEV *RHS) {
8938   // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer.
8939   // Return Y via OutY.
8940   auto MatchBinaryAddToConst =
8941       [this](const SCEV *Result, const SCEV *X, APInt &OutY,
8942              SCEV::NoWrapFlags ExpectedFlags) {
8943     const SCEV *NonConstOp, *ConstOp;
8944     SCEV::NoWrapFlags FlagsPresent;
8945 
8946     if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) ||
8947         !isa<SCEVConstant>(ConstOp) || NonConstOp != X)
8948       return false;
8949 
8950     OutY = cast<SCEVConstant>(ConstOp)->getAPInt();
8951     return (FlagsPresent & ExpectedFlags) == ExpectedFlags;
8952   };
8953 
8954   APInt C;
8955 
8956   switch (Pred) {
8957   default:
8958     break;
8959 
8960   case ICmpInst::ICMP_SGE:
8961     std::swap(LHS, RHS);
8962     LLVM_FALLTHROUGH;
8963   case ICmpInst::ICMP_SLE:
8964     // X s<= (X + C)<nsw> if C >= 0
8965     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative())
8966       return true;
8967 
8968     // (X + C)<nsw> s<= X if C <= 0
8969     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) &&
8970         !C.isStrictlyPositive())
8971       return true;
8972     break;
8973 
8974   case ICmpInst::ICMP_SGT:
8975     std::swap(LHS, RHS);
8976     LLVM_FALLTHROUGH;
8977   case ICmpInst::ICMP_SLT:
8978     // X s< (X + C)<nsw> if C > 0
8979     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) &&
8980         C.isStrictlyPositive())
8981       return true;
8982 
8983     // (X + C)<nsw> s< X if C < 0
8984     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative())
8985       return true;
8986     break;
8987   }
8988 
8989   return false;
8990 }
8991 
8992 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
8993                                                    const SCEV *LHS,
8994                                                    const SCEV *RHS) {
8995   if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
8996     return false;
8997 
8998   // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
8999   // the stack can result in exponential time complexity.
9000   SaveAndRestore<bool> Restore(ProvingSplitPredicate, true);
9001 
9002   // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
9003   //
9004   // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
9005   // isKnownPredicate.  isKnownPredicate is more powerful, but also more
9006   // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
9007   // interesting cases seen in practice.  We can consider "upgrading" L >= 0 to
9008   // use isKnownPredicate later if needed.
9009   return isKnownNonNegative(RHS) &&
9010          isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
9011          isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
9012 }
9013 
9014 bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB,
9015                                         ICmpInst::Predicate Pred,
9016                                         const SCEV *LHS, const SCEV *RHS) {
9017   // No need to even try if we know the module has no guards.
9018   if (!HasGuards)
9019     return false;
9020 
9021   return any_of(*BB, [&](Instruction &I) {
9022     using namespace llvm::PatternMatch;
9023 
9024     Value *Condition;
9025     return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
9026                          m_Value(Condition))) &&
9027            isImpliedCond(Pred, LHS, RHS, Condition, false);
9028   });
9029 }
9030 
9031 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
9032 /// protected by a conditional between LHS and RHS.  This is used to
9033 /// to eliminate casts.
9034 bool
9035 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
9036                                              ICmpInst::Predicate Pred,
9037                                              const SCEV *LHS, const SCEV *RHS) {
9038   // Interpret a null as meaning no loop, where there is obviously no guard
9039   // (interprocedural conditions notwithstanding).
9040   if (!L) return true;
9041 
9042   if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
9043     return true;
9044 
9045   BasicBlock *Latch = L->getLoopLatch();
9046   if (!Latch)
9047     return false;
9048 
9049   BranchInst *LoopContinuePredicate =
9050     dyn_cast<BranchInst>(Latch->getTerminator());
9051   if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
9052       isImpliedCond(Pred, LHS, RHS,
9053                     LoopContinuePredicate->getCondition(),
9054                     LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
9055     return true;
9056 
9057   // We don't want more than one activation of the following loops on the stack
9058   // -- that can lead to O(n!) time complexity.
9059   if (WalkingBEDominatingConds)
9060     return false;
9061 
9062   SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true);
9063 
9064   // See if we can exploit a trip count to prove the predicate.
9065   const auto &BETakenInfo = getBackedgeTakenInfo(L);
9066   const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
9067   if (LatchBECount != getCouldNotCompute()) {
9068     // We know that Latch branches back to the loop header exactly
9069     // LatchBECount times.  This means the backdege condition at Latch is
9070     // equivalent to  "{0,+,1} u< LatchBECount".
9071     Type *Ty = LatchBECount->getType();
9072     auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
9073     const SCEV *LoopCounter =
9074       getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
9075     if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
9076                       LatchBECount))
9077       return true;
9078   }
9079 
9080   // Check conditions due to any @llvm.assume intrinsics.
9081   for (auto &AssumeVH : AC.assumptions()) {
9082     if (!AssumeVH)
9083       continue;
9084     auto *CI = cast<CallInst>(AssumeVH);
9085     if (!DT.dominates(CI, Latch->getTerminator()))
9086       continue;
9087 
9088     if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
9089       return true;
9090   }
9091 
9092   // If the loop is not reachable from the entry block, we risk running into an
9093   // infinite loop as we walk up into the dom tree.  These loops do not matter
9094   // anyway, so we just return a conservative answer when we see them.
9095   if (!DT.isReachableFromEntry(L->getHeader()))
9096     return false;
9097 
9098   if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
9099     return true;
9100 
9101   for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
9102        DTN != HeaderDTN; DTN = DTN->getIDom()) {
9103     assert(DTN && "should reach the loop header before reaching the root!");
9104 
9105     BasicBlock *BB = DTN->getBlock();
9106     if (isImpliedViaGuard(BB, Pred, LHS, RHS))
9107       return true;
9108 
9109     BasicBlock *PBB = BB->getSinglePredecessor();
9110     if (!PBB)
9111       continue;
9112 
9113     BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
9114     if (!ContinuePredicate || !ContinuePredicate->isConditional())
9115       continue;
9116 
9117     Value *Condition = ContinuePredicate->getCondition();
9118 
9119     // If we have an edge `E` within the loop body that dominates the only
9120     // latch, the condition guarding `E` also guards the backedge.  This
9121     // reasoning works only for loops with a single latch.
9122 
9123     BasicBlockEdge DominatingEdge(PBB, BB);
9124     if (DominatingEdge.isSingleEdge()) {
9125       // We're constructively (and conservatively) enumerating edges within the
9126       // loop body that dominate the latch.  The dominator tree better agree
9127       // with us on this:
9128       assert(DT.dominates(DominatingEdge, Latch) && "should be!");
9129 
9130       if (isImpliedCond(Pred, LHS, RHS, Condition,
9131                         BB != ContinuePredicate->getSuccessor(0)))
9132         return true;
9133     }
9134   }
9135 
9136   return false;
9137 }
9138 
9139 bool
9140 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
9141                                           ICmpInst::Predicate Pred,
9142                                           const SCEV *LHS, const SCEV *RHS) {
9143   // Interpret a null as meaning no loop, where there is obviously no guard
9144   // (interprocedural conditions notwithstanding).
9145   if (!L) return false;
9146 
9147   // Both LHS and RHS must be available at loop entry.
9148   assert(isAvailableAtLoopEntry(LHS, L) &&
9149          "LHS is not available at Loop Entry");
9150   assert(isAvailableAtLoopEntry(RHS, L) &&
9151          "RHS is not available at Loop Entry");
9152 
9153   if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
9154     return true;
9155 
9156   // If we cannot prove strict comparison (e.g. a > b), maybe we can prove
9157   // the facts (a >= b && a != b) separately. A typical situation is when the
9158   // non-strict comparison is known from ranges and non-equality is known from
9159   // dominating predicates. If we are proving strict comparison, we always try
9160   // to prove non-equality and non-strict comparison separately.
9161   auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred);
9162   const bool ProvingStrictComparison = (Pred != NonStrictPredicate);
9163   bool ProvedNonStrictComparison = false;
9164   bool ProvedNonEquality = false;
9165 
9166   if (ProvingStrictComparison) {
9167     ProvedNonStrictComparison =
9168         isKnownViaNonRecursiveReasoning(NonStrictPredicate, LHS, RHS);
9169     ProvedNonEquality =
9170         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, LHS, RHS);
9171     if (ProvedNonStrictComparison && ProvedNonEquality)
9172       return true;
9173   }
9174 
9175   // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard.
9176   auto ProveViaGuard = [&](BasicBlock *Block) {
9177     if (isImpliedViaGuard(Block, Pred, LHS, RHS))
9178       return true;
9179     if (ProvingStrictComparison) {
9180       if (!ProvedNonStrictComparison)
9181         ProvedNonStrictComparison =
9182             isImpliedViaGuard(Block, NonStrictPredicate, LHS, RHS);
9183       if (!ProvedNonEquality)
9184         ProvedNonEquality =
9185             isImpliedViaGuard(Block, ICmpInst::ICMP_NE, LHS, RHS);
9186       if (ProvedNonStrictComparison && ProvedNonEquality)
9187         return true;
9188     }
9189     return false;
9190   };
9191 
9192   // Try to prove (Pred, LHS, RHS) using isImpliedCond.
9193   auto ProveViaCond = [&](Value *Condition, bool Inverse) {
9194     if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse))
9195       return true;
9196     if (ProvingStrictComparison) {
9197       if (!ProvedNonStrictComparison)
9198         ProvedNonStrictComparison =
9199             isImpliedCond(NonStrictPredicate, LHS, RHS, Condition, Inverse);
9200       if (!ProvedNonEquality)
9201         ProvedNonEquality =
9202             isImpliedCond(ICmpInst::ICMP_NE, LHS, RHS, Condition, Inverse);
9203       if (ProvedNonStrictComparison && ProvedNonEquality)
9204         return true;
9205     }
9206     return false;
9207   };
9208 
9209   // Starting at the loop predecessor, climb up the predecessor chain, as long
9210   // as there are predecessors that can be found that have unique successors
9211   // leading to the original header.
9212   for (std::pair<BasicBlock *, BasicBlock *>
9213          Pair(L->getLoopPredecessor(), L->getHeader());
9214        Pair.first;
9215        Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
9216 
9217     if (ProveViaGuard(Pair.first))
9218       return true;
9219 
9220     BranchInst *LoopEntryPredicate =
9221       dyn_cast<BranchInst>(Pair.first->getTerminator());
9222     if (!LoopEntryPredicate ||
9223         LoopEntryPredicate->isUnconditional())
9224       continue;
9225 
9226     if (ProveViaCond(LoopEntryPredicate->getCondition(),
9227                      LoopEntryPredicate->getSuccessor(0) != Pair.second))
9228       return true;
9229   }
9230 
9231   // Check conditions due to any @llvm.assume intrinsics.
9232   for (auto &AssumeVH : AC.assumptions()) {
9233     if (!AssumeVH)
9234       continue;
9235     auto *CI = cast<CallInst>(AssumeVH);
9236     if (!DT.dominates(CI, L->getHeader()))
9237       continue;
9238 
9239     if (ProveViaCond(CI->getArgOperand(0), false))
9240       return true;
9241   }
9242 
9243   return false;
9244 }
9245 
9246 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
9247                                     const SCEV *LHS, const SCEV *RHS,
9248                                     Value *FoundCondValue,
9249                                     bool Inverse) {
9250   if (!PendingLoopPredicates.insert(FoundCondValue).second)
9251     return false;
9252 
9253   auto ClearOnExit =
9254       make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
9255 
9256   // Recursively handle And and Or conditions.
9257   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
9258     if (BO->getOpcode() == Instruction::And) {
9259       if (!Inverse)
9260         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
9261                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
9262     } else if (BO->getOpcode() == Instruction::Or) {
9263       if (Inverse)
9264         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
9265                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
9266     }
9267   }
9268 
9269   ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
9270   if (!ICI) return false;
9271 
9272   // Now that we found a conditional branch that dominates the loop or controls
9273   // the loop latch. Check to see if it is the comparison we are looking for.
9274   ICmpInst::Predicate FoundPred;
9275   if (Inverse)
9276     FoundPred = ICI->getInversePredicate();
9277   else
9278     FoundPred = ICI->getPredicate();
9279 
9280   const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
9281   const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
9282 
9283   return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS);
9284 }
9285 
9286 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
9287                                     const SCEV *RHS,
9288                                     ICmpInst::Predicate FoundPred,
9289                                     const SCEV *FoundLHS,
9290                                     const SCEV *FoundRHS) {
9291   // Balance the types.
9292   if (getTypeSizeInBits(LHS->getType()) <
9293       getTypeSizeInBits(FoundLHS->getType())) {
9294     if (CmpInst::isSigned(Pred)) {
9295       LHS = getSignExtendExpr(LHS, FoundLHS->getType());
9296       RHS = getSignExtendExpr(RHS, FoundLHS->getType());
9297     } else {
9298       LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
9299       RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
9300     }
9301   } else if (getTypeSizeInBits(LHS->getType()) >
9302       getTypeSizeInBits(FoundLHS->getType())) {
9303     if (CmpInst::isSigned(FoundPred)) {
9304       FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
9305       FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
9306     } else {
9307       FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
9308       FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
9309     }
9310   }
9311 
9312   // Canonicalize the query to match the way instcombine will have
9313   // canonicalized the comparison.
9314   if (SimplifyICmpOperands(Pred, LHS, RHS))
9315     if (LHS == RHS)
9316       return CmpInst::isTrueWhenEqual(Pred);
9317   if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
9318     if (FoundLHS == FoundRHS)
9319       return CmpInst::isFalseWhenEqual(FoundPred);
9320 
9321   // Check to see if we can make the LHS or RHS match.
9322   if (LHS == FoundRHS || RHS == FoundLHS) {
9323     if (isa<SCEVConstant>(RHS)) {
9324       std::swap(FoundLHS, FoundRHS);
9325       FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
9326     } else {
9327       std::swap(LHS, RHS);
9328       Pred = ICmpInst::getSwappedPredicate(Pred);
9329     }
9330   }
9331 
9332   // Check whether the found predicate is the same as the desired predicate.
9333   if (FoundPred == Pred)
9334     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
9335 
9336   // Check whether swapping the found predicate makes it the same as the
9337   // desired predicate.
9338   if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
9339     if (isa<SCEVConstant>(RHS))
9340       return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
9341     else
9342       return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
9343                                    RHS, LHS, FoundLHS, FoundRHS);
9344   }
9345 
9346   // Unsigned comparison is the same as signed comparison when both the operands
9347   // are non-negative.
9348   if (CmpInst::isUnsigned(FoundPred) &&
9349       CmpInst::getSignedPredicate(FoundPred) == Pred &&
9350       isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS))
9351     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
9352 
9353   // Check if we can make progress by sharpening ranges.
9354   if (FoundPred == ICmpInst::ICMP_NE &&
9355       (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
9356 
9357     const SCEVConstant *C = nullptr;
9358     const SCEV *V = nullptr;
9359 
9360     if (isa<SCEVConstant>(FoundLHS)) {
9361       C = cast<SCEVConstant>(FoundLHS);
9362       V = FoundRHS;
9363     } else {
9364       C = cast<SCEVConstant>(FoundRHS);
9365       V = FoundLHS;
9366     }
9367 
9368     // The guarding predicate tells us that C != V. If the known range
9369     // of V is [C, t), we can sharpen the range to [C + 1, t).  The
9370     // range we consider has to correspond to same signedness as the
9371     // predicate we're interested in folding.
9372 
9373     APInt Min = ICmpInst::isSigned(Pred) ?
9374         getSignedRangeMin(V) : getUnsignedRangeMin(V);
9375 
9376     if (Min == C->getAPInt()) {
9377       // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
9378       // This is true even if (Min + 1) wraps around -- in case of
9379       // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
9380 
9381       APInt SharperMin = Min + 1;
9382 
9383       switch (Pred) {
9384         case ICmpInst::ICMP_SGE:
9385         case ICmpInst::ICMP_UGE:
9386           // We know V `Pred` SharperMin.  If this implies LHS `Pred`
9387           // RHS, we're done.
9388           if (isImpliedCondOperands(Pred, LHS, RHS, V,
9389                                     getConstant(SharperMin)))
9390             return true;
9391           LLVM_FALLTHROUGH;
9392 
9393         case ICmpInst::ICMP_SGT:
9394         case ICmpInst::ICMP_UGT:
9395           // We know from the range information that (V `Pred` Min ||
9396           // V == Min).  We know from the guarding condition that !(V
9397           // == Min).  This gives us
9398           //
9399           //       V `Pred` Min || V == Min && !(V == Min)
9400           //   =>  V `Pred` Min
9401           //
9402           // If V `Pred` Min implies LHS `Pred` RHS, we're done.
9403 
9404           if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min)))
9405             return true;
9406           LLVM_FALLTHROUGH;
9407 
9408         default:
9409           // No change
9410           break;
9411       }
9412     }
9413   }
9414 
9415   // Check whether the actual condition is beyond sufficient.
9416   if (FoundPred == ICmpInst::ICMP_EQ)
9417     if (ICmpInst::isTrueWhenEqual(Pred))
9418       if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
9419         return true;
9420   if (Pred == ICmpInst::ICMP_NE)
9421     if (!ICmpInst::isTrueWhenEqual(FoundPred))
9422       if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
9423         return true;
9424 
9425   // Otherwise assume the worst.
9426   return false;
9427 }
9428 
9429 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
9430                                      const SCEV *&L, const SCEV *&R,
9431                                      SCEV::NoWrapFlags &Flags) {
9432   const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
9433   if (!AE || AE->getNumOperands() != 2)
9434     return false;
9435 
9436   L = AE->getOperand(0);
9437   R = AE->getOperand(1);
9438   Flags = AE->getNoWrapFlags();
9439   return true;
9440 }
9441 
9442 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More,
9443                                                            const SCEV *Less) {
9444   // We avoid subtracting expressions here because this function is usually
9445   // fairly deep in the call stack (i.e. is called many times).
9446 
9447   if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
9448     const auto *LAR = cast<SCEVAddRecExpr>(Less);
9449     const auto *MAR = cast<SCEVAddRecExpr>(More);
9450 
9451     if (LAR->getLoop() != MAR->getLoop())
9452       return None;
9453 
9454     // We look at affine expressions only; not for correctness but to keep
9455     // getStepRecurrence cheap.
9456     if (!LAR->isAffine() || !MAR->isAffine())
9457       return None;
9458 
9459     if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
9460       return None;
9461 
9462     Less = LAR->getStart();
9463     More = MAR->getStart();
9464 
9465     // fall through
9466   }
9467 
9468   if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
9469     const auto &M = cast<SCEVConstant>(More)->getAPInt();
9470     const auto &L = cast<SCEVConstant>(Less)->getAPInt();
9471     return M - L;
9472   }
9473 
9474   const SCEV *L, *R;
9475   SCEV::NoWrapFlags Flags;
9476   if (splitBinaryAdd(Less, L, R, Flags))
9477     if (const auto *LC = dyn_cast<SCEVConstant>(L))
9478       if (R == More)
9479         return -(LC->getAPInt());
9480 
9481   if (splitBinaryAdd(More, L, R, Flags))
9482     if (const auto *LC = dyn_cast<SCEVConstant>(L))
9483       if (R == Less)
9484         return LC->getAPInt();
9485 
9486   return None;
9487 }
9488 
9489 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
9490     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
9491     const SCEV *FoundLHS, const SCEV *FoundRHS) {
9492   if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
9493     return false;
9494 
9495   const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
9496   if (!AddRecLHS)
9497     return false;
9498 
9499   const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
9500   if (!AddRecFoundLHS)
9501     return false;
9502 
9503   // We'd like to let SCEV reason about control dependencies, so we constrain
9504   // both the inequalities to be about add recurrences on the same loop.  This
9505   // way we can use isLoopEntryGuardedByCond later.
9506 
9507   const Loop *L = AddRecFoundLHS->getLoop();
9508   if (L != AddRecLHS->getLoop())
9509     return false;
9510 
9511   //  FoundLHS u< FoundRHS u< -C =>  (FoundLHS + C) u< (FoundRHS + C) ... (1)
9512   //
9513   //  FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
9514   //                                                                  ... (2)
9515   //
9516   // Informal proof for (2), assuming (1) [*]:
9517   //
9518   // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
9519   //
9520   // Then
9521   //
9522   //       FoundLHS s< FoundRHS s< INT_MIN - C
9523   // <=>  (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C   [ using (3) ]
9524   // <=>  (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
9525   // <=>  (FoundLHS + INT_MIN + C + INT_MIN) s<
9526   //                        (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
9527   // <=>  FoundLHS + C s< FoundRHS + C
9528   //
9529   // [*]: (1) can be proved by ruling out overflow.
9530   //
9531   // [**]: This can be proved by analyzing all the four possibilities:
9532   //    (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
9533   //    (A s>= 0, B s>= 0).
9534   //
9535   // Note:
9536   // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
9537   // will not sign underflow.  For instance, say FoundLHS = (i8 -128), FoundRHS
9538   // = (i8 -127) and C = (i8 -100).  Then INT_MIN - C = (i8 -28), and FoundRHS
9539   // s< (INT_MIN - C).  Lack of sign overflow / underflow in "FoundRHS + C" is
9540   // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
9541   // C)".
9542 
9543   Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
9544   Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
9545   if (!LDiff || !RDiff || *LDiff != *RDiff)
9546     return false;
9547 
9548   if (LDiff->isMinValue())
9549     return true;
9550 
9551   APInt FoundRHSLimit;
9552 
9553   if (Pred == CmpInst::ICMP_ULT) {
9554     FoundRHSLimit = -(*RDiff);
9555   } else {
9556     assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
9557     FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
9558   }
9559 
9560   // Try to prove (1) or (2), as needed.
9561   return isAvailableAtLoopEntry(FoundRHS, L) &&
9562          isLoopEntryGuardedByCond(L, Pred, FoundRHS,
9563                                   getConstant(FoundRHSLimit));
9564 }
9565 
9566 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
9567                                             const SCEV *LHS, const SCEV *RHS,
9568                                             const SCEV *FoundLHS,
9569                                             const SCEV *FoundRHS) {
9570   if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
9571     return true;
9572 
9573   if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
9574     return true;
9575 
9576   return isImpliedCondOperandsHelper(Pred, LHS, RHS,
9577                                      FoundLHS, FoundRHS) ||
9578          // ~x < ~y --> x > y
9579          isImpliedCondOperandsHelper(Pred, LHS, RHS,
9580                                      getNotSCEV(FoundRHS),
9581                                      getNotSCEV(FoundLHS));
9582 }
9583 
9584 /// If Expr computes ~A, return A else return nullptr
9585 static const SCEV *MatchNotExpr(const SCEV *Expr) {
9586   const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
9587   if (!Add || Add->getNumOperands() != 2 ||
9588       !Add->getOperand(0)->isAllOnesValue())
9589     return nullptr;
9590 
9591   const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
9592   if (!AddRHS || AddRHS->getNumOperands() != 2 ||
9593       !AddRHS->getOperand(0)->isAllOnesValue())
9594     return nullptr;
9595 
9596   return AddRHS->getOperand(1);
9597 }
9598 
9599 /// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values?
9600 template<typename MaxExprType>
9601 static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr,
9602                               const SCEV *Candidate) {
9603   const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr);
9604   if (!MaxExpr) return false;
9605 
9606   return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end();
9607 }
9608 
9609 /// Is MaybeMinExpr an SMin or UMin of Candidate and some other values?
9610 template<typename MaxExprType>
9611 static bool IsMinConsistingOf(ScalarEvolution &SE,
9612                               const SCEV *MaybeMinExpr,
9613                               const SCEV *Candidate) {
9614   const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr);
9615   if (!MaybeMaxExpr)
9616     return false;
9617 
9618   return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate));
9619 }
9620 
9621 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
9622                                            ICmpInst::Predicate Pred,
9623                                            const SCEV *LHS, const SCEV *RHS) {
9624   // If both sides are affine addrecs for the same loop, with equal
9625   // steps, and we know the recurrences don't wrap, then we only
9626   // need to check the predicate on the starting values.
9627 
9628   if (!ICmpInst::isRelational(Pred))
9629     return false;
9630 
9631   const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
9632   if (!LAR)
9633     return false;
9634   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
9635   if (!RAR)
9636     return false;
9637   if (LAR->getLoop() != RAR->getLoop())
9638     return false;
9639   if (!LAR->isAffine() || !RAR->isAffine())
9640     return false;
9641 
9642   if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
9643     return false;
9644 
9645   SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
9646                          SCEV::FlagNSW : SCEV::FlagNUW;
9647   if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
9648     return false;
9649 
9650   return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
9651 }
9652 
9653 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
9654 /// expression?
9655 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
9656                                         ICmpInst::Predicate Pred,
9657                                         const SCEV *LHS, const SCEV *RHS) {
9658   switch (Pred) {
9659   default:
9660     return false;
9661 
9662   case ICmpInst::ICMP_SGE:
9663     std::swap(LHS, RHS);
9664     LLVM_FALLTHROUGH;
9665   case ICmpInst::ICMP_SLE:
9666     return
9667       // min(A, ...) <= A
9668       IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) ||
9669       // A <= max(A, ...)
9670       IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
9671 
9672   case ICmpInst::ICMP_UGE:
9673     std::swap(LHS, RHS);
9674     LLVM_FALLTHROUGH;
9675   case ICmpInst::ICMP_ULE:
9676     return
9677       // min(A, ...) <= A
9678       IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) ||
9679       // A <= max(A, ...)
9680       IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
9681   }
9682 
9683   llvm_unreachable("covered switch fell through?!");
9684 }
9685 
9686 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred,
9687                                              const SCEV *LHS, const SCEV *RHS,
9688                                              const SCEV *FoundLHS,
9689                                              const SCEV *FoundRHS,
9690                                              unsigned Depth) {
9691   assert(getTypeSizeInBits(LHS->getType()) ==
9692              getTypeSizeInBits(RHS->getType()) &&
9693          "LHS and RHS have different sizes?");
9694   assert(getTypeSizeInBits(FoundLHS->getType()) ==
9695              getTypeSizeInBits(FoundRHS->getType()) &&
9696          "FoundLHS and FoundRHS have different sizes?");
9697   // We want to avoid hurting the compile time with analysis of too big trees.
9698   if (Depth > MaxSCEVOperationsImplicationDepth)
9699     return false;
9700   // We only want to work with ICMP_SGT comparison so far.
9701   // TODO: Extend to ICMP_UGT?
9702   if (Pred == ICmpInst::ICMP_SLT) {
9703     Pred = ICmpInst::ICMP_SGT;
9704     std::swap(LHS, RHS);
9705     std::swap(FoundLHS, FoundRHS);
9706   }
9707   if (Pred != ICmpInst::ICMP_SGT)
9708     return false;
9709 
9710   auto GetOpFromSExt = [&](const SCEV *S) {
9711     if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
9712       return Ext->getOperand();
9713     // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
9714     // the constant in some cases.
9715     return S;
9716   };
9717 
9718   // Acquire values from extensions.
9719   auto *OrigFoundLHS = FoundLHS;
9720   LHS = GetOpFromSExt(LHS);
9721   FoundLHS = GetOpFromSExt(FoundLHS);
9722 
9723   // Is the SGT predicate can be proved trivially or using the found context.
9724   auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
9725     return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
9726            isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
9727                                   FoundRHS, Depth + 1);
9728   };
9729 
9730   if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
9731     // We want to avoid creation of any new non-constant SCEV. Since we are
9732     // going to compare the operands to RHS, we should be certain that we don't
9733     // need any size extensions for this. So let's decline all cases when the
9734     // sizes of types of LHS and RHS do not match.
9735     // TODO: Maybe try to get RHS from sext to catch more cases?
9736     if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType()))
9737       return false;
9738 
9739     // Should not overflow.
9740     if (!LHSAddExpr->hasNoSignedWrap())
9741       return false;
9742 
9743     auto *LL = LHSAddExpr->getOperand(0);
9744     auto *LR = LHSAddExpr->getOperand(1);
9745     auto *MinusOne = getNegativeSCEV(getOne(RHS->getType()));
9746 
9747     // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
9748     auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
9749       return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
9750     };
9751     // Try to prove the following rule:
9752     // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
9753     // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
9754     if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
9755       return true;
9756   } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
9757     Value *LL, *LR;
9758     // FIXME: Once we have SDiv implemented, we can get rid of this matching.
9759 
9760     using namespace llvm::PatternMatch;
9761 
9762     if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
9763       // Rules for division.
9764       // We are going to perform some comparisons with Denominator and its
9765       // derivative expressions. In general case, creating a SCEV for it may
9766       // lead to a complex analysis of the entire graph, and in particular it
9767       // can request trip count recalculation for the same loop. This would
9768       // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
9769       // this, we only want to create SCEVs that are constants in this section.
9770       // So we bail if Denominator is not a constant.
9771       if (!isa<ConstantInt>(LR))
9772         return false;
9773 
9774       auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
9775 
9776       // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
9777       // then a SCEV for the numerator already exists and matches with FoundLHS.
9778       auto *Numerator = getExistingSCEV(LL);
9779       if (!Numerator || Numerator->getType() != FoundLHS->getType())
9780         return false;
9781 
9782       // Make sure that the numerator matches with FoundLHS and the denominator
9783       // is positive.
9784       if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
9785         return false;
9786 
9787       auto *DTy = Denominator->getType();
9788       auto *FRHSTy = FoundRHS->getType();
9789       if (DTy->isPointerTy() != FRHSTy->isPointerTy())
9790         // One of types is a pointer and another one is not. We cannot extend
9791         // them properly to a wider type, so let us just reject this case.
9792         // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
9793         // to avoid this check.
9794         return false;
9795 
9796       // Given that:
9797       // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
9798       auto *WTy = getWiderType(DTy, FRHSTy);
9799       auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
9800       auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
9801 
9802       // Try to prove the following rule:
9803       // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
9804       // For example, given that FoundLHS > 2. It means that FoundLHS is at
9805       // least 3. If we divide it by Denominator < 4, we will have at least 1.
9806       auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
9807       if (isKnownNonPositive(RHS) &&
9808           IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
9809         return true;
9810 
9811       // Try to prove the following rule:
9812       // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
9813       // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
9814       // If we divide it by Denominator > 2, then:
9815       // 1. If FoundLHS is negative, then the result is 0.
9816       // 2. If FoundLHS is non-negative, then the result is non-negative.
9817       // Anyways, the result is non-negative.
9818       auto *MinusOne = getNegativeSCEV(getOne(WTy));
9819       auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
9820       if (isKnownNegative(RHS) &&
9821           IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
9822         return true;
9823     }
9824   }
9825 
9826   return false;
9827 }
9828 
9829 bool
9830 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred,
9831                                            const SCEV *LHS, const SCEV *RHS) {
9832   return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
9833          IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
9834          IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
9835          isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
9836 }
9837 
9838 bool
9839 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
9840                                              const SCEV *LHS, const SCEV *RHS,
9841                                              const SCEV *FoundLHS,
9842                                              const SCEV *FoundRHS) {
9843   switch (Pred) {
9844   default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
9845   case ICmpInst::ICMP_EQ:
9846   case ICmpInst::ICMP_NE:
9847     if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
9848       return true;
9849     break;
9850   case ICmpInst::ICMP_SLT:
9851   case ICmpInst::ICMP_SLE:
9852     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
9853         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS))
9854       return true;
9855     break;
9856   case ICmpInst::ICMP_SGT:
9857   case ICmpInst::ICMP_SGE:
9858     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
9859         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS))
9860       return true;
9861     break;
9862   case ICmpInst::ICMP_ULT:
9863   case ICmpInst::ICMP_ULE:
9864     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
9865         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS))
9866       return true;
9867     break;
9868   case ICmpInst::ICMP_UGT:
9869   case ICmpInst::ICMP_UGE:
9870     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
9871         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS))
9872       return true;
9873     break;
9874   }
9875 
9876   // Maybe it can be proved via operations?
9877   if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
9878     return true;
9879 
9880   return false;
9881 }
9882 
9883 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
9884                                                      const SCEV *LHS,
9885                                                      const SCEV *RHS,
9886                                                      const SCEV *FoundLHS,
9887                                                      const SCEV *FoundRHS) {
9888   if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
9889     // The restriction on `FoundRHS` be lifted easily -- it exists only to
9890     // reduce the compile time impact of this optimization.
9891     return false;
9892 
9893   Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
9894   if (!Addend)
9895     return false;
9896 
9897   const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
9898 
9899   // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
9900   // antecedent "`FoundLHS` `Pred` `FoundRHS`".
9901   ConstantRange FoundLHSRange =
9902       ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS);
9903 
9904   // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
9905   ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
9906 
9907   // We can also compute the range of values for `LHS` that satisfy the
9908   // consequent, "`LHS` `Pred` `RHS`":
9909   const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
9910   ConstantRange SatisfyingLHSRange =
9911       ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS);
9912 
9913   // The antecedent implies the consequent if every value of `LHS` that
9914   // satisfies the antecedent also satisfies the consequent.
9915   return SatisfyingLHSRange.contains(LHSRange);
9916 }
9917 
9918 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
9919                                          bool IsSigned, bool NoWrap) {
9920   assert(isKnownPositive(Stride) && "Positive stride expected!");
9921 
9922   if (NoWrap) return false;
9923 
9924   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
9925   const SCEV *One = getOne(Stride->getType());
9926 
9927   if (IsSigned) {
9928     APInt MaxRHS = getSignedRangeMax(RHS);
9929     APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
9930     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
9931 
9932     // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
9933     return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS);
9934   }
9935 
9936   APInt MaxRHS = getUnsignedRangeMax(RHS);
9937   APInt MaxValue = APInt::getMaxValue(BitWidth);
9938   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
9939 
9940   // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
9941   return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS);
9942 }
9943 
9944 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
9945                                          bool IsSigned, bool NoWrap) {
9946   if (NoWrap) return false;
9947 
9948   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
9949   const SCEV *One = getOne(Stride->getType());
9950 
9951   if (IsSigned) {
9952     APInt MinRHS = getSignedRangeMin(RHS);
9953     APInt MinValue = APInt::getSignedMinValue(BitWidth);
9954     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
9955 
9956     // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
9957     return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS);
9958   }
9959 
9960   APInt MinRHS = getUnsignedRangeMin(RHS);
9961   APInt MinValue = APInt::getMinValue(BitWidth);
9962   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
9963 
9964   // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
9965   return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS);
9966 }
9967 
9968 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step,
9969                                             bool Equality) {
9970   const SCEV *One = getOne(Step->getType());
9971   Delta = Equality ? getAddExpr(Delta, Step)
9972                    : getAddExpr(Delta, getMinusSCEV(Step, One));
9973   return getUDivExpr(Delta, Step);
9974 }
9975 
9976 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start,
9977                                                     const SCEV *Stride,
9978                                                     const SCEV *End,
9979                                                     unsigned BitWidth,
9980                                                     bool IsSigned) {
9981 
9982   assert(!isKnownNonPositive(Stride) &&
9983          "Stride is expected strictly positive!");
9984   // Calculate the maximum backedge count based on the range of values
9985   // permitted by Start, End, and Stride.
9986   const SCEV *MaxBECount;
9987   APInt MinStart =
9988       IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start);
9989 
9990   APInt StrideForMaxBECount =
9991       IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride);
9992 
9993   // We already know that the stride is positive, so we paper over conservatism
9994   // in our range computation by forcing StrideForMaxBECount to be at least one.
9995   // In theory this is unnecessary, but we expect MaxBECount to be a
9996   // SCEVConstant, and (udiv <constant> 0) is not constant folded by SCEV (there
9997   // is nothing to constant fold it to).
9998   APInt One(BitWidth, 1, IsSigned);
9999   StrideForMaxBECount = APIntOps::smax(One, StrideForMaxBECount);
10000 
10001   APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth)
10002                             : APInt::getMaxValue(BitWidth);
10003   APInt Limit = MaxValue - (StrideForMaxBECount - 1);
10004 
10005   // Although End can be a MAX expression we estimate MaxEnd considering only
10006   // the case End = RHS of the loop termination condition. This is safe because
10007   // in the other case (End - Start) is zero, leading to a zero maximum backedge
10008   // taken count.
10009   APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit)
10010                           : APIntOps::umin(getUnsignedRangeMax(End), Limit);
10011 
10012   MaxBECount = computeBECount(getConstant(MaxEnd - MinStart) /* Delta */,
10013                               getConstant(StrideForMaxBECount) /* Step */,
10014                               false /* Equality */);
10015 
10016   return MaxBECount;
10017 }
10018 
10019 ScalarEvolution::ExitLimit
10020 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
10021                                   const Loop *L, bool IsSigned,
10022                                   bool ControlsExit, bool AllowPredicates) {
10023   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
10024 
10025   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
10026   bool PredicatedIV = false;
10027 
10028   if (!IV && AllowPredicates) {
10029     // Try to make this an AddRec using runtime tests, in the first X
10030     // iterations of this loop, where X is the SCEV expression found by the
10031     // algorithm below.
10032     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
10033     PredicatedIV = true;
10034   }
10035 
10036   // Avoid weird loops
10037   if (!IV || IV->getLoop() != L || !IV->isAffine())
10038     return getCouldNotCompute();
10039 
10040   bool NoWrap = ControlsExit &&
10041                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
10042 
10043   const SCEV *Stride = IV->getStepRecurrence(*this);
10044 
10045   bool PositiveStride = isKnownPositive(Stride);
10046 
10047   // Avoid negative or zero stride values.
10048   if (!PositiveStride) {
10049     // We can compute the correct backedge taken count for loops with unknown
10050     // strides if we can prove that the loop is not an infinite loop with side
10051     // effects. Here's the loop structure we are trying to handle -
10052     //
10053     // i = start
10054     // do {
10055     //   A[i] = i;
10056     //   i += s;
10057     // } while (i < end);
10058     //
10059     // The backedge taken count for such loops is evaluated as -
10060     // (max(end, start + stride) - start - 1) /u stride
10061     //
10062     // The additional preconditions that we need to check to prove correctness
10063     // of the above formula is as follows -
10064     //
10065     // a) IV is either nuw or nsw depending upon signedness (indicated by the
10066     //    NoWrap flag).
10067     // b) loop is single exit with no side effects.
10068     //
10069     //
10070     // Precondition a) implies that if the stride is negative, this is a single
10071     // trip loop. The backedge taken count formula reduces to zero in this case.
10072     //
10073     // Precondition b) implies that the unknown stride cannot be zero otherwise
10074     // we have UB.
10075     //
10076     // The positive stride case is the same as isKnownPositive(Stride) returning
10077     // true (original behavior of the function).
10078     //
10079     // We want to make sure that the stride is truly unknown as there are edge
10080     // cases where ScalarEvolution propagates no wrap flags to the
10081     // post-increment/decrement IV even though the increment/decrement operation
10082     // itself is wrapping. The computed backedge taken count may be wrong in
10083     // such cases. This is prevented by checking that the stride is not known to
10084     // be either positive or non-positive. For example, no wrap flags are
10085     // propagated to the post-increment IV of this loop with a trip count of 2 -
10086     //
10087     // unsigned char i;
10088     // for(i=127; i<128; i+=129)
10089     //   A[i] = i;
10090     //
10091     if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) ||
10092         !loopHasNoSideEffects(L))
10093       return getCouldNotCompute();
10094   } else if (!Stride->isOne() &&
10095              doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap))
10096     // Avoid proven overflow cases: this will ensure that the backedge taken
10097     // count will not generate any unsigned overflow. Relaxed no-overflow
10098     // conditions exploit NoWrapFlags, allowing to optimize in presence of
10099     // undefined behaviors like the case of C language.
10100     return getCouldNotCompute();
10101 
10102   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT
10103                                       : ICmpInst::ICMP_ULT;
10104   const SCEV *Start = IV->getStart();
10105   const SCEV *End = RHS;
10106   // When the RHS is not invariant, we do not know the end bound of the loop and
10107   // cannot calculate the ExactBECount needed by ExitLimit. However, we can
10108   // calculate the MaxBECount, given the start, stride and max value for the end
10109   // bound of the loop (RHS), and the fact that IV does not overflow (which is
10110   // checked above).
10111   if (!isLoopInvariant(RHS, L)) {
10112     const SCEV *MaxBECount = computeMaxBECountForLT(
10113         Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
10114     return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount,
10115                      false /*MaxOrZero*/, Predicates);
10116   }
10117   // If the backedge is taken at least once, then it will be taken
10118   // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start
10119   // is the LHS value of the less-than comparison the first time it is evaluated
10120   // and End is the RHS.
10121   const SCEV *BECountIfBackedgeTaken =
10122     computeBECount(getMinusSCEV(End, Start), Stride, false);
10123   // If the loop entry is guarded by the result of the backedge test of the
10124   // first loop iteration, then we know the backedge will be taken at least
10125   // once and so the backedge taken count is as above. If not then we use the
10126   // expression (max(End,Start)-Start)/Stride to describe the backedge count,
10127   // as if the backedge is taken at least once max(End,Start) is End and so the
10128   // result is as above, and if not max(End,Start) is Start so we get a backedge
10129   // count of zero.
10130   const SCEV *BECount;
10131   if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS))
10132     BECount = BECountIfBackedgeTaken;
10133   else {
10134     End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
10135     BECount = computeBECount(getMinusSCEV(End, Start), Stride, false);
10136   }
10137 
10138   const SCEV *MaxBECount;
10139   bool MaxOrZero = false;
10140   if (isa<SCEVConstant>(BECount))
10141     MaxBECount = BECount;
10142   else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) {
10143     // If we know exactly how many times the backedge will be taken if it's
10144     // taken at least once, then the backedge count will either be that or
10145     // zero.
10146     MaxBECount = BECountIfBackedgeTaken;
10147     MaxOrZero = true;
10148   } else {
10149     MaxBECount = computeMaxBECountForLT(
10150         Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
10151   }
10152 
10153   if (isa<SCEVCouldNotCompute>(MaxBECount) &&
10154       !isa<SCEVCouldNotCompute>(BECount))
10155     MaxBECount = getConstant(getUnsignedRangeMax(BECount));
10156 
10157   return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates);
10158 }
10159 
10160 ScalarEvolution::ExitLimit
10161 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
10162                                      const Loop *L, bool IsSigned,
10163                                      bool ControlsExit, bool AllowPredicates) {
10164   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
10165   // We handle only IV > Invariant
10166   if (!isLoopInvariant(RHS, L))
10167     return getCouldNotCompute();
10168 
10169   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
10170   if (!IV && AllowPredicates)
10171     // Try to make this an AddRec using runtime tests, in the first X
10172     // iterations of this loop, where X is the SCEV expression found by the
10173     // algorithm below.
10174     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
10175 
10176   // Avoid weird loops
10177   if (!IV || IV->getLoop() != L || !IV->isAffine())
10178     return getCouldNotCompute();
10179 
10180   bool NoWrap = ControlsExit &&
10181                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
10182 
10183   const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
10184 
10185   // Avoid negative or zero stride values
10186   if (!isKnownPositive(Stride))
10187     return getCouldNotCompute();
10188 
10189   // Avoid proven overflow cases: this will ensure that the backedge taken count
10190   // will not generate any unsigned overflow. Relaxed no-overflow conditions
10191   // exploit NoWrapFlags, allowing to optimize in presence of undefined
10192   // behaviors like the case of C language.
10193   if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap))
10194     return getCouldNotCompute();
10195 
10196   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT
10197                                       : ICmpInst::ICMP_UGT;
10198 
10199   const SCEV *Start = IV->getStart();
10200   const SCEV *End = RHS;
10201   if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS))
10202     End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
10203 
10204   const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false);
10205 
10206   APInt MaxStart = IsSigned ? getSignedRangeMax(Start)
10207                             : getUnsignedRangeMax(Start);
10208 
10209   APInt MinStride = IsSigned ? getSignedRangeMin(Stride)
10210                              : getUnsignedRangeMin(Stride);
10211 
10212   unsigned BitWidth = getTypeSizeInBits(LHS->getType());
10213   APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
10214                          : APInt::getMinValue(BitWidth) + (MinStride - 1);
10215 
10216   // Although End can be a MIN expression we estimate MinEnd considering only
10217   // the case End = RHS. This is safe because in the other case (Start - End)
10218   // is zero, leading to a zero maximum backedge taken count.
10219   APInt MinEnd =
10220     IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit)
10221              : APIntOps::umax(getUnsignedRangeMin(RHS), Limit);
10222 
10223 
10224   const SCEV *MaxBECount = getCouldNotCompute();
10225   if (isa<SCEVConstant>(BECount))
10226     MaxBECount = BECount;
10227   else
10228     MaxBECount = computeBECount(getConstant(MaxStart - MinEnd),
10229                                 getConstant(MinStride), false);
10230 
10231   if (isa<SCEVCouldNotCompute>(MaxBECount))
10232     MaxBECount = BECount;
10233 
10234   return ExitLimit(BECount, MaxBECount, false, Predicates);
10235 }
10236 
10237 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range,
10238                                                     ScalarEvolution &SE) const {
10239   if (Range.isFullSet())  // Infinite loop.
10240     return SE.getCouldNotCompute();
10241 
10242   // If the start is a non-zero constant, shift the range to simplify things.
10243   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
10244     if (!SC->getValue()->isZero()) {
10245       SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
10246       Operands[0] = SE.getZero(SC->getType());
10247       const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
10248                                              getNoWrapFlags(FlagNW));
10249       if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
10250         return ShiftedAddRec->getNumIterationsInRange(
10251             Range.subtract(SC->getAPInt()), SE);
10252       // This is strange and shouldn't happen.
10253       return SE.getCouldNotCompute();
10254     }
10255 
10256   // The only time we can solve this is when we have all constant indices.
10257   // Otherwise, we cannot determine the overflow conditions.
10258   if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
10259     return SE.getCouldNotCompute();
10260 
10261   // Okay at this point we know that all elements of the chrec are constants and
10262   // that the start element is zero.
10263 
10264   // First check to see if the range contains zero.  If not, the first
10265   // iteration exits.
10266   unsigned BitWidth = SE.getTypeSizeInBits(getType());
10267   if (!Range.contains(APInt(BitWidth, 0)))
10268     return SE.getZero(getType());
10269 
10270   if (isAffine()) {
10271     // If this is an affine expression then we have this situation:
10272     //   Solve {0,+,A} in Range  ===  Ax in Range
10273 
10274     // We know that zero is in the range.  If A is positive then we know that
10275     // the upper value of the range must be the first possible exit value.
10276     // If A is negative then the lower of the range is the last possible loop
10277     // value.  Also note that we already checked for a full range.
10278     APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
10279     APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower();
10280 
10281     // The exit value should be (End+A)/A.
10282     APInt ExitVal = (End + A).udiv(A);
10283     ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
10284 
10285     // Evaluate at the exit value.  If we really did fall out of the valid
10286     // range, then we computed our trip count, otherwise wrap around or other
10287     // things must have happened.
10288     ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
10289     if (Range.contains(Val->getValue()))
10290       return SE.getCouldNotCompute();  // Something strange happened
10291 
10292     // Ensure that the previous value is in the range.  This is a sanity check.
10293     assert(Range.contains(
10294            EvaluateConstantChrecAtConstant(this,
10295            ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&
10296            "Linear scev computation is off in a bad way!");
10297     return SE.getConstant(ExitValue);
10298   } else if (isQuadratic()) {
10299     // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
10300     // quadratic equation to solve it.  To do this, we must frame our problem in
10301     // terms of figuring out when zero is crossed, instead of when
10302     // Range.getUpper() is crossed.
10303     SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
10304     NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
10305     const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(), FlagAnyWrap);
10306 
10307     // Next, solve the constructed addrec
10308     if (auto Roots =
10309             SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE)) {
10310       const SCEVConstant *R1 = Roots->first;
10311       const SCEVConstant *R2 = Roots->second;
10312       // Pick the smallest positive root value.
10313       if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
10314               ICmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
10315         if (!CB->getZExtValue())
10316           std::swap(R1, R2); // R1 is the minimum root now.
10317 
10318         // Make sure the root is not off by one.  The returned iteration should
10319         // not be in the range, but the previous one should be.  When solving
10320         // for "X*X < 5", for example, we should not return a root of 2.
10321         ConstantInt *R1Val =
10322             EvaluateConstantChrecAtConstant(this, R1->getValue(), SE);
10323         if (Range.contains(R1Val->getValue())) {
10324           // The next iteration must be out of the range...
10325           ConstantInt *NextVal =
10326               ConstantInt::get(SE.getContext(), R1->getAPInt() + 1);
10327 
10328           R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
10329           if (!Range.contains(R1Val->getValue()))
10330             return SE.getConstant(NextVal);
10331           return SE.getCouldNotCompute(); // Something strange happened
10332         }
10333 
10334         // If R1 was not in the range, then it is a good return value.  Make
10335         // sure that R1-1 WAS in the range though, just in case.
10336         ConstantInt *NextVal =
10337             ConstantInt::get(SE.getContext(), R1->getAPInt() - 1);
10338         R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
10339         if (Range.contains(R1Val->getValue()))
10340           return R1;
10341         return SE.getCouldNotCompute(); // Something strange happened
10342       }
10343     }
10344   }
10345 
10346   return SE.getCouldNotCompute();
10347 }
10348 
10349 const SCEVAddRecExpr *
10350 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const {
10351   assert(getNumOperands() > 1 && "AddRec with zero step?");
10352   // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)),
10353   // but in this case we cannot guarantee that the value returned will be an
10354   // AddRec because SCEV does not have a fixed point where it stops
10355   // simplification: it is legal to return ({rec1} + {rec2}). For example, it
10356   // may happen if we reach arithmetic depth limit while simplifying. So we
10357   // construct the returned value explicitly.
10358   SmallVector<const SCEV *, 3> Ops;
10359   // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and
10360   // (this + Step) is {A+B,+,B+C,+...,+,N}.
10361   for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i)
10362     Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1)));
10363   // We know that the last operand is not a constant zero (otherwise it would
10364   // have been popped out earlier). This guarantees us that if the result has
10365   // the same last operand, then it will also not be popped out, meaning that
10366   // the returned value will be an AddRec.
10367   const SCEV *Last = getOperand(getNumOperands() - 1);
10368   assert(!Last->isZero() && "Recurrency with zero step?");
10369   Ops.push_back(Last);
10370   return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(),
10371                                                SCEV::FlagAnyWrap));
10372 }
10373 
10374 // Return true when S contains at least an undef value.
10375 static inline bool containsUndefs(const SCEV *S) {
10376   return SCEVExprContains(S, [](const SCEV *S) {
10377     if (const auto *SU = dyn_cast<SCEVUnknown>(S))
10378       return isa<UndefValue>(SU->getValue());
10379     else if (const auto *SC = dyn_cast<SCEVConstant>(S))
10380       return isa<UndefValue>(SC->getValue());
10381     return false;
10382   });
10383 }
10384 
10385 namespace {
10386 
10387 // Collect all steps of SCEV expressions.
10388 struct SCEVCollectStrides {
10389   ScalarEvolution &SE;
10390   SmallVectorImpl<const SCEV *> &Strides;
10391 
10392   SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S)
10393       : SE(SE), Strides(S) {}
10394 
10395   bool follow(const SCEV *S) {
10396     if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
10397       Strides.push_back(AR->getStepRecurrence(SE));
10398     return true;
10399   }
10400 
10401   bool isDone() const { return false; }
10402 };
10403 
10404 // Collect all SCEVUnknown and SCEVMulExpr expressions.
10405 struct SCEVCollectTerms {
10406   SmallVectorImpl<const SCEV *> &Terms;
10407 
10408   SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) : Terms(T) {}
10409 
10410   bool follow(const SCEV *S) {
10411     if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) ||
10412         isa<SCEVSignExtendExpr>(S)) {
10413       if (!containsUndefs(S))
10414         Terms.push_back(S);
10415 
10416       // Stop recursion: once we collected a term, do not walk its operands.
10417       return false;
10418     }
10419 
10420     // Keep looking.
10421     return true;
10422   }
10423 
10424   bool isDone() const { return false; }
10425 };
10426 
10427 // Check if a SCEV contains an AddRecExpr.
10428 struct SCEVHasAddRec {
10429   bool &ContainsAddRec;
10430 
10431   SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) {
10432     ContainsAddRec = false;
10433   }
10434 
10435   bool follow(const SCEV *S) {
10436     if (isa<SCEVAddRecExpr>(S)) {
10437       ContainsAddRec = true;
10438 
10439       // Stop recursion: once we collected a term, do not walk its operands.
10440       return false;
10441     }
10442 
10443     // Keep looking.
10444     return true;
10445   }
10446 
10447   bool isDone() const { return false; }
10448 };
10449 
10450 // Find factors that are multiplied with an expression that (possibly as a
10451 // subexpression) contains an AddRecExpr. In the expression:
10452 //
10453 //  8 * (100 +  %p * %q * (%a + {0, +, 1}_loop))
10454 //
10455 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)"
10456 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size
10457 // parameters as they form a product with an induction variable.
10458 //
10459 // This collector expects all array size parameters to be in the same MulExpr.
10460 // It might be necessary to later add support for collecting parameters that are
10461 // spread over different nested MulExpr.
10462 struct SCEVCollectAddRecMultiplies {
10463   SmallVectorImpl<const SCEV *> &Terms;
10464   ScalarEvolution &SE;
10465 
10466   SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE)
10467       : Terms(T), SE(SE) {}
10468 
10469   bool follow(const SCEV *S) {
10470     if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) {
10471       bool HasAddRec = false;
10472       SmallVector<const SCEV *, 0> Operands;
10473       for (auto Op : Mul->operands()) {
10474         const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op);
10475         if (Unknown && !isa<CallInst>(Unknown->getValue())) {
10476           Operands.push_back(Op);
10477         } else if (Unknown) {
10478           HasAddRec = true;
10479         } else {
10480           bool ContainsAddRec;
10481           SCEVHasAddRec ContiansAddRec(ContainsAddRec);
10482           visitAll(Op, ContiansAddRec);
10483           HasAddRec |= ContainsAddRec;
10484         }
10485       }
10486       if (Operands.size() == 0)
10487         return true;
10488 
10489       if (!HasAddRec)
10490         return false;
10491 
10492       Terms.push_back(SE.getMulExpr(Operands));
10493       // Stop recursion: once we collected a term, do not walk its operands.
10494       return false;
10495     }
10496 
10497     // Keep looking.
10498     return true;
10499   }
10500 
10501   bool isDone() const { return false; }
10502 };
10503 
10504 } // end anonymous namespace
10505 
10506 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in
10507 /// two places:
10508 ///   1) The strides of AddRec expressions.
10509 ///   2) Unknowns that are multiplied with AddRec expressions.
10510 void ScalarEvolution::collectParametricTerms(const SCEV *Expr,
10511     SmallVectorImpl<const SCEV *> &Terms) {
10512   SmallVector<const SCEV *, 4> Strides;
10513   SCEVCollectStrides StrideCollector(*this, Strides);
10514   visitAll(Expr, StrideCollector);
10515 
10516   DEBUG({
10517       dbgs() << "Strides:\n";
10518       for (const SCEV *S : Strides)
10519         dbgs() << *S << "\n";
10520     });
10521 
10522   for (const SCEV *S : Strides) {
10523     SCEVCollectTerms TermCollector(Terms);
10524     visitAll(S, TermCollector);
10525   }
10526 
10527   DEBUG({
10528       dbgs() << "Terms:\n";
10529       for (const SCEV *T : Terms)
10530         dbgs() << *T << "\n";
10531     });
10532 
10533   SCEVCollectAddRecMultiplies MulCollector(Terms, *this);
10534   visitAll(Expr, MulCollector);
10535 }
10536 
10537 static bool findArrayDimensionsRec(ScalarEvolution &SE,
10538                                    SmallVectorImpl<const SCEV *> &Terms,
10539                                    SmallVectorImpl<const SCEV *> &Sizes) {
10540   int Last = Terms.size() - 1;
10541   const SCEV *Step = Terms[Last];
10542 
10543   // End of recursion.
10544   if (Last == 0) {
10545     if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) {
10546       SmallVector<const SCEV *, 2> Qs;
10547       for (const SCEV *Op : M->operands())
10548         if (!isa<SCEVConstant>(Op))
10549           Qs.push_back(Op);
10550 
10551       Step = SE.getMulExpr(Qs);
10552     }
10553 
10554     Sizes.push_back(Step);
10555     return true;
10556   }
10557 
10558   for (const SCEV *&Term : Terms) {
10559     // Normalize the terms before the next call to findArrayDimensionsRec.
10560     const SCEV *Q, *R;
10561     SCEVDivision::divide(SE, Term, Step, &Q, &R);
10562 
10563     // Bail out when GCD does not evenly divide one of the terms.
10564     if (!R->isZero())
10565       return false;
10566 
10567     Term = Q;
10568   }
10569 
10570   // Remove all SCEVConstants.
10571   Terms.erase(
10572       remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }),
10573       Terms.end());
10574 
10575   if (Terms.size() > 0)
10576     if (!findArrayDimensionsRec(SE, Terms, Sizes))
10577       return false;
10578 
10579   Sizes.push_back(Step);
10580   return true;
10581 }
10582 
10583 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter.
10584 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) {
10585   for (const SCEV *T : Terms)
10586     if (SCEVExprContains(T, isa<SCEVUnknown, const SCEV *>))
10587       return true;
10588   return false;
10589 }
10590 
10591 // Return the number of product terms in S.
10592 static inline int numberOfTerms(const SCEV *S) {
10593   if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S))
10594     return Expr->getNumOperands();
10595   return 1;
10596 }
10597 
10598 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) {
10599   if (isa<SCEVConstant>(T))
10600     return nullptr;
10601 
10602   if (isa<SCEVUnknown>(T))
10603     return T;
10604 
10605   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) {
10606     SmallVector<const SCEV *, 2> Factors;
10607     for (const SCEV *Op : M->operands())
10608       if (!isa<SCEVConstant>(Op))
10609         Factors.push_back(Op);
10610 
10611     return SE.getMulExpr(Factors);
10612   }
10613 
10614   return T;
10615 }
10616 
10617 /// Return the size of an element read or written by Inst.
10618 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
10619   Type *Ty;
10620   if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
10621     Ty = Store->getValueOperand()->getType();
10622   else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
10623     Ty = Load->getType();
10624   else
10625     return nullptr;
10626 
10627   Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
10628   return getSizeOfExpr(ETy, Ty);
10629 }
10630 
10631 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
10632                                           SmallVectorImpl<const SCEV *> &Sizes,
10633                                           const SCEV *ElementSize) {
10634   if (Terms.size() < 1 || !ElementSize)
10635     return;
10636 
10637   // Early return when Terms do not contain parameters: we do not delinearize
10638   // non parametric SCEVs.
10639   if (!containsParameters(Terms))
10640     return;
10641 
10642   DEBUG({
10643       dbgs() << "Terms:\n";
10644       for (const SCEV *T : Terms)
10645         dbgs() << *T << "\n";
10646     });
10647 
10648   // Remove duplicates.
10649   array_pod_sort(Terms.begin(), Terms.end());
10650   Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end());
10651 
10652   // Put larger terms first.
10653   std::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) {
10654     return numberOfTerms(LHS) > numberOfTerms(RHS);
10655   });
10656 
10657   // Try to divide all terms by the element size. If term is not divisible by
10658   // element size, proceed with the original term.
10659   for (const SCEV *&Term : Terms) {
10660     const SCEV *Q, *R;
10661     SCEVDivision::divide(*this, Term, ElementSize, &Q, &R);
10662     if (!Q->isZero())
10663       Term = Q;
10664   }
10665 
10666   SmallVector<const SCEV *, 4> NewTerms;
10667 
10668   // Remove constant factors.
10669   for (const SCEV *T : Terms)
10670     if (const SCEV *NewT = removeConstantFactors(*this, T))
10671       NewTerms.push_back(NewT);
10672 
10673   DEBUG({
10674       dbgs() << "Terms after sorting:\n";
10675       for (const SCEV *T : NewTerms)
10676         dbgs() << *T << "\n";
10677     });
10678 
10679   if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) {
10680     Sizes.clear();
10681     return;
10682   }
10683 
10684   // The last element to be pushed into Sizes is the size of an element.
10685   Sizes.push_back(ElementSize);
10686 
10687   DEBUG({
10688       dbgs() << "Sizes:\n";
10689       for (const SCEV *S : Sizes)
10690         dbgs() << *S << "\n";
10691     });
10692 }
10693 
10694 void ScalarEvolution::computeAccessFunctions(
10695     const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts,
10696     SmallVectorImpl<const SCEV *> &Sizes) {
10697   // Early exit in case this SCEV is not an affine multivariate function.
10698   if (Sizes.empty())
10699     return;
10700 
10701   if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr))
10702     if (!AR->isAffine())
10703       return;
10704 
10705   const SCEV *Res = Expr;
10706   int Last = Sizes.size() - 1;
10707   for (int i = Last; i >= 0; i--) {
10708     const SCEV *Q, *R;
10709     SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R);
10710 
10711     DEBUG({
10712         dbgs() << "Res: " << *Res << "\n";
10713         dbgs() << "Sizes[i]: " << *Sizes[i] << "\n";
10714         dbgs() << "Res divided by Sizes[i]:\n";
10715         dbgs() << "Quotient: " << *Q << "\n";
10716         dbgs() << "Remainder: " << *R << "\n";
10717       });
10718 
10719     Res = Q;
10720 
10721     // Do not record the last subscript corresponding to the size of elements in
10722     // the array.
10723     if (i == Last) {
10724 
10725       // Bail out if the remainder is too complex.
10726       if (isa<SCEVAddRecExpr>(R)) {
10727         Subscripts.clear();
10728         Sizes.clear();
10729         return;
10730       }
10731 
10732       continue;
10733     }
10734 
10735     // Record the access function for the current subscript.
10736     Subscripts.push_back(R);
10737   }
10738 
10739   // Also push in last position the remainder of the last division: it will be
10740   // the access function of the innermost dimension.
10741   Subscripts.push_back(Res);
10742 
10743   std::reverse(Subscripts.begin(), Subscripts.end());
10744 
10745   DEBUG({
10746       dbgs() << "Subscripts:\n";
10747       for (const SCEV *S : Subscripts)
10748         dbgs() << *S << "\n";
10749     });
10750 }
10751 
10752 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and
10753 /// sizes of an array access. Returns the remainder of the delinearization that
10754 /// is the offset start of the array.  The SCEV->delinearize algorithm computes
10755 /// the multiples of SCEV coefficients: that is a pattern matching of sub
10756 /// expressions in the stride and base of a SCEV corresponding to the
10757 /// computation of a GCD (greatest common divisor) of base and stride.  When
10758 /// SCEV->delinearize fails, it returns the SCEV unchanged.
10759 ///
10760 /// For example: when analyzing the memory access A[i][j][k] in this loop nest
10761 ///
10762 ///  void foo(long n, long m, long o, double A[n][m][o]) {
10763 ///
10764 ///    for (long i = 0; i < n; i++)
10765 ///      for (long j = 0; j < m; j++)
10766 ///        for (long k = 0; k < o; k++)
10767 ///          A[i][j][k] = 1.0;
10768 ///  }
10769 ///
10770 /// the delinearization input is the following AddRec SCEV:
10771 ///
10772 ///  AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k>
10773 ///
10774 /// From this SCEV, we are able to say that the base offset of the access is %A
10775 /// because it appears as an offset that does not divide any of the strides in
10776 /// the loops:
10777 ///
10778 ///  CHECK: Base offset: %A
10779 ///
10780 /// and then SCEV->delinearize determines the size of some of the dimensions of
10781 /// the array as these are the multiples by which the strides are happening:
10782 ///
10783 ///  CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes.
10784 ///
10785 /// Note that the outermost dimension remains of UnknownSize because there are
10786 /// no strides that would help identifying the size of the last dimension: when
10787 /// the array has been statically allocated, one could compute the size of that
10788 /// dimension by dividing the overall size of the array by the size of the known
10789 /// dimensions: %m * %o * 8.
10790 ///
10791 /// Finally delinearize provides the access functions for the array reference
10792 /// that does correspond to A[i][j][k] of the above C testcase:
10793 ///
10794 ///  CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>]
10795 ///
10796 /// The testcases are checking the output of a function pass:
10797 /// DelinearizationPass that walks through all loads and stores of a function
10798 /// asking for the SCEV of the memory access with respect to all enclosing
10799 /// loops, calling SCEV->delinearize on that and printing the results.
10800 void ScalarEvolution::delinearize(const SCEV *Expr,
10801                                  SmallVectorImpl<const SCEV *> &Subscripts,
10802                                  SmallVectorImpl<const SCEV *> &Sizes,
10803                                  const SCEV *ElementSize) {
10804   // First step: collect parametric terms.
10805   SmallVector<const SCEV *, 4> Terms;
10806   collectParametricTerms(Expr, Terms);
10807 
10808   if (Terms.empty())
10809     return;
10810 
10811   // Second step: find subscript sizes.
10812   findArrayDimensions(Terms, Sizes, ElementSize);
10813 
10814   if (Sizes.empty())
10815     return;
10816 
10817   // Third step: compute the access functions for each subscript.
10818   computeAccessFunctions(Expr, Subscripts, Sizes);
10819 
10820   if (Subscripts.empty())
10821     return;
10822 
10823   DEBUG({
10824       dbgs() << "succeeded to delinearize " << *Expr << "\n";
10825       dbgs() << "ArrayDecl[UnknownSize]";
10826       for (const SCEV *S : Sizes)
10827         dbgs() << "[" << *S << "]";
10828 
10829       dbgs() << "\nArrayRef";
10830       for (const SCEV *S : Subscripts)
10831         dbgs() << "[" << *S << "]";
10832       dbgs() << "\n";
10833     });
10834 }
10835 
10836 //===----------------------------------------------------------------------===//
10837 //                   SCEVCallbackVH Class Implementation
10838 //===----------------------------------------------------------------------===//
10839 
10840 void ScalarEvolution::SCEVCallbackVH::deleted() {
10841   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
10842   if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
10843     SE->ConstantEvolutionLoopExitValue.erase(PN);
10844   SE->eraseValueFromMap(getValPtr());
10845   // this now dangles!
10846 }
10847 
10848 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
10849   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
10850 
10851   // Forget all the expressions associated with users of the old value,
10852   // so that future queries will recompute the expressions using the new
10853   // value.
10854   Value *Old = getValPtr();
10855   SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end());
10856   SmallPtrSet<User *, 8> Visited;
10857   while (!Worklist.empty()) {
10858     User *U = Worklist.pop_back_val();
10859     // Deleting the Old value will cause this to dangle. Postpone
10860     // that until everything else is done.
10861     if (U == Old)
10862       continue;
10863     if (!Visited.insert(U).second)
10864       continue;
10865     if (PHINode *PN = dyn_cast<PHINode>(U))
10866       SE->ConstantEvolutionLoopExitValue.erase(PN);
10867     SE->eraseValueFromMap(U);
10868     Worklist.insert(Worklist.end(), U->user_begin(), U->user_end());
10869   }
10870   // Delete the Old value.
10871   if (PHINode *PN = dyn_cast<PHINode>(Old))
10872     SE->ConstantEvolutionLoopExitValue.erase(PN);
10873   SE->eraseValueFromMap(Old);
10874   // this now dangles!
10875 }
10876 
10877 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
10878   : CallbackVH(V), SE(se) {}
10879 
10880 //===----------------------------------------------------------------------===//
10881 //                   ScalarEvolution Class Implementation
10882 //===----------------------------------------------------------------------===//
10883 
10884 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
10885                                  AssumptionCache &AC, DominatorTree &DT,
10886                                  LoopInfo &LI)
10887     : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
10888       CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64),
10889       LoopDispositions(64), BlockDispositions(64) {
10890   // To use guards for proving predicates, we need to scan every instruction in
10891   // relevant basic blocks, and not just terminators.  Doing this is a waste of
10892   // time if the IR does not actually contain any calls to
10893   // @llvm.experimental.guard, so do a quick check and remember this beforehand.
10894   //
10895   // This pessimizes the case where a pass that preserves ScalarEvolution wants
10896   // to _add_ guards to the module when there weren't any before, and wants
10897   // ScalarEvolution to optimize based on those guards.  For now we prefer to be
10898   // efficient in lieu of being smart in that rather obscure case.
10899 
10900   auto *GuardDecl = F.getParent()->getFunction(
10901       Intrinsic::getName(Intrinsic::experimental_guard));
10902   HasGuards = GuardDecl && !GuardDecl->use_empty();
10903 }
10904 
10905 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
10906     : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT),
10907       LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
10908       ValueExprMap(std::move(Arg.ValueExprMap)),
10909       PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
10910       PendingPhiRanges(std::move(Arg.PendingPhiRanges)),
10911       MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)),
10912       BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
10913       PredicatedBackedgeTakenCounts(
10914           std::move(Arg.PredicatedBackedgeTakenCounts)),
10915       ConstantEvolutionLoopExitValue(
10916           std::move(Arg.ConstantEvolutionLoopExitValue)),
10917       ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
10918       LoopDispositions(std::move(Arg.LoopDispositions)),
10919       LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
10920       BlockDispositions(std::move(Arg.BlockDispositions)),
10921       UnsignedRanges(std::move(Arg.UnsignedRanges)),
10922       SignedRanges(std::move(Arg.SignedRanges)),
10923       UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
10924       UniquePreds(std::move(Arg.UniquePreds)),
10925       SCEVAllocator(std::move(Arg.SCEVAllocator)),
10926       LoopUsers(std::move(Arg.LoopUsers)),
10927       PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)),
10928       FirstUnknown(Arg.FirstUnknown) {
10929   Arg.FirstUnknown = nullptr;
10930 }
10931 
10932 ScalarEvolution::~ScalarEvolution() {
10933   // Iterate through all the SCEVUnknown instances and call their
10934   // destructors, so that they release their references to their values.
10935   for (SCEVUnknown *U = FirstUnknown; U;) {
10936     SCEVUnknown *Tmp = U;
10937     U = U->Next;
10938     Tmp->~SCEVUnknown();
10939   }
10940   FirstUnknown = nullptr;
10941 
10942   ExprValueMap.clear();
10943   ValueExprMap.clear();
10944   HasRecMap.clear();
10945 
10946   // Free any extra memory created for ExitNotTakenInfo in the unlikely event
10947   // that a loop had multiple computable exits.
10948   for (auto &BTCI : BackedgeTakenCounts)
10949     BTCI.second.clear();
10950   for (auto &BTCI : PredicatedBackedgeTakenCounts)
10951     BTCI.second.clear();
10952 
10953   assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
10954   assert(PendingPhiRanges.empty() && "getRangeRef garbage");
10955   assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
10956   assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
10957 }
10958 
10959 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
10960   return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
10961 }
10962 
10963 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
10964                           const Loop *L) {
10965   // Print all inner loops first
10966   for (Loop *I : *L)
10967     PrintLoopInfo(OS, SE, I);
10968 
10969   OS << "Loop ";
10970   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
10971   OS << ": ";
10972 
10973   SmallVector<BasicBlock *, 8> ExitBlocks;
10974   L->getExitBlocks(ExitBlocks);
10975   if (ExitBlocks.size() != 1)
10976     OS << "<multiple exits> ";
10977 
10978   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
10979     OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
10980   } else {
10981     OS << "Unpredictable backedge-taken count. ";
10982   }
10983 
10984   OS << "\n"
10985         "Loop ";
10986   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
10987   OS << ": ";
10988 
10989   if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
10990     OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
10991     if (SE->isBackedgeTakenCountMaxOrZero(L))
10992       OS << ", actual taken count either this or zero.";
10993   } else {
10994     OS << "Unpredictable max backedge-taken count. ";
10995   }
10996 
10997   OS << "\n"
10998         "Loop ";
10999   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
11000   OS << ": ";
11001 
11002   SCEVUnionPredicate Pred;
11003   auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred);
11004   if (!isa<SCEVCouldNotCompute>(PBT)) {
11005     OS << "Predicated backedge-taken count is " << *PBT << "\n";
11006     OS << " Predicates:\n";
11007     Pred.print(OS, 4);
11008   } else {
11009     OS << "Unpredictable predicated backedge-taken count. ";
11010   }
11011   OS << "\n";
11012 
11013   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
11014     OS << "Loop ";
11015     L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
11016     OS << ": ";
11017     OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
11018   }
11019 }
11020 
11021 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) {
11022   switch (LD) {
11023   case ScalarEvolution::LoopVariant:
11024     return "Variant";
11025   case ScalarEvolution::LoopInvariant:
11026     return "Invariant";
11027   case ScalarEvolution::LoopComputable:
11028     return "Computable";
11029   }
11030   llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!");
11031 }
11032 
11033 void ScalarEvolution::print(raw_ostream &OS) const {
11034   // ScalarEvolution's implementation of the print method is to print
11035   // out SCEV values of all instructions that are interesting. Doing
11036   // this potentially causes it to create new SCEV objects though,
11037   // which technically conflicts with the const qualifier. This isn't
11038   // observable from outside the class though, so casting away the
11039   // const isn't dangerous.
11040   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
11041 
11042   OS << "Classifying expressions for: ";
11043   F.printAsOperand(OS, /*PrintType=*/false);
11044   OS << "\n";
11045   for (Instruction &I : instructions(F))
11046     if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
11047       OS << I << '\n';
11048       OS << "  -->  ";
11049       const SCEV *SV = SE.getSCEV(&I);
11050       SV->print(OS);
11051       if (!isa<SCEVCouldNotCompute>(SV)) {
11052         OS << " U: ";
11053         SE.getUnsignedRange(SV).print(OS);
11054         OS << " S: ";
11055         SE.getSignedRange(SV).print(OS);
11056       }
11057 
11058       const Loop *L = LI.getLoopFor(I.getParent());
11059 
11060       const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
11061       if (AtUse != SV) {
11062         OS << "  -->  ";
11063         AtUse->print(OS);
11064         if (!isa<SCEVCouldNotCompute>(AtUse)) {
11065           OS << " U: ";
11066           SE.getUnsignedRange(AtUse).print(OS);
11067           OS << " S: ";
11068           SE.getSignedRange(AtUse).print(OS);
11069         }
11070       }
11071 
11072       if (L) {
11073         OS << "\t\t" "Exits: ";
11074         const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
11075         if (!SE.isLoopInvariant(ExitValue, L)) {
11076           OS << "<<Unknown>>";
11077         } else {
11078           OS << *ExitValue;
11079         }
11080 
11081         bool First = true;
11082         for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
11083           if (First) {
11084             OS << "\t\t" "LoopDispositions: { ";
11085             First = false;
11086           } else {
11087             OS << ", ";
11088           }
11089 
11090           Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
11091           OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter));
11092         }
11093 
11094         for (auto *InnerL : depth_first(L)) {
11095           if (InnerL == L)
11096             continue;
11097           if (First) {
11098             OS << "\t\t" "LoopDispositions: { ";
11099             First = false;
11100           } else {
11101             OS << ", ";
11102           }
11103 
11104           InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
11105           OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL));
11106         }
11107 
11108         OS << " }";
11109       }
11110 
11111       OS << "\n";
11112     }
11113 
11114   OS << "Determining loop execution counts for: ";
11115   F.printAsOperand(OS, /*PrintType=*/false);
11116   OS << "\n";
11117   for (Loop *I : LI)
11118     PrintLoopInfo(OS, &SE, I);
11119 }
11120 
11121 ScalarEvolution::LoopDisposition
11122 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
11123   auto &Values = LoopDispositions[S];
11124   for (auto &V : Values) {
11125     if (V.getPointer() == L)
11126       return V.getInt();
11127   }
11128   Values.emplace_back(L, LoopVariant);
11129   LoopDisposition D = computeLoopDisposition(S, L);
11130   auto &Values2 = LoopDispositions[S];
11131   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
11132     if (V.getPointer() == L) {
11133       V.setInt(D);
11134       break;
11135     }
11136   }
11137   return D;
11138 }
11139 
11140 ScalarEvolution::LoopDisposition
11141 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
11142   switch (static_cast<SCEVTypes>(S->getSCEVType())) {
11143   case scConstant:
11144     return LoopInvariant;
11145   case scTruncate:
11146   case scZeroExtend:
11147   case scSignExtend:
11148     return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
11149   case scAddRecExpr: {
11150     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
11151 
11152     // If L is the addrec's loop, it's computable.
11153     if (AR->getLoop() == L)
11154       return LoopComputable;
11155 
11156     // Add recurrences are never invariant in the function-body (null loop).
11157     if (!L)
11158       return LoopVariant;
11159 
11160     // Everything that is not defined at loop entry is variant.
11161     if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader()))
11162       return LoopVariant;
11163     assert(!L->contains(AR->getLoop()) && "Containing loop's header does not"
11164            " dominate the contained loop's header?");
11165 
11166     // This recurrence is invariant w.r.t. L if AR's loop contains L.
11167     if (AR->getLoop()->contains(L))
11168       return LoopInvariant;
11169 
11170     // This recurrence is variant w.r.t. L if any of its operands
11171     // are variant.
11172     for (auto *Op : AR->operands())
11173       if (!isLoopInvariant(Op, L))
11174         return LoopVariant;
11175 
11176     // Otherwise it's loop-invariant.
11177     return LoopInvariant;
11178   }
11179   case scAddExpr:
11180   case scMulExpr:
11181   case scUMaxExpr:
11182   case scSMaxExpr: {
11183     bool HasVarying = false;
11184     for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) {
11185       LoopDisposition D = getLoopDisposition(Op, L);
11186       if (D == LoopVariant)
11187         return LoopVariant;
11188       if (D == LoopComputable)
11189         HasVarying = true;
11190     }
11191     return HasVarying ? LoopComputable : LoopInvariant;
11192   }
11193   case scUDivExpr: {
11194     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
11195     LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
11196     if (LD == LoopVariant)
11197       return LoopVariant;
11198     LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
11199     if (RD == LoopVariant)
11200       return LoopVariant;
11201     return (LD == LoopInvariant && RD == LoopInvariant) ?
11202            LoopInvariant : LoopComputable;
11203   }
11204   case scUnknown:
11205     // All non-instruction values are loop invariant.  All instructions are loop
11206     // invariant if they are not contained in the specified loop.
11207     // Instructions are never considered invariant in the function body
11208     // (null loop) because they are defined within the "loop".
11209     if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
11210       return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
11211     return LoopInvariant;
11212   case scCouldNotCompute:
11213     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
11214   }
11215   llvm_unreachable("Unknown SCEV kind!");
11216 }
11217 
11218 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
11219   return getLoopDisposition(S, L) == LoopInvariant;
11220 }
11221 
11222 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
11223   return getLoopDisposition(S, L) == LoopComputable;
11224 }
11225 
11226 ScalarEvolution::BlockDisposition
11227 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
11228   auto &Values = BlockDispositions[S];
11229   for (auto &V : Values) {
11230     if (V.getPointer() == BB)
11231       return V.getInt();
11232   }
11233   Values.emplace_back(BB, DoesNotDominateBlock);
11234   BlockDisposition D = computeBlockDisposition(S, BB);
11235   auto &Values2 = BlockDispositions[S];
11236   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
11237     if (V.getPointer() == BB) {
11238       V.setInt(D);
11239       break;
11240     }
11241   }
11242   return D;
11243 }
11244 
11245 ScalarEvolution::BlockDisposition
11246 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
11247   switch (static_cast<SCEVTypes>(S->getSCEVType())) {
11248   case scConstant:
11249     return ProperlyDominatesBlock;
11250   case scTruncate:
11251   case scZeroExtend:
11252   case scSignExtend:
11253     return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
11254   case scAddRecExpr: {
11255     // This uses a "dominates" query instead of "properly dominates" query
11256     // to test for proper dominance too, because the instruction which
11257     // produces the addrec's value is a PHI, and a PHI effectively properly
11258     // dominates its entire containing block.
11259     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
11260     if (!DT.dominates(AR->getLoop()->getHeader(), BB))
11261       return DoesNotDominateBlock;
11262 
11263     // Fall through into SCEVNAryExpr handling.
11264     LLVM_FALLTHROUGH;
11265   }
11266   case scAddExpr:
11267   case scMulExpr:
11268   case scUMaxExpr:
11269   case scSMaxExpr: {
11270     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
11271     bool Proper = true;
11272     for (const SCEV *NAryOp : NAry->operands()) {
11273       BlockDisposition D = getBlockDisposition(NAryOp, BB);
11274       if (D == DoesNotDominateBlock)
11275         return DoesNotDominateBlock;
11276       if (D == DominatesBlock)
11277         Proper = false;
11278     }
11279     return Proper ? ProperlyDominatesBlock : DominatesBlock;
11280   }
11281   case scUDivExpr: {
11282     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
11283     const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
11284     BlockDisposition LD = getBlockDisposition(LHS, BB);
11285     if (LD == DoesNotDominateBlock)
11286       return DoesNotDominateBlock;
11287     BlockDisposition RD = getBlockDisposition(RHS, BB);
11288     if (RD == DoesNotDominateBlock)
11289       return DoesNotDominateBlock;
11290     return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
11291       ProperlyDominatesBlock : DominatesBlock;
11292   }
11293   case scUnknown:
11294     if (Instruction *I =
11295           dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
11296       if (I->getParent() == BB)
11297         return DominatesBlock;
11298       if (DT.properlyDominates(I->getParent(), BB))
11299         return ProperlyDominatesBlock;
11300       return DoesNotDominateBlock;
11301     }
11302     return ProperlyDominatesBlock;
11303   case scCouldNotCompute:
11304     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
11305   }
11306   llvm_unreachable("Unknown SCEV kind!");
11307 }
11308 
11309 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
11310   return getBlockDisposition(S, BB) >= DominatesBlock;
11311 }
11312 
11313 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
11314   return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
11315 }
11316 
11317 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
11318   return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; });
11319 }
11320 
11321 bool ScalarEvolution::ExitLimit::hasOperand(const SCEV *S) const {
11322   auto IsS = [&](const SCEV *X) { return S == X; };
11323   auto ContainsS = [&](const SCEV *X) {
11324     return !isa<SCEVCouldNotCompute>(X) && SCEVExprContains(X, IsS);
11325   };
11326   return ContainsS(ExactNotTaken) || ContainsS(MaxNotTaken);
11327 }
11328 
11329 void
11330 ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
11331   ValuesAtScopes.erase(S);
11332   LoopDispositions.erase(S);
11333   BlockDispositions.erase(S);
11334   UnsignedRanges.erase(S);
11335   SignedRanges.erase(S);
11336   ExprValueMap.erase(S);
11337   HasRecMap.erase(S);
11338   MinTrailingZerosCache.erase(S);
11339 
11340   for (auto I = PredicatedSCEVRewrites.begin();
11341        I != PredicatedSCEVRewrites.end();) {
11342     std::pair<const SCEV *, const Loop *> Entry = I->first;
11343     if (Entry.first == S)
11344       PredicatedSCEVRewrites.erase(I++);
11345     else
11346       ++I;
11347   }
11348 
11349   auto RemoveSCEVFromBackedgeMap =
11350       [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
11351         for (auto I = Map.begin(), E = Map.end(); I != E;) {
11352           BackedgeTakenInfo &BEInfo = I->second;
11353           if (BEInfo.hasOperand(S, this)) {
11354             BEInfo.clear();
11355             Map.erase(I++);
11356           } else
11357             ++I;
11358         }
11359       };
11360 
11361   RemoveSCEVFromBackedgeMap(BackedgeTakenCounts);
11362   RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts);
11363 }
11364 
11365 void
11366 ScalarEvolution::getUsedLoops(const SCEV *S,
11367                               SmallPtrSetImpl<const Loop *> &LoopsUsed) {
11368   struct FindUsedLoops {
11369     FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed)
11370         : LoopsUsed(LoopsUsed) {}
11371     SmallPtrSetImpl<const Loop *> &LoopsUsed;
11372     bool follow(const SCEV *S) {
11373       if (auto *AR = dyn_cast<SCEVAddRecExpr>(S))
11374         LoopsUsed.insert(AR->getLoop());
11375       return true;
11376     }
11377 
11378     bool isDone() const { return false; }
11379   };
11380 
11381   FindUsedLoops F(LoopsUsed);
11382   SCEVTraversal<FindUsedLoops>(F).visitAll(S);
11383 }
11384 
11385 void ScalarEvolution::addToLoopUseLists(const SCEV *S) {
11386   SmallPtrSet<const Loop *, 8> LoopsUsed;
11387   getUsedLoops(S, LoopsUsed);
11388   for (auto *L : LoopsUsed)
11389     LoopUsers[L].push_back(S);
11390 }
11391 
11392 void ScalarEvolution::verify() const {
11393   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
11394   ScalarEvolution SE2(F, TLI, AC, DT, LI);
11395 
11396   SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end());
11397 
11398   // Map's SCEV expressions from one ScalarEvolution "universe" to another.
11399   struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> {
11400     SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {}
11401 
11402     const SCEV *visitConstant(const SCEVConstant *Constant) {
11403       return SE.getConstant(Constant->getAPInt());
11404     }
11405 
11406     const SCEV *visitUnknown(const SCEVUnknown *Expr) {
11407       return SE.getUnknown(Expr->getValue());
11408     }
11409 
11410     const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
11411       return SE.getCouldNotCompute();
11412     }
11413   };
11414 
11415   SCEVMapper SCM(SE2);
11416 
11417   while (!LoopStack.empty()) {
11418     auto *L = LoopStack.pop_back_val();
11419     LoopStack.insert(LoopStack.end(), L->begin(), L->end());
11420 
11421     auto *CurBECount = SCM.visit(
11422         const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L));
11423     auto *NewBECount = SE2.getBackedgeTakenCount(L);
11424 
11425     if (CurBECount == SE2.getCouldNotCompute() ||
11426         NewBECount == SE2.getCouldNotCompute()) {
11427       // NB! This situation is legal, but is very suspicious -- whatever pass
11428       // change the loop to make a trip count go from could not compute to
11429       // computable or vice-versa *should have* invalidated SCEV.  However, we
11430       // choose not to assert here (for now) since we don't want false
11431       // positives.
11432       continue;
11433     }
11434 
11435     if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) {
11436       // SCEV treats "undef" as an unknown but consistent value (i.e. it does
11437       // not propagate undef aggressively).  This means we can (and do) fail
11438       // verification in cases where a transform makes the trip count of a loop
11439       // go from "undef" to "undef+1" (say).  The transform is fine, since in
11440       // both cases the loop iterates "undef" times, but SCEV thinks we
11441       // increased the trip count of the loop by 1 incorrectly.
11442       continue;
11443     }
11444 
11445     if (SE.getTypeSizeInBits(CurBECount->getType()) >
11446         SE.getTypeSizeInBits(NewBECount->getType()))
11447       NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType());
11448     else if (SE.getTypeSizeInBits(CurBECount->getType()) <
11449              SE.getTypeSizeInBits(NewBECount->getType()))
11450       CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType());
11451 
11452     auto *ConstantDelta =
11453         dyn_cast<SCEVConstant>(SE2.getMinusSCEV(CurBECount, NewBECount));
11454 
11455     if (ConstantDelta && ConstantDelta->getAPInt() != 0) {
11456       dbgs() << "Trip Count Changed!\n";
11457       dbgs() << "Old: " << *CurBECount << "\n";
11458       dbgs() << "New: " << *NewBECount << "\n";
11459       dbgs() << "Delta: " << *ConstantDelta << "\n";
11460       std::abort();
11461     }
11462   }
11463 }
11464 
11465 bool ScalarEvolution::invalidate(
11466     Function &F, const PreservedAnalyses &PA,
11467     FunctionAnalysisManager::Invalidator &Inv) {
11468   // Invalidate the ScalarEvolution object whenever it isn't preserved or one
11469   // of its dependencies is invalidated.
11470   auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
11471   return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
11472          Inv.invalidate<AssumptionAnalysis>(F, PA) ||
11473          Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
11474          Inv.invalidate<LoopAnalysis>(F, PA);
11475 }
11476 
11477 AnalysisKey ScalarEvolutionAnalysis::Key;
11478 
11479 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
11480                                              FunctionAnalysisManager &AM) {
11481   return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F),
11482                          AM.getResult<AssumptionAnalysis>(F),
11483                          AM.getResult<DominatorTreeAnalysis>(F),
11484                          AM.getResult<LoopAnalysis>(F));
11485 }
11486 
11487 PreservedAnalyses
11488 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
11489   AM.getResult<ScalarEvolutionAnalysis>(F).print(OS);
11490   return PreservedAnalyses::all();
11491 }
11492 
11493 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
11494                       "Scalar Evolution Analysis", false, true)
11495 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
11496 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
11497 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
11498 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
11499 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
11500                     "Scalar Evolution Analysis", false, true)
11501 
11502 char ScalarEvolutionWrapperPass::ID = 0;
11503 
11504 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
11505   initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
11506 }
11507 
11508 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
11509   SE.reset(new ScalarEvolution(
11510       F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
11511       getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
11512       getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
11513       getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
11514   return false;
11515 }
11516 
11517 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
11518 
11519 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
11520   SE->print(OS);
11521 }
11522 
11523 void ScalarEvolutionWrapperPass::verifyAnalysis() const {
11524   if (!VerifySCEV)
11525     return;
11526 
11527   SE->verify();
11528 }
11529 
11530 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
11531   AU.setPreservesAll();
11532   AU.addRequiredTransitive<AssumptionCacheTracker>();
11533   AU.addRequiredTransitive<LoopInfoWrapperPass>();
11534   AU.addRequiredTransitive<DominatorTreeWrapperPass>();
11535   AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
11536 }
11537 
11538 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS,
11539                                                         const SCEV *RHS) {
11540   FoldingSetNodeID ID;
11541   assert(LHS->getType() == RHS->getType() &&
11542          "Type mismatch between LHS and RHS");
11543   // Unique this node based on the arguments
11544   ID.AddInteger(SCEVPredicate::P_Equal);
11545   ID.AddPointer(LHS);
11546   ID.AddPointer(RHS);
11547   void *IP = nullptr;
11548   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
11549     return S;
11550   SCEVEqualPredicate *Eq = new (SCEVAllocator)
11551       SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS);
11552   UniquePreds.InsertNode(Eq, IP);
11553   return Eq;
11554 }
11555 
11556 const SCEVPredicate *ScalarEvolution::getWrapPredicate(
11557     const SCEVAddRecExpr *AR,
11558     SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
11559   FoldingSetNodeID ID;
11560   // Unique this node based on the arguments
11561   ID.AddInteger(SCEVPredicate::P_Wrap);
11562   ID.AddPointer(AR);
11563   ID.AddInteger(AddedFlags);
11564   void *IP = nullptr;
11565   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
11566     return S;
11567   auto *OF = new (SCEVAllocator)
11568       SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
11569   UniquePreds.InsertNode(OF, IP);
11570   return OF;
11571 }
11572 
11573 namespace {
11574 
11575 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
11576 public:
11577 
11578   /// Rewrites \p S in the context of a loop L and the SCEV predication
11579   /// infrastructure.
11580   ///
11581   /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
11582   /// equivalences present in \p Pred.
11583   ///
11584   /// If \p NewPreds is non-null, rewrite is free to add further predicates to
11585   /// \p NewPreds such that the result will be an AddRecExpr.
11586   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
11587                              SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
11588                              SCEVUnionPredicate *Pred) {
11589     SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
11590     return Rewriter.visit(S);
11591   }
11592 
11593   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
11594     if (Pred) {
11595       auto ExprPreds = Pred->getPredicatesForExpr(Expr);
11596       for (auto *Pred : ExprPreds)
11597         if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred))
11598           if (IPred->getLHS() == Expr)
11599             return IPred->getRHS();
11600     }
11601     return convertToAddRecWithPreds(Expr);
11602   }
11603 
11604   const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
11605     const SCEV *Operand = visit(Expr->getOperand());
11606     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
11607     if (AR && AR->getLoop() == L && AR->isAffine()) {
11608       // This couldn't be folded because the operand didn't have the nuw
11609       // flag. Add the nusw flag as an assumption that we could make.
11610       const SCEV *Step = AR->getStepRecurrence(SE);
11611       Type *Ty = Expr->getType();
11612       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
11613         return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
11614                                 SE.getSignExtendExpr(Step, Ty), L,
11615                                 AR->getNoWrapFlags());
11616     }
11617     return SE.getZeroExtendExpr(Operand, Expr->getType());
11618   }
11619 
11620   const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
11621     const SCEV *Operand = visit(Expr->getOperand());
11622     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
11623     if (AR && AR->getLoop() == L && AR->isAffine()) {
11624       // This couldn't be folded because the operand didn't have the nsw
11625       // flag. Add the nssw flag as an assumption that we could make.
11626       const SCEV *Step = AR->getStepRecurrence(SE);
11627       Type *Ty = Expr->getType();
11628       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
11629         return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
11630                                 SE.getSignExtendExpr(Step, Ty), L,
11631                                 AR->getNoWrapFlags());
11632     }
11633     return SE.getSignExtendExpr(Operand, Expr->getType());
11634   }
11635 
11636 private:
11637   explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE,
11638                         SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
11639                         SCEVUnionPredicate *Pred)
11640       : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
11641 
11642   bool addOverflowAssumption(const SCEVPredicate *P) {
11643     if (!NewPreds) {
11644       // Check if we've already made this assumption.
11645       return Pred && Pred->implies(P);
11646     }
11647     NewPreds->insert(P);
11648     return true;
11649   }
11650 
11651   bool addOverflowAssumption(const SCEVAddRecExpr *AR,
11652                              SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
11653     auto *A = SE.getWrapPredicate(AR, AddedFlags);
11654     return addOverflowAssumption(A);
11655   }
11656 
11657   // If \p Expr represents a PHINode, we try to see if it can be represented
11658   // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible
11659   // to add this predicate as a runtime overflow check, we return the AddRec.
11660   // If \p Expr does not meet these conditions (is not a PHI node, or we
11661   // couldn't create an AddRec for it, or couldn't add the predicate), we just
11662   // return \p Expr.
11663   const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) {
11664     if (!VersionUnknown)
11665       return Expr;
11666     if (!isa<PHINode>(Expr->getValue()))
11667       return Expr;
11668     Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
11669     PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr);
11670     if (!PredicatedRewrite)
11671       return Expr;
11672     for (auto *P : PredicatedRewrite->second){
11673       // Wrap predicates from outer loops are not supported.
11674       if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) {
11675         auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr());
11676         if (L != AR->getLoop())
11677           return Expr;
11678       }
11679       if (!addOverflowAssumption(P))
11680         return Expr;
11681     }
11682     return PredicatedRewrite->first;
11683   }
11684 
11685   SmallPtrSetImpl<const SCEVPredicate *> *NewPreds;
11686   SCEVUnionPredicate *Pred;
11687   const Loop *L;
11688 };
11689 
11690 } // end anonymous namespace
11691 
11692 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
11693                                                    SCEVUnionPredicate &Preds) {
11694   return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
11695 }
11696 
11697 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates(
11698     const SCEV *S, const Loop *L,
11699     SmallPtrSetImpl<const SCEVPredicate *> &Preds) {
11700   SmallPtrSet<const SCEVPredicate *, 4> TransformPreds;
11701   S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
11702   auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
11703 
11704   if (!AddRec)
11705     return nullptr;
11706 
11707   // Since the transformation was successful, we can now transfer the SCEV
11708   // predicates.
11709   for (auto *P : TransformPreds)
11710     Preds.insert(P);
11711 
11712   return AddRec;
11713 }
11714 
11715 /// SCEV predicates
11716 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
11717                              SCEVPredicateKind Kind)
11718     : FastID(ID), Kind(Kind) {}
11719 
11720 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID,
11721                                        const SCEV *LHS, const SCEV *RHS)
11722     : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {
11723   assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match");
11724   assert(LHS != RHS && "LHS and RHS are the same SCEV");
11725 }
11726 
11727 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const {
11728   const auto *Op = dyn_cast<SCEVEqualPredicate>(N);
11729 
11730   if (!Op)
11731     return false;
11732 
11733   return Op->LHS == LHS && Op->RHS == RHS;
11734 }
11735 
11736 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; }
11737 
11738 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; }
11739 
11740 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const {
11741   OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
11742 }
11743 
11744 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
11745                                      const SCEVAddRecExpr *AR,
11746                                      IncrementWrapFlags Flags)
11747     : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
11748 
11749 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; }
11750 
11751 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const {
11752   const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
11753 
11754   return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags;
11755 }
11756 
11757 bool SCEVWrapPredicate::isAlwaysTrue() const {
11758   SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
11759   IncrementWrapFlags IFlags = Flags;
11760 
11761   if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
11762     IFlags = clearFlags(IFlags, IncrementNSSW);
11763 
11764   return IFlags == IncrementAnyWrap;
11765 }
11766 
11767 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
11768   OS.indent(Depth) << *getExpr() << " Added Flags: ";
11769   if (SCEVWrapPredicate::IncrementNUSW & getFlags())
11770     OS << "<nusw>";
11771   if (SCEVWrapPredicate::IncrementNSSW & getFlags())
11772     OS << "<nssw>";
11773   OS << "\n";
11774 }
11775 
11776 SCEVWrapPredicate::IncrementWrapFlags
11777 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR,
11778                                    ScalarEvolution &SE) {
11779   IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
11780   SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
11781 
11782   // We can safely transfer the NSW flag as NSSW.
11783   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
11784     ImpliedFlags = IncrementNSSW;
11785 
11786   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
11787     // If the increment is positive, the SCEV NUW flag will also imply the
11788     // WrapPredicate NUSW flag.
11789     if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
11790       if (Step->getValue()->getValue().isNonNegative())
11791         ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
11792   }
11793 
11794   return ImpliedFlags;
11795 }
11796 
11797 /// Union predicates don't get cached so create a dummy set ID for it.
11798 SCEVUnionPredicate::SCEVUnionPredicate()
11799     : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {}
11800 
11801 bool SCEVUnionPredicate::isAlwaysTrue() const {
11802   return all_of(Preds,
11803                 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
11804 }
11805 
11806 ArrayRef<const SCEVPredicate *>
11807 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) {
11808   auto I = SCEVToPreds.find(Expr);
11809   if (I == SCEVToPreds.end())
11810     return ArrayRef<const SCEVPredicate *>();
11811   return I->second;
11812 }
11813 
11814 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
11815   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
11816     return all_of(Set->Preds,
11817                   [this](const SCEVPredicate *I) { return this->implies(I); });
11818 
11819   auto ScevPredsIt = SCEVToPreds.find(N->getExpr());
11820   if (ScevPredsIt == SCEVToPreds.end())
11821     return false;
11822   auto &SCEVPreds = ScevPredsIt->second;
11823 
11824   return any_of(SCEVPreds,
11825                 [N](const SCEVPredicate *I) { return I->implies(N); });
11826 }
11827 
11828 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; }
11829 
11830 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
11831   for (auto Pred : Preds)
11832     Pred->print(OS, Depth);
11833 }
11834 
11835 void SCEVUnionPredicate::add(const SCEVPredicate *N) {
11836   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
11837     for (auto Pred : Set->Preds)
11838       add(Pred);
11839     return;
11840   }
11841 
11842   if (implies(N))
11843     return;
11844 
11845   const SCEV *Key = N->getExpr();
11846   assert(Key && "Only SCEVUnionPredicate doesn't have an "
11847                 " associated expression!");
11848 
11849   SCEVToPreds[Key].push_back(N);
11850   Preds.push_back(N);
11851 }
11852 
11853 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
11854                                                      Loop &L)
11855     : SE(SE), L(L) {}
11856 
11857 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
11858   const SCEV *Expr = SE.getSCEV(V);
11859   RewriteEntry &Entry = RewriteMap[Expr];
11860 
11861   // If we already have an entry and the version matches, return it.
11862   if (Entry.second && Generation == Entry.first)
11863     return Entry.second;
11864 
11865   // We found an entry but it's stale. Rewrite the stale entry
11866   // according to the current predicate.
11867   if (Entry.second)
11868     Expr = Entry.second;
11869 
11870   const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds);
11871   Entry = {Generation, NewSCEV};
11872 
11873   return NewSCEV;
11874 }
11875 
11876 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() {
11877   if (!BackedgeCount) {
11878     SCEVUnionPredicate BackedgePred;
11879     BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred);
11880     addPredicate(BackedgePred);
11881   }
11882   return BackedgeCount;
11883 }
11884 
11885 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
11886   if (Preds.implies(&Pred))
11887     return;
11888   Preds.add(&Pred);
11889   updateGeneration();
11890 }
11891 
11892 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const {
11893   return Preds;
11894 }
11895 
11896 void PredicatedScalarEvolution::updateGeneration() {
11897   // If the generation number wrapped recompute everything.
11898   if (++Generation == 0) {
11899     for (auto &II : RewriteMap) {
11900       const SCEV *Rewritten = II.second.second;
11901       II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)};
11902     }
11903   }
11904 }
11905 
11906 void PredicatedScalarEvolution::setNoOverflow(
11907     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
11908   const SCEV *Expr = getSCEV(V);
11909   const auto *AR = cast<SCEVAddRecExpr>(Expr);
11910 
11911   auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE);
11912 
11913   // Clear the statically implied flags.
11914   Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags);
11915   addPredicate(*SE.getWrapPredicate(AR, Flags));
11916 
11917   auto II = FlagsMap.insert({V, Flags});
11918   if (!II.second)
11919     II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second);
11920 }
11921 
11922 bool PredicatedScalarEvolution::hasNoOverflow(
11923     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
11924   const SCEV *Expr = getSCEV(V);
11925   const auto *AR = cast<SCEVAddRecExpr>(Expr);
11926 
11927   Flags = SCEVWrapPredicate::clearFlags(
11928       Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
11929 
11930   auto II = FlagsMap.find(V);
11931 
11932   if (II != FlagsMap.end())
11933     Flags = SCEVWrapPredicate::clearFlags(Flags, II->second);
11934 
11935   return Flags == SCEVWrapPredicate::IncrementAnyWrap;
11936 }
11937 
11938 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) {
11939   const SCEV *Expr = this->getSCEV(V);
11940   SmallPtrSet<const SCEVPredicate *, 4> NewPreds;
11941   auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
11942 
11943   if (!New)
11944     return nullptr;
11945 
11946   for (auto *P : NewPreds)
11947     Preds.add(P);
11948 
11949   updateGeneration();
11950   RewriteMap[SE.getSCEV(V)] = {Generation, New};
11951   return New;
11952 }
11953 
11954 PredicatedScalarEvolution::PredicatedScalarEvolution(
11955     const PredicatedScalarEvolution &Init)
11956     : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds),
11957       Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
11958   for (const auto &I : Init.FlagsMap)
11959     FlagsMap.insert(I);
11960 }
11961 
11962 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const {
11963   // For each block.
11964   for (auto *BB : L.getBlocks())
11965     for (auto &I : *BB) {
11966       if (!SE.isSCEVable(I.getType()))
11967         continue;
11968 
11969       auto *Expr = SE.getSCEV(&I);
11970       auto II = RewriteMap.find(Expr);
11971 
11972       if (II == RewriteMap.end())
11973         continue;
11974 
11975       // Don't print things that are not interesting.
11976       if (II->second.second == Expr)
11977         continue;
11978 
11979       OS.indent(Depth) << "[PSE]" << I << ":\n";
11980       OS.indent(Depth + 2) << *Expr << "\n";
11981       OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
11982     }
11983 }
11984