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/Optional.h"
63 #include "llvm/ADT/STLExtras.h"
64 #include "llvm/ADT/ScopeExit.h"
65 #include "llvm/ADT/Sequence.h"
66 #include "llvm/ADT/SmallPtrSet.h"
67 #include "llvm/ADT/Statistic.h"
68 #include "llvm/Analysis/AssumptionCache.h"
69 #include "llvm/Analysis/ConstantFolding.h"
70 #include "llvm/Analysis/InstructionSimplify.h"
71 #include "llvm/Analysis/LoopInfo.h"
72 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
73 #include "llvm/Analysis/TargetLibraryInfo.h"
74 #include "llvm/Analysis/ValueTracking.h"
75 #include "llvm/IR/ConstantRange.h"
76 #include "llvm/IR/Constants.h"
77 #include "llvm/IR/DataLayout.h"
78 #include "llvm/IR/DerivedTypes.h"
79 #include "llvm/IR/Dominators.h"
80 #include "llvm/IR/GetElementPtrTypeIterator.h"
81 #include "llvm/IR/GlobalAlias.h"
82 #include "llvm/IR/GlobalVariable.h"
83 #include "llvm/IR/InstIterator.h"
84 #include "llvm/IR/Instructions.h"
85 #include "llvm/IR/LLVMContext.h"
86 #include "llvm/IR/Metadata.h"
87 #include "llvm/IR/Operator.h"
88 #include "llvm/IR/PatternMatch.h"
89 #include "llvm/Support/CommandLine.h"
90 #include "llvm/Support/Debug.h"
91 #include "llvm/Support/ErrorHandling.h"
92 #include "llvm/Support/KnownBits.h"
93 #include "llvm/Support/MathExtras.h"
94 #include "llvm/Support/SaveAndRestore.h"
95 #include "llvm/Support/raw_ostream.h"
96 #include <algorithm>
97 using namespace llvm;
98 
99 #define DEBUG_TYPE "scalar-evolution"
100 
101 STATISTIC(NumArrayLenItCounts,
102           "Number of trip counts computed with array length");
103 STATISTIC(NumTripCountsComputed,
104           "Number of loops with predictable loop counts");
105 STATISTIC(NumTripCountsNotComputed,
106           "Number of loops without predictable loop counts");
107 STATISTIC(NumBruteForceTripCountsComputed,
108           "Number of loops with trip counts computed by force");
109 
110 static cl::opt<unsigned>
111 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
112                         cl::desc("Maximum number of iterations SCEV will "
113                                  "symbolically execute a constant "
114                                  "derived loop"),
115                         cl::init(100));
116 
117 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean.
118 static cl::opt<bool>
119 VerifySCEV("verify-scev",
120            cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
121 static cl::opt<bool>
122     VerifySCEVMap("verify-scev-maps",
123                   cl::desc("Verify no dangling value in ScalarEvolution's "
124                            "ExprValueMap (slow)"));
125 
126 static cl::opt<unsigned> MulOpsInlineThreshold(
127     "scev-mulops-inline-threshold", cl::Hidden,
128     cl::desc("Threshold for inlining multiplication operands into a SCEV"),
129     cl::init(32));
130 
131 static cl::opt<unsigned> AddOpsInlineThreshold(
132     "scev-addops-inline-threshold", cl::Hidden,
133     cl::desc("Threshold for inlining addition operands into a SCEV"),
134     cl::init(500));
135 
136 static cl::opt<unsigned> MaxSCEVCompareDepth(
137     "scalar-evolution-max-scev-compare-depth", cl::Hidden,
138     cl::desc("Maximum depth of recursive SCEV complexity comparisons"),
139     cl::init(32));
140 
141 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth(
142     "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden,
143     cl::desc("Maximum depth of recursive SCEV operations implication analysis"),
144     cl::init(2));
145 
146 static cl::opt<unsigned> MaxValueCompareDepth(
147     "scalar-evolution-max-value-compare-depth", cl::Hidden,
148     cl::desc("Maximum depth of recursive value complexity comparisons"),
149     cl::init(2));
150 
151 static cl::opt<unsigned>
152     MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden,
153                   cl::desc("Maximum depth of recursive arithmetics"),
154                   cl::init(32));
155 
156 static cl::opt<unsigned> MaxConstantEvolvingDepth(
157     "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
158     cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
159 
160 static cl::opt<unsigned>
161     MaxExtDepth("scalar-evolution-max-ext-depth", cl::Hidden,
162                 cl::desc("Maximum depth of recursive SExt/ZExt"),
163                 cl::init(8));
164 
165 static cl::opt<unsigned>
166     MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden,
167                   cl::desc("Max coefficients in AddRec during evolving"),
168                   cl::init(16));
169 
170 //===----------------------------------------------------------------------===//
171 //                           SCEV class definitions
172 //===----------------------------------------------------------------------===//
173 
174 //===----------------------------------------------------------------------===//
175 // Implementation of the SCEV class.
176 //
177 
178 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
179 LLVM_DUMP_METHOD void SCEV::dump() const {
180   print(dbgs());
181   dbgs() << '\n';
182 }
183 #endif
184 
185 void SCEV::print(raw_ostream &OS) const {
186   switch (static_cast<SCEVTypes>(getSCEVType())) {
187   case scConstant:
188     cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
189     return;
190   case scTruncate: {
191     const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
192     const SCEV *Op = Trunc->getOperand();
193     OS << "(trunc " << *Op->getType() << " " << *Op << " to "
194        << *Trunc->getType() << ")";
195     return;
196   }
197   case scZeroExtend: {
198     const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
199     const SCEV *Op = ZExt->getOperand();
200     OS << "(zext " << *Op->getType() << " " << *Op << " to "
201        << *ZExt->getType() << ")";
202     return;
203   }
204   case scSignExtend: {
205     const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
206     const SCEV *Op = SExt->getOperand();
207     OS << "(sext " << *Op->getType() << " " << *Op << " to "
208        << *SExt->getType() << ")";
209     return;
210   }
211   case scAddRecExpr: {
212     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
213     OS << "{" << *AR->getOperand(0);
214     for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
215       OS << ",+," << *AR->getOperand(i);
216     OS << "}<";
217     if (AR->hasNoUnsignedWrap())
218       OS << "nuw><";
219     if (AR->hasNoSignedWrap())
220       OS << "nsw><";
221     if (AR->hasNoSelfWrap() &&
222         !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
223       OS << "nw><";
224     AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
225     OS << ">";
226     return;
227   }
228   case scAddExpr:
229   case scMulExpr:
230   case scUMaxExpr:
231   case scSMaxExpr: {
232     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
233     const char *OpStr = nullptr;
234     switch (NAry->getSCEVType()) {
235     case scAddExpr: OpStr = " + "; break;
236     case scMulExpr: OpStr = " * "; break;
237     case scUMaxExpr: OpStr = " umax "; break;
238     case scSMaxExpr: OpStr = " smax "; break;
239     }
240     OS << "(";
241     for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
242          I != E; ++I) {
243       OS << **I;
244       if (std::next(I) != E)
245         OS << OpStr;
246     }
247     OS << ")";
248     switch (NAry->getSCEVType()) {
249     case scAddExpr:
250     case scMulExpr:
251       if (NAry->hasNoUnsignedWrap())
252         OS << "<nuw>";
253       if (NAry->hasNoSignedWrap())
254         OS << "<nsw>";
255     }
256     return;
257   }
258   case scUDivExpr: {
259     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
260     OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
261     return;
262   }
263   case scUnknown: {
264     const SCEVUnknown *U = cast<SCEVUnknown>(this);
265     Type *AllocTy;
266     if (U->isSizeOf(AllocTy)) {
267       OS << "sizeof(" << *AllocTy << ")";
268       return;
269     }
270     if (U->isAlignOf(AllocTy)) {
271       OS << "alignof(" << *AllocTy << ")";
272       return;
273     }
274 
275     Type *CTy;
276     Constant *FieldNo;
277     if (U->isOffsetOf(CTy, FieldNo)) {
278       OS << "offsetof(" << *CTy << ", ";
279       FieldNo->printAsOperand(OS, false);
280       OS << ")";
281       return;
282     }
283 
284     // Otherwise just print it normally.
285     U->getValue()->printAsOperand(OS, false);
286     return;
287   }
288   case scCouldNotCompute:
289     OS << "***COULDNOTCOMPUTE***";
290     return;
291   }
292   llvm_unreachable("Unknown SCEV kind!");
293 }
294 
295 Type *SCEV::getType() const {
296   switch (static_cast<SCEVTypes>(getSCEVType())) {
297   case scConstant:
298     return cast<SCEVConstant>(this)->getType();
299   case scTruncate:
300   case scZeroExtend:
301   case scSignExtend:
302     return cast<SCEVCastExpr>(this)->getType();
303   case scAddRecExpr:
304   case scMulExpr:
305   case scUMaxExpr:
306   case scSMaxExpr:
307     return cast<SCEVNAryExpr>(this)->getType();
308   case scAddExpr:
309     return cast<SCEVAddExpr>(this)->getType();
310   case scUDivExpr:
311     return cast<SCEVUDivExpr>(this)->getType();
312   case scUnknown:
313     return cast<SCEVUnknown>(this)->getType();
314   case scCouldNotCompute:
315     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
316   }
317   llvm_unreachable("Unknown SCEV kind!");
318 }
319 
320 bool SCEV::isZero() const {
321   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
322     return SC->getValue()->isZero();
323   return false;
324 }
325 
326 bool SCEV::isOne() const {
327   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
328     return SC->getValue()->isOne();
329   return false;
330 }
331 
332 bool SCEV::isAllOnesValue() const {
333   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
334     return SC->getValue()->isMinusOne();
335   return false;
336 }
337 
338 bool SCEV::isNonConstantNegative() const {
339   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
340   if (!Mul) return false;
341 
342   // If there is a constant factor, it will be first.
343   const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
344   if (!SC) return false;
345 
346   // Return true if the value is negative, this matches things like (-42 * V).
347   return SC->getAPInt().isNegative();
348 }
349 
350 SCEVCouldNotCompute::SCEVCouldNotCompute() :
351   SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {}
352 
353 bool SCEVCouldNotCompute::classof(const SCEV *S) {
354   return S->getSCEVType() == scCouldNotCompute;
355 }
356 
357 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
358   FoldingSetNodeID ID;
359   ID.AddInteger(scConstant);
360   ID.AddPointer(V);
361   void *IP = nullptr;
362   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
363   SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
364   UniqueSCEVs.InsertNode(S, IP);
365   return S;
366 }
367 
368 const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
369   return getConstant(ConstantInt::get(getContext(), Val));
370 }
371 
372 const SCEV *
373 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
374   IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
375   return getConstant(ConstantInt::get(ITy, V, isSigned));
376 }
377 
378 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
379                            unsigned SCEVTy, const SCEV *op, Type *ty)
380   : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
381 
382 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
383                                    const SCEV *op, Type *ty)
384   : SCEVCastExpr(ID, scTruncate, op, ty) {
385   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
386          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
387          "Cannot truncate non-integer value!");
388 }
389 
390 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
391                                        const SCEV *op, Type *ty)
392   : SCEVCastExpr(ID, scZeroExtend, op, ty) {
393   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
394          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
395          "Cannot zero extend non-integer value!");
396 }
397 
398 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
399                                        const SCEV *op, Type *ty)
400   : SCEVCastExpr(ID, scSignExtend, op, ty) {
401   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
402          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
403          "Cannot sign extend non-integer value!");
404 }
405 
406 void SCEVUnknown::deleted() {
407   // Clear this SCEVUnknown from various maps.
408   SE->forgetMemoizedResults(this);
409 
410   // Remove this SCEVUnknown from the uniquing map.
411   SE->UniqueSCEVs.RemoveNode(this);
412 
413   // Release the value.
414   setValPtr(nullptr);
415 }
416 
417 void SCEVUnknown::allUsesReplacedWith(Value *New) {
418   // Remove this SCEVUnknown from the uniquing map.
419   SE->UniqueSCEVs.RemoveNode(this);
420 
421   // Update this SCEVUnknown to point to the new value. This is needed
422   // because there may still be outstanding SCEVs which still point to
423   // this SCEVUnknown.
424   setValPtr(New);
425 }
426 
427 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
428   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
429     if (VCE->getOpcode() == Instruction::PtrToInt)
430       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
431         if (CE->getOpcode() == Instruction::GetElementPtr &&
432             CE->getOperand(0)->isNullValue() &&
433             CE->getNumOperands() == 2)
434           if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
435             if (CI->isOne()) {
436               AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
437                                  ->getElementType();
438               return true;
439             }
440 
441   return false;
442 }
443 
444 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
445   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
446     if (VCE->getOpcode() == Instruction::PtrToInt)
447       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
448         if (CE->getOpcode() == Instruction::GetElementPtr &&
449             CE->getOperand(0)->isNullValue()) {
450           Type *Ty =
451             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
452           if (StructType *STy = dyn_cast<StructType>(Ty))
453             if (!STy->isPacked() &&
454                 CE->getNumOperands() == 3 &&
455                 CE->getOperand(1)->isNullValue()) {
456               if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
457                 if (CI->isOne() &&
458                     STy->getNumElements() == 2 &&
459                     STy->getElementType(0)->isIntegerTy(1)) {
460                   AllocTy = STy->getElementType(1);
461                   return true;
462                 }
463             }
464         }
465 
466   return false;
467 }
468 
469 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
470   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
471     if (VCE->getOpcode() == Instruction::PtrToInt)
472       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
473         if (CE->getOpcode() == Instruction::GetElementPtr &&
474             CE->getNumOperands() == 3 &&
475             CE->getOperand(0)->isNullValue() &&
476             CE->getOperand(1)->isNullValue()) {
477           Type *Ty =
478             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
479           // Ignore vector types here so that ScalarEvolutionExpander doesn't
480           // emit getelementptrs that index into vectors.
481           if (Ty->isStructTy() || Ty->isArrayTy()) {
482             CTy = Ty;
483             FieldNo = CE->getOperand(2);
484             return true;
485           }
486         }
487 
488   return false;
489 }
490 
491 //===----------------------------------------------------------------------===//
492 //                               SCEV Utilities
493 //===----------------------------------------------------------------------===//
494 
495 /// Compare the two values \p LV and \p RV in terms of their "complexity" where
496 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order
497 /// operands in SCEV expressions.  \p EqCache is a set of pairs of values that
498 /// have been previously deemed to be "equally complex" by this routine.  It is
499 /// intended to avoid exponential time complexity in cases like:
500 ///
501 ///   %a = f(%x, %y)
502 ///   %b = f(%a, %a)
503 ///   %c = f(%b, %b)
504 ///
505 ///   %d = f(%x, %y)
506 ///   %e = f(%d, %d)
507 ///   %f = f(%e, %e)
508 ///
509 ///   CompareValueComplexity(%f, %c)
510 ///
511 /// Since we do not continue running this routine on expression trees once we
512 /// have seen unequal values, there is no need to track them in the cache.
513 static int
514 CompareValueComplexity(SmallSet<std::pair<Value *, Value *>, 8> &EqCache,
515                        const LoopInfo *const LI, Value *LV, Value *RV,
516                        unsigned Depth) {
517   if (Depth > MaxValueCompareDepth || EqCache.count({LV, RV}))
518     return 0;
519 
520   // Order pointer values after integer values. This helps SCEVExpander form
521   // GEPs.
522   bool LIsPointer = LV->getType()->isPointerTy(),
523        RIsPointer = RV->getType()->isPointerTy();
524   if (LIsPointer != RIsPointer)
525     return (int)LIsPointer - (int)RIsPointer;
526 
527   // Compare getValueID values.
528   unsigned LID = LV->getValueID(), RID = RV->getValueID();
529   if (LID != RID)
530     return (int)LID - (int)RID;
531 
532   // Sort arguments by their position.
533   if (const auto *LA = dyn_cast<Argument>(LV)) {
534     const auto *RA = cast<Argument>(RV);
535     unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
536     return (int)LArgNo - (int)RArgNo;
537   }
538 
539   if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
540     const auto *RGV = cast<GlobalValue>(RV);
541 
542     const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
543       auto LT = GV->getLinkage();
544       return !(GlobalValue::isPrivateLinkage(LT) ||
545                GlobalValue::isInternalLinkage(LT));
546     };
547 
548     // Use the names to distinguish the two values, but only if the
549     // names are semantically important.
550     if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
551       return LGV->getName().compare(RGV->getName());
552   }
553 
554   // For instructions, compare their loop depth, and their operand count.  This
555   // is pretty loose.
556   if (const auto *LInst = dyn_cast<Instruction>(LV)) {
557     const auto *RInst = cast<Instruction>(RV);
558 
559     // Compare loop depths.
560     const BasicBlock *LParent = LInst->getParent(),
561                      *RParent = RInst->getParent();
562     if (LParent != RParent) {
563       unsigned LDepth = LI->getLoopDepth(LParent),
564                RDepth = LI->getLoopDepth(RParent);
565       if (LDepth != RDepth)
566         return (int)LDepth - (int)RDepth;
567     }
568 
569     // Compare the number of operands.
570     unsigned LNumOps = LInst->getNumOperands(),
571              RNumOps = RInst->getNumOperands();
572     if (LNumOps != RNumOps)
573       return (int)LNumOps - (int)RNumOps;
574 
575     for (unsigned Idx : seq(0u, LNumOps)) {
576       int Result =
577           CompareValueComplexity(EqCache, LI, LInst->getOperand(Idx),
578                                  RInst->getOperand(Idx), Depth + 1);
579       if (Result != 0)
580         return Result;
581     }
582   }
583 
584   EqCache.insert({LV, RV});
585   return 0;
586 }
587 
588 // Return negative, zero, or positive, if LHS is less than, equal to, or greater
589 // than RHS, respectively. A three-way result allows recursive comparisons to be
590 // more efficient.
591 static int CompareSCEVComplexity(
592     SmallSet<std::pair<const SCEV *, const SCEV *>, 8> &EqCacheSCEV,
593     const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS,
594     DominatorTree &DT, unsigned Depth = 0) {
595   // Fast-path: SCEVs are uniqued so we can do a quick equality check.
596   if (LHS == RHS)
597     return 0;
598 
599   // Primarily, sort the SCEVs by their getSCEVType().
600   unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
601   if (LType != RType)
602     return (int)LType - (int)RType;
603 
604   if (Depth > MaxSCEVCompareDepth || EqCacheSCEV.count({LHS, RHS}))
605     return 0;
606   // Aside from the getSCEVType() ordering, the particular ordering
607   // isn't very important except that it's beneficial to be consistent,
608   // so that (a + b) and (b + a) don't end up as different expressions.
609   switch (static_cast<SCEVTypes>(LType)) {
610   case scUnknown: {
611     const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
612     const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
613 
614     SmallSet<std::pair<Value *, Value *>, 8> EqCache;
615     int X = CompareValueComplexity(EqCache, LI, LU->getValue(), RU->getValue(),
616                                    Depth + 1);
617     if (X == 0)
618       EqCacheSCEV.insert({LHS, RHS});
619     return X;
620   }
621 
622   case scConstant: {
623     const SCEVConstant *LC = cast<SCEVConstant>(LHS);
624     const SCEVConstant *RC = cast<SCEVConstant>(RHS);
625 
626     // Compare constant values.
627     const APInt &LA = LC->getAPInt();
628     const APInt &RA = RC->getAPInt();
629     unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
630     if (LBitWidth != RBitWidth)
631       return (int)LBitWidth - (int)RBitWidth;
632     return LA.ult(RA) ? -1 : 1;
633   }
634 
635   case scAddRecExpr: {
636     const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
637     const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
638 
639     // There is always a dominance between two recs that are used by one SCEV,
640     // so we can safely sort recs by loop header dominance. We require such
641     // order in getAddExpr.
642     const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
643     if (LLoop != RLoop) {
644       const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
645       assert(LHead != RHead && "Two loops share the same header?");
646       if (DT.dominates(LHead, RHead))
647         return 1;
648       else
649         assert(DT.dominates(RHead, LHead) &&
650                "No dominance between recurrences used by one SCEV?");
651       return -1;
652     }
653 
654     // Addrec complexity grows with operand count.
655     unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
656     if (LNumOps != RNumOps)
657       return (int)LNumOps - (int)RNumOps;
658 
659     // Lexicographically compare.
660     for (unsigned i = 0; i != LNumOps; ++i) {
661       int X = CompareSCEVComplexity(EqCacheSCEV, LI, LA->getOperand(i),
662                                     RA->getOperand(i), DT,  Depth + 1);
663       if (X != 0)
664         return X;
665     }
666     EqCacheSCEV.insert({LHS, RHS});
667     return 0;
668   }
669 
670   case scAddExpr:
671   case scMulExpr:
672   case scSMaxExpr:
673   case scUMaxExpr: {
674     const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
675     const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
676 
677     // Lexicographically compare n-ary expressions.
678     unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
679     if (LNumOps != RNumOps)
680       return (int)LNumOps - (int)RNumOps;
681 
682     for (unsigned i = 0; i != LNumOps; ++i) {
683       if (i >= RNumOps)
684         return 1;
685       int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getOperand(i),
686                                     RC->getOperand(i), DT, Depth + 1);
687       if (X != 0)
688         return X;
689     }
690     EqCacheSCEV.insert({LHS, RHS});
691     return 0;
692   }
693 
694   case scUDivExpr: {
695     const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
696     const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
697 
698     // Lexicographically compare udiv expressions.
699     int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getLHS(), RC->getLHS(),
700                                   DT, Depth + 1);
701     if (X != 0)
702       return X;
703     X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getRHS(), RC->getRHS(), DT,
704                               Depth + 1);
705     if (X == 0)
706       EqCacheSCEV.insert({LHS, RHS});
707     return X;
708   }
709 
710   case scTruncate:
711   case scZeroExtend:
712   case scSignExtend: {
713     const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
714     const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
715 
716     // Compare cast expressions by operand.
717     int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getOperand(),
718                                   RC->getOperand(), DT, Depth + 1);
719     if (X == 0)
720       EqCacheSCEV.insert({LHS, RHS});
721     return X;
722   }
723 
724   case scCouldNotCompute:
725     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
726   }
727   llvm_unreachable("Unknown SCEV kind!");
728 }
729 
730 /// Given a list of SCEV objects, order them by their complexity, and group
731 /// objects of the same complexity together by value.  When this routine is
732 /// finished, we know that any duplicates in the vector are consecutive and that
733 /// complexity is monotonically increasing.
734 ///
735 /// Note that we go take special precautions to ensure that we get deterministic
736 /// results from this routine.  In other words, we don't want the results of
737 /// this to depend on where the addresses of various SCEV objects happened to
738 /// land in memory.
739 ///
740 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
741                               LoopInfo *LI, DominatorTree &DT) {
742   if (Ops.size() < 2) return;  // Noop
743 
744   SmallSet<std::pair<const SCEV *, const SCEV *>, 8> EqCache;
745   if (Ops.size() == 2) {
746     // This is the common case, which also happens to be trivially simple.
747     // Special case it.
748     const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
749     if (CompareSCEVComplexity(EqCache, LI, RHS, LHS, DT) < 0)
750       std::swap(LHS, RHS);
751     return;
752   }
753 
754   // Do the rough sort by complexity.
755   std::stable_sort(Ops.begin(), Ops.end(),
756                    [&EqCache, LI, &DT](const SCEV *LHS, const SCEV *RHS) {
757                      return
758                          CompareSCEVComplexity(EqCache, LI, LHS, RHS, DT) < 0;
759                    });
760 
761   // Now that we are sorted by complexity, group elements of the same
762   // complexity.  Note that this is, at worst, N^2, but the vector is likely to
763   // be extremely short in practice.  Note that we take this approach because we
764   // do not want to depend on the addresses of the objects we are grouping.
765   for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
766     const SCEV *S = Ops[i];
767     unsigned Complexity = S->getSCEVType();
768 
769     // If there are any objects of the same complexity and same value as this
770     // one, group them.
771     for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
772       if (Ops[j] == S) { // Found a duplicate.
773         // Move it to immediately after i'th element.
774         std::swap(Ops[i+1], Ops[j]);
775         ++i;   // no need to rescan it.
776         if (i == e-2) return;  // Done!
777       }
778     }
779   }
780 }
781 
782 // Returns the size of the SCEV S.
783 static inline int sizeOfSCEV(const SCEV *S) {
784   struct FindSCEVSize {
785     int Size;
786     FindSCEVSize() : Size(0) {}
787 
788     bool follow(const SCEV *S) {
789       ++Size;
790       // Keep looking at all operands of S.
791       return true;
792     }
793     bool isDone() const {
794       return false;
795     }
796   };
797 
798   FindSCEVSize F;
799   SCEVTraversal<FindSCEVSize> ST(F);
800   ST.visitAll(S);
801   return F.Size;
802 }
803 
804 namespace {
805 
806 struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> {
807 public:
808   // Computes the Quotient and Remainder of the division of Numerator by
809   // Denominator.
810   static void divide(ScalarEvolution &SE, const SCEV *Numerator,
811                      const SCEV *Denominator, const SCEV **Quotient,
812                      const SCEV **Remainder) {
813     assert(Numerator && Denominator && "Uninitialized SCEV");
814 
815     SCEVDivision D(SE, Numerator, Denominator);
816 
817     // Check for the trivial case here to avoid having to check for it in the
818     // rest of the code.
819     if (Numerator == Denominator) {
820       *Quotient = D.One;
821       *Remainder = D.Zero;
822       return;
823     }
824 
825     if (Numerator->isZero()) {
826       *Quotient = D.Zero;
827       *Remainder = D.Zero;
828       return;
829     }
830 
831     // A simple case when N/1. The quotient is N.
832     if (Denominator->isOne()) {
833       *Quotient = Numerator;
834       *Remainder = D.Zero;
835       return;
836     }
837 
838     // Split the Denominator when it is a product.
839     if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) {
840       const SCEV *Q, *R;
841       *Quotient = Numerator;
842       for (const SCEV *Op : T->operands()) {
843         divide(SE, *Quotient, Op, &Q, &R);
844         *Quotient = Q;
845 
846         // Bail out when the Numerator is not divisible by one of the terms of
847         // the Denominator.
848         if (!R->isZero()) {
849           *Quotient = D.Zero;
850           *Remainder = Numerator;
851           return;
852         }
853       }
854       *Remainder = D.Zero;
855       return;
856     }
857 
858     D.visit(Numerator);
859     *Quotient = D.Quotient;
860     *Remainder = D.Remainder;
861   }
862 
863   // Except in the trivial case described above, we do not know how to divide
864   // Expr by Denominator for the following functions with empty implementation.
865   void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {}
866   void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {}
867   void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {}
868   void visitUDivExpr(const SCEVUDivExpr *Numerator) {}
869   void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {}
870   void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {}
871   void visitUnknown(const SCEVUnknown *Numerator) {}
872   void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {}
873 
874   void visitConstant(const SCEVConstant *Numerator) {
875     if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) {
876       APInt NumeratorVal = Numerator->getAPInt();
877       APInt DenominatorVal = D->getAPInt();
878       uint32_t NumeratorBW = NumeratorVal.getBitWidth();
879       uint32_t DenominatorBW = DenominatorVal.getBitWidth();
880 
881       if (NumeratorBW > DenominatorBW)
882         DenominatorVal = DenominatorVal.sext(NumeratorBW);
883       else if (NumeratorBW < DenominatorBW)
884         NumeratorVal = NumeratorVal.sext(DenominatorBW);
885 
886       APInt QuotientVal(NumeratorVal.getBitWidth(), 0);
887       APInt RemainderVal(NumeratorVal.getBitWidth(), 0);
888       APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal);
889       Quotient = SE.getConstant(QuotientVal);
890       Remainder = SE.getConstant(RemainderVal);
891       return;
892     }
893   }
894 
895   void visitAddRecExpr(const SCEVAddRecExpr *Numerator) {
896     const SCEV *StartQ, *StartR, *StepQ, *StepR;
897     if (!Numerator->isAffine())
898       return cannotDivide(Numerator);
899     divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR);
900     divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR);
901     // Bail out if the types do not match.
902     Type *Ty = Denominator->getType();
903     if (Ty != StartQ->getType() || Ty != StartR->getType() ||
904         Ty != StepQ->getType() || Ty != StepR->getType())
905       return cannotDivide(Numerator);
906     Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(),
907                                 Numerator->getNoWrapFlags());
908     Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(),
909                                  Numerator->getNoWrapFlags());
910   }
911 
912   void visitAddExpr(const SCEVAddExpr *Numerator) {
913     SmallVector<const SCEV *, 2> Qs, Rs;
914     Type *Ty = Denominator->getType();
915 
916     for (const SCEV *Op : Numerator->operands()) {
917       const SCEV *Q, *R;
918       divide(SE, Op, Denominator, &Q, &R);
919 
920       // Bail out if types do not match.
921       if (Ty != Q->getType() || Ty != R->getType())
922         return cannotDivide(Numerator);
923 
924       Qs.push_back(Q);
925       Rs.push_back(R);
926     }
927 
928     if (Qs.size() == 1) {
929       Quotient = Qs[0];
930       Remainder = Rs[0];
931       return;
932     }
933 
934     Quotient = SE.getAddExpr(Qs);
935     Remainder = SE.getAddExpr(Rs);
936   }
937 
938   void visitMulExpr(const SCEVMulExpr *Numerator) {
939     SmallVector<const SCEV *, 2> Qs;
940     Type *Ty = Denominator->getType();
941 
942     bool FoundDenominatorTerm = false;
943     for (const SCEV *Op : Numerator->operands()) {
944       // Bail out if types do not match.
945       if (Ty != Op->getType())
946         return cannotDivide(Numerator);
947 
948       if (FoundDenominatorTerm) {
949         Qs.push_back(Op);
950         continue;
951       }
952 
953       // Check whether Denominator divides one of the product operands.
954       const SCEV *Q, *R;
955       divide(SE, Op, Denominator, &Q, &R);
956       if (!R->isZero()) {
957         Qs.push_back(Op);
958         continue;
959       }
960 
961       // Bail out if types do not match.
962       if (Ty != Q->getType())
963         return cannotDivide(Numerator);
964 
965       FoundDenominatorTerm = true;
966       Qs.push_back(Q);
967     }
968 
969     if (FoundDenominatorTerm) {
970       Remainder = Zero;
971       if (Qs.size() == 1)
972         Quotient = Qs[0];
973       else
974         Quotient = SE.getMulExpr(Qs);
975       return;
976     }
977 
978     if (!isa<SCEVUnknown>(Denominator))
979       return cannotDivide(Numerator);
980 
981     // The Remainder is obtained by replacing Denominator by 0 in Numerator.
982     ValueToValueMap RewriteMap;
983     RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
984         cast<SCEVConstant>(Zero)->getValue();
985     Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
986 
987     if (Remainder->isZero()) {
988       // The Quotient is obtained by replacing Denominator by 1 in Numerator.
989       RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
990           cast<SCEVConstant>(One)->getValue();
991       Quotient =
992           SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
993       return;
994     }
995 
996     // Quotient is (Numerator - Remainder) divided by Denominator.
997     const SCEV *Q, *R;
998     const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder);
999     // This SCEV does not seem to simplify: fail the division here.
1000     if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator))
1001       return cannotDivide(Numerator);
1002     divide(SE, Diff, Denominator, &Q, &R);
1003     if (R != Zero)
1004       return cannotDivide(Numerator);
1005     Quotient = Q;
1006   }
1007 
1008 private:
1009   SCEVDivision(ScalarEvolution &S, const SCEV *Numerator,
1010                const SCEV *Denominator)
1011       : SE(S), Denominator(Denominator) {
1012     Zero = SE.getZero(Denominator->getType());
1013     One = SE.getOne(Denominator->getType());
1014 
1015     // We generally do not know how to divide Expr by Denominator. We
1016     // initialize the division to a "cannot divide" state to simplify the rest
1017     // of the code.
1018     cannotDivide(Numerator);
1019   }
1020 
1021   // Convenience function for giving up on the division. We set the quotient to
1022   // be equal to zero and the remainder to be equal to the numerator.
1023   void cannotDivide(const SCEV *Numerator) {
1024     Quotient = Zero;
1025     Remainder = Numerator;
1026   }
1027 
1028   ScalarEvolution &SE;
1029   const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One;
1030 };
1031 
1032 }
1033 
1034 //===----------------------------------------------------------------------===//
1035 //                      Simple SCEV method implementations
1036 //===----------------------------------------------------------------------===//
1037 
1038 /// Compute BC(It, K).  The result has width W.  Assume, K > 0.
1039 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
1040                                        ScalarEvolution &SE,
1041                                        Type *ResultTy) {
1042   // Handle the simplest case efficiently.
1043   if (K == 1)
1044     return SE.getTruncateOrZeroExtend(It, ResultTy);
1045 
1046   // We are using the following formula for BC(It, K):
1047   //
1048   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
1049   //
1050   // Suppose, W is the bitwidth of the return value.  We must be prepared for
1051   // overflow.  Hence, we must assure that the result of our computation is
1052   // equal to the accurate one modulo 2^W.  Unfortunately, division isn't
1053   // safe in modular arithmetic.
1054   //
1055   // However, this code doesn't use exactly that formula; the formula it uses
1056   // is something like the following, where T is the number of factors of 2 in
1057   // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
1058   // exponentiation:
1059   //
1060   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
1061   //
1062   // This formula is trivially equivalent to the previous formula.  However,
1063   // this formula can be implemented much more efficiently.  The trick is that
1064   // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
1065   // arithmetic.  To do exact division in modular arithmetic, all we have
1066   // to do is multiply by the inverse.  Therefore, this step can be done at
1067   // width W.
1068   //
1069   // The next issue is how to safely do the division by 2^T.  The way this
1070   // is done is by doing the multiplication step at a width of at least W + T
1071   // bits.  This way, the bottom W+T bits of the product are accurate. Then,
1072   // when we perform the division by 2^T (which is equivalent to a right shift
1073   // by T), the bottom W bits are accurate.  Extra bits are okay; they'll get
1074   // truncated out after the division by 2^T.
1075   //
1076   // In comparison to just directly using the first formula, this technique
1077   // is much more efficient; using the first formula requires W * K bits,
1078   // but this formula less than W + K bits. Also, the first formula requires
1079   // a division step, whereas this formula only requires multiplies and shifts.
1080   //
1081   // It doesn't matter whether the subtraction step is done in the calculation
1082   // width or the input iteration count's width; if the subtraction overflows,
1083   // the result must be zero anyway.  We prefer here to do it in the width of
1084   // the induction variable because it helps a lot for certain cases; CodeGen
1085   // isn't smart enough to ignore the overflow, which leads to much less
1086   // efficient code if the width of the subtraction is wider than the native
1087   // register width.
1088   //
1089   // (It's possible to not widen at all by pulling out factors of 2 before
1090   // the multiplication; for example, K=2 can be calculated as
1091   // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
1092   // extra arithmetic, so it's not an obvious win, and it gets
1093   // much more complicated for K > 3.)
1094 
1095   // Protection from insane SCEVs; this bound is conservative,
1096   // but it probably doesn't matter.
1097   if (K > 1000)
1098     return SE.getCouldNotCompute();
1099 
1100   unsigned W = SE.getTypeSizeInBits(ResultTy);
1101 
1102   // Calculate K! / 2^T and T; we divide out the factors of two before
1103   // multiplying for calculating K! / 2^T to avoid overflow.
1104   // Other overflow doesn't matter because we only care about the bottom
1105   // W bits of the result.
1106   APInt OddFactorial(W, 1);
1107   unsigned T = 1;
1108   for (unsigned i = 3; i <= K; ++i) {
1109     APInt Mult(W, i);
1110     unsigned TwoFactors = Mult.countTrailingZeros();
1111     T += TwoFactors;
1112     Mult.lshrInPlace(TwoFactors);
1113     OddFactorial *= Mult;
1114   }
1115 
1116   // We need at least W + T bits for the multiplication step
1117   unsigned CalculationBits = W + T;
1118 
1119   // Calculate 2^T, at width T+W.
1120   APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
1121 
1122   // Calculate the multiplicative inverse of K! / 2^T;
1123   // this multiplication factor will perform the exact division by
1124   // K! / 2^T.
1125   APInt Mod = APInt::getSignedMinValue(W+1);
1126   APInt MultiplyFactor = OddFactorial.zext(W+1);
1127   MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
1128   MultiplyFactor = MultiplyFactor.trunc(W);
1129 
1130   // Calculate the product, at width T+W
1131   IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
1132                                                       CalculationBits);
1133   const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
1134   for (unsigned i = 1; i != K; ++i) {
1135     const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
1136     Dividend = SE.getMulExpr(Dividend,
1137                              SE.getTruncateOrZeroExtend(S, CalculationTy));
1138   }
1139 
1140   // Divide by 2^T
1141   const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
1142 
1143   // Truncate the result, and divide by K! / 2^T.
1144 
1145   return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1146                        SE.getTruncateOrZeroExtend(DivResult, ResultTy));
1147 }
1148 
1149 /// Return the value of this chain of recurrences at the specified iteration
1150 /// number.  We can evaluate this recurrence by multiplying each element in the
1151 /// chain by the binomial coefficient corresponding to it.  In other words, we
1152 /// can evaluate {A,+,B,+,C,+,D} as:
1153 ///
1154 ///   A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
1155 ///
1156 /// where BC(It, k) stands for binomial coefficient.
1157 ///
1158 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
1159                                                 ScalarEvolution &SE) const {
1160   const SCEV *Result = getStart();
1161   for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1162     // The computation is correct in the face of overflow provided that the
1163     // multiplication is performed _after_ the evaluation of the binomial
1164     // coefficient.
1165     const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
1166     if (isa<SCEVCouldNotCompute>(Coeff))
1167       return Coeff;
1168 
1169     Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
1170   }
1171   return Result;
1172 }
1173 
1174 //===----------------------------------------------------------------------===//
1175 //                    SCEV Expression folder implementations
1176 //===----------------------------------------------------------------------===//
1177 
1178 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
1179                                              Type *Ty) {
1180   assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1181          "This is not a truncating conversion!");
1182   assert(isSCEVable(Ty) &&
1183          "This is not a conversion to a SCEVable type!");
1184   Ty = getEffectiveSCEVType(Ty);
1185 
1186   FoldingSetNodeID ID;
1187   ID.AddInteger(scTruncate);
1188   ID.AddPointer(Op);
1189   ID.AddPointer(Ty);
1190   void *IP = nullptr;
1191   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1192 
1193   // Fold if the operand is constant.
1194   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1195     return getConstant(
1196       cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1197 
1198   // trunc(trunc(x)) --> trunc(x)
1199   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
1200     return getTruncateExpr(ST->getOperand(), Ty);
1201 
1202   // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1203   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1204     return getTruncateOrSignExtend(SS->getOperand(), Ty);
1205 
1206   // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1207   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1208     return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
1209 
1210   // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can
1211   // eliminate all the truncates, or we replace other casts with truncates.
1212   if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) {
1213     SmallVector<const SCEV *, 4> Operands;
1214     bool hasTrunc = false;
1215     for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) {
1216       const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty);
1217       if (!isa<SCEVCastExpr>(SA->getOperand(i)))
1218         hasTrunc = isa<SCEVTruncateExpr>(S);
1219       Operands.push_back(S);
1220     }
1221     if (!hasTrunc)
1222       return getAddExpr(Operands);
1223     UniqueSCEVs.FindNodeOrInsertPos(ID, IP);  // Mutates IP, returns NULL.
1224   }
1225 
1226   // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can
1227   // eliminate all the truncates, or we replace other casts with truncates.
1228   if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) {
1229     SmallVector<const SCEV *, 4> Operands;
1230     bool hasTrunc = false;
1231     for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) {
1232       const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty);
1233       if (!isa<SCEVCastExpr>(SM->getOperand(i)))
1234         hasTrunc = isa<SCEVTruncateExpr>(S);
1235       Operands.push_back(S);
1236     }
1237     if (!hasTrunc)
1238       return getMulExpr(Operands);
1239     UniqueSCEVs.FindNodeOrInsertPos(ID, IP);  // Mutates IP, returns NULL.
1240   }
1241 
1242   // If the input value is a chrec scev, truncate the chrec's operands.
1243   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1244     SmallVector<const SCEV *, 4> Operands;
1245     for (const SCEV *Op : AddRec->operands())
1246       Operands.push_back(getTruncateExpr(Op, Ty));
1247     return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1248   }
1249 
1250   // The cast wasn't folded; create an explicit cast node. We can reuse
1251   // the existing insert position since if we get here, we won't have
1252   // made any changes which would invalidate it.
1253   SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1254                                                  Op, Ty);
1255   UniqueSCEVs.InsertNode(S, IP);
1256   return S;
1257 }
1258 
1259 // Get the limit of a recurrence such that incrementing by Step cannot cause
1260 // signed overflow as long as the value of the recurrence within the
1261 // loop does not exceed this limit before incrementing.
1262 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1263                                                  ICmpInst::Predicate *Pred,
1264                                                  ScalarEvolution *SE) {
1265   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1266   if (SE->isKnownPositive(Step)) {
1267     *Pred = ICmpInst::ICMP_SLT;
1268     return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1269                            SE->getSignedRangeMax(Step));
1270   }
1271   if (SE->isKnownNegative(Step)) {
1272     *Pred = ICmpInst::ICMP_SGT;
1273     return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1274                            SE->getSignedRangeMin(Step));
1275   }
1276   return nullptr;
1277 }
1278 
1279 // Get the limit of a recurrence such that incrementing by Step cannot cause
1280 // unsigned overflow as long as the value of the recurrence within the loop does
1281 // not exceed this limit before incrementing.
1282 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1283                                                    ICmpInst::Predicate *Pred,
1284                                                    ScalarEvolution *SE) {
1285   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1286   *Pred = ICmpInst::ICMP_ULT;
1287 
1288   return SE->getConstant(APInt::getMinValue(BitWidth) -
1289                          SE->getUnsignedRangeMax(Step));
1290 }
1291 
1292 namespace {
1293 
1294 struct ExtendOpTraitsBase {
1295   typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *,
1296                                                           unsigned);
1297 };
1298 
1299 // Used to make code generic over signed and unsigned overflow.
1300 template <typename ExtendOp> struct ExtendOpTraits {
1301   // Members present:
1302   //
1303   // static const SCEV::NoWrapFlags WrapType;
1304   //
1305   // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1306   //
1307   // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1308   //                                           ICmpInst::Predicate *Pred,
1309   //                                           ScalarEvolution *SE);
1310 };
1311 
1312 template <>
1313 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1314   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1315 
1316   static const GetExtendExprTy GetExtendExpr;
1317 
1318   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1319                                              ICmpInst::Predicate *Pred,
1320                                              ScalarEvolution *SE) {
1321     return getSignedOverflowLimitForStep(Step, Pred, SE);
1322   }
1323 };
1324 
1325 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1326     SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr;
1327 
1328 template <>
1329 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1330   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1331 
1332   static const GetExtendExprTy GetExtendExpr;
1333 
1334   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1335                                              ICmpInst::Predicate *Pred,
1336                                              ScalarEvolution *SE) {
1337     return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1338   }
1339 };
1340 
1341 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1342     SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr;
1343 }
1344 
1345 // The recurrence AR has been shown to have no signed/unsigned wrap or something
1346 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1347 // easily prove NSW/NUW for its preincrement or postincrement sibling. This
1348 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1349 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1350 // expression "Step + sext/zext(PreIncAR)" is congruent with
1351 // "sext/zext(PostIncAR)"
1352 template <typename ExtendOpTy>
1353 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1354                                         ScalarEvolution *SE, unsigned Depth) {
1355   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1356   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1357 
1358   const Loop *L = AR->getLoop();
1359   const SCEV *Start = AR->getStart();
1360   const SCEV *Step = AR->getStepRecurrence(*SE);
1361 
1362   // Check for a simple looking step prior to loop entry.
1363   const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1364   if (!SA)
1365     return nullptr;
1366 
1367   // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1368   // subtraction is expensive. For this purpose, perform a quick and dirty
1369   // difference, by checking for Step in the operand list.
1370   SmallVector<const SCEV *, 4> DiffOps;
1371   for (const SCEV *Op : SA->operands())
1372     if (Op != Step)
1373       DiffOps.push_back(Op);
1374 
1375   if (DiffOps.size() == SA->getNumOperands())
1376     return nullptr;
1377 
1378   // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1379   // `Step`:
1380 
1381   // 1. NSW/NUW flags on the step increment.
1382   auto PreStartFlags =
1383     ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
1384   const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1385   const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1386       SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1387 
1388   // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1389   // "S+X does not sign/unsign-overflow".
1390   //
1391 
1392   const SCEV *BECount = SE->getBackedgeTakenCount(L);
1393   if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1394       !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1395     return PreStart;
1396 
1397   // 2. Direct overflow check on the step operation's expression.
1398   unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1399   Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1400   const SCEV *OperandExtendedStart =
1401       SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
1402                      (SE->*GetExtendExpr)(Step, WideTy, Depth));
1403   if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
1404     if (PreAR && AR->getNoWrapFlags(WrapType)) {
1405       // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1406       // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1407       // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`.  Cache this fact.
1408       const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType);
1409     }
1410     return PreStart;
1411   }
1412 
1413   // 3. Loop precondition.
1414   ICmpInst::Predicate Pred;
1415   const SCEV *OverflowLimit =
1416       ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1417 
1418   if (OverflowLimit &&
1419       SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1420     return PreStart;
1421 
1422   return nullptr;
1423 }
1424 
1425 // Get the normalized zero or sign extended expression for this AddRec's Start.
1426 template <typename ExtendOpTy>
1427 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1428                                         ScalarEvolution *SE,
1429                                         unsigned Depth) {
1430   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1431 
1432   const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth);
1433   if (!PreStart)
1434     return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth);
1435 
1436   return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty,
1437                                              Depth),
1438                         (SE->*GetExtendExpr)(PreStart, Ty, Depth));
1439 }
1440 
1441 // Try to prove away overflow by looking at "nearby" add recurrences.  A
1442 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1443 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1444 //
1445 // Formally:
1446 //
1447 //     {S,+,X} == {S-T,+,X} + T
1448 //  => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1449 //
1450 // If ({S-T,+,X} + T) does not overflow  ... (1)
1451 //
1452 //  RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1453 //
1454 // If {S-T,+,X} does not overflow  ... (2)
1455 //
1456 //  RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1457 //      == {Ext(S-T)+Ext(T),+,Ext(X)}
1458 //
1459 // If (S-T)+T does not overflow  ... (3)
1460 //
1461 //  RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1462 //      == {Ext(S),+,Ext(X)} == LHS
1463 //
1464 // Thus, if (1), (2) and (3) are true for some T, then
1465 //   Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1466 //
1467 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1468 // does not overflow" restricted to the 0th iteration.  Therefore we only need
1469 // to check for (1) and (2).
1470 //
1471 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1472 // is `Delta` (defined below).
1473 //
1474 template <typename ExtendOpTy>
1475 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1476                                                 const SCEV *Step,
1477                                                 const Loop *L) {
1478   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1479 
1480   // We restrict `Start` to a constant to prevent SCEV from spending too much
1481   // time here.  It is correct (but more expensive) to continue with a
1482   // non-constant `Start` and do a general SCEV subtraction to compute
1483   // `PreStart` below.
1484   //
1485   const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1486   if (!StartC)
1487     return false;
1488 
1489   APInt StartAI = StartC->getAPInt();
1490 
1491   for (unsigned Delta : {-2, -1, 1, 2}) {
1492     const SCEV *PreStart = getConstant(StartAI - Delta);
1493 
1494     FoldingSetNodeID ID;
1495     ID.AddInteger(scAddRecExpr);
1496     ID.AddPointer(PreStart);
1497     ID.AddPointer(Step);
1498     ID.AddPointer(L);
1499     void *IP = nullptr;
1500     const auto *PreAR =
1501       static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1502 
1503     // Give up if we don't already have the add recurrence we need because
1504     // actually constructing an add recurrence is relatively expensive.
1505     if (PreAR && PreAR->getNoWrapFlags(WrapType)) {  // proves (2)
1506       const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1507       ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1508       const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1509           DeltaS, &Pred, this);
1510       if (Limit && isKnownPredicate(Pred, PreAR, Limit))  // proves (1)
1511         return true;
1512     }
1513   }
1514 
1515   return false;
1516 }
1517 
1518 const SCEV *
1519 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1520   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1521          "This is not an extending conversion!");
1522   assert(isSCEVable(Ty) &&
1523          "This is not a conversion to a SCEVable type!");
1524   Ty = getEffectiveSCEVType(Ty);
1525 
1526   // Fold if the operand is constant.
1527   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1528     return getConstant(
1529       cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
1530 
1531   // zext(zext(x)) --> zext(x)
1532   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1533     return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1534 
1535   // Before doing any expensive analysis, check to see if we've already
1536   // computed a SCEV for this Op and Ty.
1537   FoldingSetNodeID ID;
1538   ID.AddInteger(scZeroExtend);
1539   ID.AddPointer(Op);
1540   ID.AddPointer(Ty);
1541   void *IP = nullptr;
1542   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1543   if (Depth > MaxExtDepth) {
1544     SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1545                                                      Op, Ty);
1546     UniqueSCEVs.InsertNode(S, IP);
1547     return S;
1548   }
1549 
1550   // zext(trunc(x)) --> zext(x) or x or trunc(x)
1551   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1552     // It's possible the bits taken off by the truncate were all zero bits. If
1553     // so, we should be able to simplify this further.
1554     const SCEV *X = ST->getOperand();
1555     ConstantRange CR = getUnsignedRange(X);
1556     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1557     unsigned NewBits = getTypeSizeInBits(Ty);
1558     if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1559             CR.zextOrTrunc(NewBits)))
1560       return getTruncateOrZeroExtend(X, Ty);
1561   }
1562 
1563   // If the input value is a chrec scev, and we can prove that the value
1564   // did not overflow the old, smaller, value, we can zero extend all of the
1565   // operands (often constants).  This allows analysis of something like
1566   // this:  for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1567   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1568     if (AR->isAffine()) {
1569       const SCEV *Start = AR->getStart();
1570       const SCEV *Step = AR->getStepRecurrence(*this);
1571       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1572       const Loop *L = AR->getLoop();
1573 
1574       if (!AR->hasNoUnsignedWrap()) {
1575         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1576         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1577       }
1578 
1579       // If we have special knowledge that this addrec won't overflow,
1580       // we don't need to do any further analysis.
1581       if (AR->hasNoUnsignedWrap())
1582         return getAddRecExpr(
1583             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1584             getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1585 
1586       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1587       // Note that this serves two purposes: It filters out loops that are
1588       // simply not analyzable, and it covers the case where this code is
1589       // being called from within backedge-taken count analysis, such that
1590       // attempting to ask for the backedge-taken count would likely result
1591       // in infinite recursion. In the later case, the analysis code will
1592       // cope with a conservative value, and it will take care to purge
1593       // that value once it has finished.
1594       const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1595       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1596         // Manually compute the final value for AR, checking for
1597         // overflow.
1598 
1599         // Check whether the backedge-taken count can be losslessly casted to
1600         // the addrec's type. The count is always unsigned.
1601         const SCEV *CastedMaxBECount =
1602           getTruncateOrZeroExtend(MaxBECount, Start->getType());
1603         const SCEV *RecastedMaxBECount =
1604           getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1605         if (MaxBECount == RecastedMaxBECount) {
1606           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1607           // Check whether Start+Step*MaxBECount has no unsigned overflow.
1608           const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step,
1609                                         SCEV::FlagAnyWrap, Depth + 1);
1610           const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul,
1611                                                           SCEV::FlagAnyWrap,
1612                                                           Depth + 1),
1613                                                WideTy, Depth + 1);
1614           const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
1615           const SCEV *WideMaxBECount =
1616             getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1617           const SCEV *OperandExtendedAdd =
1618             getAddExpr(WideStart,
1619                        getMulExpr(WideMaxBECount,
1620                                   getZeroExtendExpr(Step, WideTy, Depth + 1),
1621                                   SCEV::FlagAnyWrap, Depth + 1),
1622                        SCEV::FlagAnyWrap, Depth + 1);
1623           if (ZAdd == OperandExtendedAdd) {
1624             // Cache knowledge of AR NUW, which is propagated to this AddRec.
1625             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1626             // Return the expression with the addrec on the outside.
1627             return getAddRecExpr(
1628                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1629                                                          Depth + 1),
1630                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1631                 AR->getNoWrapFlags());
1632           }
1633           // Similar to above, only this time treat the step value as signed.
1634           // This covers loops that count down.
1635           OperandExtendedAdd =
1636             getAddExpr(WideStart,
1637                        getMulExpr(WideMaxBECount,
1638                                   getSignExtendExpr(Step, WideTy, Depth + 1),
1639                                   SCEV::FlagAnyWrap, Depth + 1),
1640                        SCEV::FlagAnyWrap, Depth + 1);
1641           if (ZAdd == OperandExtendedAdd) {
1642             // Cache knowledge of AR NW, which is propagated to this AddRec.
1643             // Negative step causes unsigned wrap, but it still can't self-wrap.
1644             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1645             // Return the expression with the addrec on the outside.
1646             return getAddRecExpr(
1647                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1648                                                          Depth + 1),
1649                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1650                 AR->getNoWrapFlags());
1651           }
1652         }
1653       }
1654 
1655       // Normally, in the cases we can prove no-overflow via a
1656       // backedge guarding condition, we can also compute a backedge
1657       // taken count for the loop.  The exceptions are assumptions and
1658       // guards present in the loop -- SCEV is not great at exploiting
1659       // these to compute max backedge taken counts, but can still use
1660       // these to prove lack of overflow.  Use this fact to avoid
1661       // doing extra work that may not pay off.
1662       if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1663           !AC.assumptions().empty()) {
1664         // If the backedge is guarded by a comparison with the pre-inc
1665         // value the addrec is safe. Also, if the entry is guarded by
1666         // a comparison with the start value and the backedge is
1667         // guarded by a comparison with the post-inc value, the addrec
1668         // is safe.
1669         if (isKnownPositive(Step)) {
1670           const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
1671                                       getUnsignedRangeMax(Step));
1672           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
1673               (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
1674                isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
1675                                            AR->getPostIncExpr(*this), N))) {
1676             // Cache knowledge of AR NUW, which is propagated to this
1677             // AddRec.
1678             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1679             // Return the expression with the addrec on the outside.
1680             return getAddRecExpr(
1681                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1682                                                          Depth + 1),
1683                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1684                 AR->getNoWrapFlags());
1685           }
1686         } else if (isKnownNegative(Step)) {
1687           const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1688                                       getSignedRangeMin(Step));
1689           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1690               (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) &&
1691                isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
1692                                            AR->getPostIncExpr(*this), N))) {
1693             // Cache knowledge of AR NW, which is propagated to this
1694             // AddRec.  Negative step causes unsigned wrap, but it
1695             // still can't self-wrap.
1696             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1697             // Return the expression with the addrec on the outside.
1698             return getAddRecExpr(
1699                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1700                                                          Depth + 1),
1701                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1702                 AR->getNoWrapFlags());
1703           }
1704         }
1705       }
1706 
1707       if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1708         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1709         return getAddRecExpr(
1710             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1711             getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1712       }
1713     }
1714 
1715   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1716     // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1717     if (SA->hasNoUnsignedWrap()) {
1718       // If the addition does not unsign overflow then we can, by definition,
1719       // commute the zero extension with the addition operation.
1720       SmallVector<const SCEV *, 4> Ops;
1721       for (const auto *Op : SA->operands())
1722         Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1723       return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1);
1724     }
1725   }
1726 
1727   // The cast wasn't folded; create an explicit cast node.
1728   // Recompute the insert position, as it may have been invalidated.
1729   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1730   SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1731                                                    Op, Ty);
1732   UniqueSCEVs.InsertNode(S, IP);
1733   return S;
1734 }
1735 
1736 const SCEV *
1737 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1738   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1739          "This is not an extending conversion!");
1740   assert(isSCEVable(Ty) &&
1741          "This is not a conversion to a SCEVable type!");
1742   Ty = getEffectiveSCEVType(Ty);
1743 
1744   // Fold if the operand is constant.
1745   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1746     return getConstant(
1747       cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
1748 
1749   // sext(sext(x)) --> sext(x)
1750   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1751     return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1);
1752 
1753   // sext(zext(x)) --> zext(x)
1754   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1755     return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1756 
1757   // Before doing any expensive analysis, check to see if we've already
1758   // computed a SCEV for this Op and Ty.
1759   FoldingSetNodeID ID;
1760   ID.AddInteger(scSignExtend);
1761   ID.AddPointer(Op);
1762   ID.AddPointer(Ty);
1763   void *IP = nullptr;
1764   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1765   // Limit recursion depth.
1766   if (Depth > MaxExtDepth) {
1767     SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1768                                                      Op, Ty);
1769     UniqueSCEVs.InsertNode(S, IP);
1770     return S;
1771   }
1772 
1773   // sext(trunc(x)) --> sext(x) or x or trunc(x)
1774   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1775     // It's possible the bits taken off by the truncate were all sign bits. If
1776     // so, we should be able to simplify this further.
1777     const SCEV *X = ST->getOperand();
1778     ConstantRange CR = getSignedRange(X);
1779     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1780     unsigned NewBits = getTypeSizeInBits(Ty);
1781     if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1782             CR.sextOrTrunc(NewBits)))
1783       return getTruncateOrSignExtend(X, Ty);
1784   }
1785 
1786   // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2
1787   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1788     if (SA->getNumOperands() == 2) {
1789       auto *SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0));
1790       auto *SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1));
1791       if (SMul && SC1) {
1792         if (auto *SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) {
1793           const APInt &C1 = SC1->getAPInt();
1794           const APInt &C2 = SC2->getAPInt();
1795           if (C1.isStrictlyPositive() && C2.isStrictlyPositive() &&
1796               C2.ugt(C1) && C2.isPowerOf2())
1797             return getAddExpr(getSignExtendExpr(SC1, Ty, Depth + 1),
1798                               getSignExtendExpr(SMul, Ty, Depth + 1),
1799                               SCEV::FlagAnyWrap, Depth + 1);
1800         }
1801       }
1802     }
1803 
1804     // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1805     if (SA->hasNoSignedWrap()) {
1806       // If the addition does not sign overflow then we can, by definition,
1807       // commute the sign extension with the addition operation.
1808       SmallVector<const SCEV *, 4> Ops;
1809       for (const auto *Op : SA->operands())
1810         Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1));
1811       return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1);
1812     }
1813   }
1814   // If the input value is a chrec scev, and we can prove that the value
1815   // did not overflow the old, smaller, value, we can sign extend all of the
1816   // operands (often constants).  This allows analysis of something like
1817   // this:  for (signed char X = 0; X < 100; ++X) { int Y = X; }
1818   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1819     if (AR->isAffine()) {
1820       const SCEV *Start = AR->getStart();
1821       const SCEV *Step = AR->getStepRecurrence(*this);
1822       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1823       const Loop *L = AR->getLoop();
1824 
1825       if (!AR->hasNoSignedWrap()) {
1826         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1827         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1828       }
1829 
1830       // If we have special knowledge that this addrec won't overflow,
1831       // we don't need to do any further analysis.
1832       if (AR->hasNoSignedWrap())
1833         return getAddRecExpr(
1834             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
1835             getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW);
1836 
1837       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1838       // Note that this serves two purposes: It filters out loops that are
1839       // simply not analyzable, and it covers the case where this code is
1840       // being called from within backedge-taken count analysis, such that
1841       // attempting to ask for the backedge-taken count would likely result
1842       // in infinite recursion. In the later case, the analysis code will
1843       // cope with a conservative value, and it will take care to purge
1844       // that value once it has finished.
1845       const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1846       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1847         // Manually compute the final value for AR, checking for
1848         // overflow.
1849 
1850         // Check whether the backedge-taken count can be losslessly casted to
1851         // the addrec's type. The count is always unsigned.
1852         const SCEV *CastedMaxBECount =
1853           getTruncateOrZeroExtend(MaxBECount, Start->getType());
1854         const SCEV *RecastedMaxBECount =
1855           getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1856         if (MaxBECount == RecastedMaxBECount) {
1857           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1858           // Check whether Start+Step*MaxBECount has no signed overflow.
1859           const SCEV *SMul = getMulExpr(CastedMaxBECount, Step,
1860                                         SCEV::FlagAnyWrap, Depth + 1);
1861           const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul,
1862                                                           SCEV::FlagAnyWrap,
1863                                                           Depth + 1),
1864                                                WideTy, Depth + 1);
1865           const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
1866           const SCEV *WideMaxBECount =
1867             getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1868           const SCEV *OperandExtendedAdd =
1869             getAddExpr(WideStart,
1870                        getMulExpr(WideMaxBECount,
1871                                   getSignExtendExpr(Step, WideTy, Depth + 1),
1872                                   SCEV::FlagAnyWrap, Depth + 1),
1873                        SCEV::FlagAnyWrap, Depth + 1);
1874           if (SAdd == OperandExtendedAdd) {
1875             // Cache knowledge of AR NSW, which is propagated to this AddRec.
1876             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1877             // Return the expression with the addrec on the outside.
1878             return getAddRecExpr(
1879                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
1880                                                          Depth + 1),
1881                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1882                 AR->getNoWrapFlags());
1883           }
1884           // Similar to above, only this time treat the step value as unsigned.
1885           // This covers loops that count up with an unsigned step.
1886           OperandExtendedAdd =
1887             getAddExpr(WideStart,
1888                        getMulExpr(WideMaxBECount,
1889                                   getZeroExtendExpr(Step, WideTy, Depth + 1),
1890                                   SCEV::FlagAnyWrap, Depth + 1),
1891                        SCEV::FlagAnyWrap, Depth + 1);
1892           if (SAdd == OperandExtendedAdd) {
1893             // If AR wraps around then
1894             //
1895             //    abs(Step) * MaxBECount > unsigned-max(AR->getType())
1896             // => SAdd != OperandExtendedAdd
1897             //
1898             // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
1899             // (SAdd == OperandExtendedAdd => AR is NW)
1900 
1901             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1902 
1903             // Return the expression with the addrec on the outside.
1904             return getAddRecExpr(
1905                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
1906                                                          Depth + 1),
1907                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1908                 AR->getNoWrapFlags());
1909           }
1910         }
1911       }
1912 
1913       // Normally, in the cases we can prove no-overflow via a
1914       // backedge guarding condition, we can also compute a backedge
1915       // taken count for the loop.  The exceptions are assumptions and
1916       // guards present in the loop -- SCEV is not great at exploiting
1917       // these to compute max backedge taken counts, but can still use
1918       // these to prove lack of overflow.  Use this fact to avoid
1919       // doing extra work that may not pay off.
1920 
1921       if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1922           !AC.assumptions().empty()) {
1923         // If the backedge is guarded by a comparison with the pre-inc
1924         // value the addrec is safe. Also, if the entry is guarded by
1925         // a comparison with the start value and the backedge is
1926         // guarded by a comparison with the post-inc value, the addrec
1927         // is safe.
1928         ICmpInst::Predicate Pred;
1929         const SCEV *OverflowLimit =
1930             getSignedOverflowLimitForStep(Step, &Pred, this);
1931         if (OverflowLimit &&
1932             (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
1933              (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) &&
1934               isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this),
1935                                           OverflowLimit)))) {
1936           // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec.
1937           const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1938           return getAddRecExpr(
1939               getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
1940               getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1941         }
1942       }
1943 
1944       // If Start and Step are constants, check if we can apply this
1945       // transformation:
1946       // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2
1947       auto *SC1 = dyn_cast<SCEVConstant>(Start);
1948       auto *SC2 = dyn_cast<SCEVConstant>(Step);
1949       if (SC1 && SC2) {
1950         const APInt &C1 = SC1->getAPInt();
1951         const APInt &C2 = SC2->getAPInt();
1952         if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) &&
1953             C2.isPowerOf2()) {
1954           Start = getSignExtendExpr(Start, Ty, Depth + 1);
1955           const SCEV *NewAR = getAddRecExpr(getZero(AR->getType()), Step, L,
1956                                             AR->getNoWrapFlags());
1957           return getAddExpr(Start, getSignExtendExpr(NewAR, Ty, Depth + 1),
1958                             SCEV::FlagAnyWrap, Depth + 1);
1959         }
1960       }
1961 
1962       if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
1963         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1964         return getAddRecExpr(
1965             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
1966             getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1967       }
1968     }
1969 
1970   // If the input value is provably positive and we could not simplify
1971   // away the sext build a zext instead.
1972   if (isKnownNonNegative(Op))
1973     return getZeroExtendExpr(Op, Ty, Depth + 1);
1974 
1975   // The cast wasn't folded; create an explicit cast node.
1976   // Recompute the insert position, as it may have been invalidated.
1977   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1978   SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1979                                                    Op, Ty);
1980   UniqueSCEVs.InsertNode(S, IP);
1981   return S;
1982 }
1983 
1984 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
1985 /// unspecified bits out to the given type.
1986 ///
1987 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
1988                                               Type *Ty) {
1989   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1990          "This is not an extending conversion!");
1991   assert(isSCEVable(Ty) &&
1992          "This is not a conversion to a SCEVable type!");
1993   Ty = getEffectiveSCEVType(Ty);
1994 
1995   // Sign-extend negative constants.
1996   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1997     if (SC->getAPInt().isNegative())
1998       return getSignExtendExpr(Op, Ty);
1999 
2000   // Peel off a truncate cast.
2001   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
2002     const SCEV *NewOp = T->getOperand();
2003     if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
2004       return getAnyExtendExpr(NewOp, Ty);
2005     return getTruncateOrNoop(NewOp, Ty);
2006   }
2007 
2008   // Next try a zext cast. If the cast is folded, use it.
2009   const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2010   if (!isa<SCEVZeroExtendExpr>(ZExt))
2011     return ZExt;
2012 
2013   // Next try a sext cast. If the cast is folded, use it.
2014   const SCEV *SExt = getSignExtendExpr(Op, Ty);
2015   if (!isa<SCEVSignExtendExpr>(SExt))
2016     return SExt;
2017 
2018   // Force the cast to be folded into the operands of an addrec.
2019   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2020     SmallVector<const SCEV *, 4> Ops;
2021     for (const SCEV *Op : AR->operands())
2022       Ops.push_back(getAnyExtendExpr(Op, Ty));
2023     return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2024   }
2025 
2026   // If the expression is obviously signed, use the sext cast value.
2027   if (isa<SCEVSMaxExpr>(Op))
2028     return SExt;
2029 
2030   // Absent any other information, use the zext cast value.
2031   return ZExt;
2032 }
2033 
2034 /// Process the given Ops list, which is a list of operands to be added under
2035 /// the given scale, update the given map. This is a helper function for
2036 /// getAddRecExpr. As an example of what it does, given a sequence of operands
2037 /// that would form an add expression like this:
2038 ///
2039 ///    m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2040 ///
2041 /// where A and B are constants, update the map with these values:
2042 ///
2043 ///    (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2044 ///
2045 /// and add 13 + A*B*29 to AccumulatedConstant.
2046 /// This will allow getAddRecExpr to produce this:
2047 ///
2048 ///    13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2049 ///
2050 /// This form often exposes folding opportunities that are hidden in
2051 /// the original operand list.
2052 ///
2053 /// Return true iff it appears that any interesting folding opportunities
2054 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
2055 /// the common case where no interesting opportunities are present, and
2056 /// is also used as a check to avoid infinite recursion.
2057 ///
2058 static bool
2059 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
2060                              SmallVectorImpl<const SCEV *> &NewOps,
2061                              APInt &AccumulatedConstant,
2062                              const SCEV *const *Ops, size_t NumOperands,
2063                              const APInt &Scale,
2064                              ScalarEvolution &SE) {
2065   bool Interesting = false;
2066 
2067   // Iterate over the add operands. They are sorted, with constants first.
2068   unsigned i = 0;
2069   while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2070     ++i;
2071     // Pull a buried constant out to the outside.
2072     if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2073       Interesting = true;
2074     AccumulatedConstant += Scale * C->getAPInt();
2075   }
2076 
2077   // Next comes everything else. We're especially interested in multiplies
2078   // here, but they're in the middle, so just visit the rest with one loop.
2079   for (; i != NumOperands; ++i) {
2080     const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
2081     if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2082       APInt NewScale =
2083           Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2084       if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2085         // A multiplication of a constant with another add; recurse.
2086         const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2087         Interesting |=
2088           CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2089                                        Add->op_begin(), Add->getNumOperands(),
2090                                        NewScale, SE);
2091       } else {
2092         // A multiplication of a constant with some other value. Update
2093         // the map.
2094         SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
2095         const SCEV *Key = SE.getMulExpr(MulOps);
2096         auto Pair = M.insert({Key, NewScale});
2097         if (Pair.second) {
2098           NewOps.push_back(Pair.first->first);
2099         } else {
2100           Pair.first->second += NewScale;
2101           // The map already had an entry for this value, which may indicate
2102           // a folding opportunity.
2103           Interesting = true;
2104         }
2105       }
2106     } else {
2107       // An ordinary operand. Update the map.
2108       std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
2109           M.insert({Ops[i], Scale});
2110       if (Pair.second) {
2111         NewOps.push_back(Pair.first->first);
2112       } else {
2113         Pair.first->second += Scale;
2114         // The map already had an entry for this value, which may indicate
2115         // a folding opportunity.
2116         Interesting = true;
2117       }
2118     }
2119   }
2120 
2121   return Interesting;
2122 }
2123 
2124 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2125 // `OldFlags' as can't-wrap behavior.  Infer a more aggressive set of
2126 // can't-overflow flags for the operation if possible.
2127 static SCEV::NoWrapFlags
2128 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
2129                       const SmallVectorImpl<const SCEV *> &Ops,
2130                       SCEV::NoWrapFlags Flags) {
2131   using namespace std::placeholders;
2132   typedef OverflowingBinaryOperator OBO;
2133 
2134   bool CanAnalyze =
2135       Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
2136   (void)CanAnalyze;
2137   assert(CanAnalyze && "don't call from other places!");
2138 
2139   int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2140   SCEV::NoWrapFlags SignOrUnsignWrap =
2141       ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2142 
2143   // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2144   auto IsKnownNonNegative = [&](const SCEV *S) {
2145     return SE->isKnownNonNegative(S);
2146   };
2147 
2148   if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2149     Flags =
2150         ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
2151 
2152   SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2153 
2154   if (SignOrUnsignWrap != SignOrUnsignMask && Type == scAddExpr &&
2155       Ops.size() == 2 && isa<SCEVConstant>(Ops[0])) {
2156 
2157     // (A + C) --> (A + C)<nsw> if the addition does not sign overflow
2158     // (A + C) --> (A + C)<nuw> if the addition does not unsign overflow
2159 
2160     const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2161     if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2162       auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2163           Instruction::Add, C, OBO::NoSignedWrap);
2164       if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2165         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2166     }
2167     if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2168       auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2169           Instruction::Add, C, OBO::NoUnsignedWrap);
2170       if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2171         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2172     }
2173   }
2174 
2175   return Flags;
2176 }
2177 
2178 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) {
2179   if (!isLoopInvariant(S, L))
2180     return false;
2181   // If a value depends on a SCEVUnknown which is defined after the loop, we
2182   // conservatively assume that we cannot calculate it at the loop's entry.
2183   struct FindDominatedSCEVUnknown {
2184     bool Found = false;
2185     const Loop *L;
2186     DominatorTree &DT;
2187     LoopInfo &LI;
2188 
2189     FindDominatedSCEVUnknown(const Loop *L, DominatorTree &DT, LoopInfo &LI)
2190         : L(L), DT(DT), LI(LI) {}
2191 
2192     bool checkSCEVUnknown(const SCEVUnknown *SU) {
2193       if (auto *I = dyn_cast<Instruction>(SU->getValue())) {
2194         if (DT.dominates(L->getHeader(), I->getParent()))
2195           Found = true;
2196         else
2197           assert(DT.dominates(I->getParent(), L->getHeader()) &&
2198                  "No dominance relationship between SCEV and loop?");
2199       }
2200       return false;
2201     }
2202 
2203     bool follow(const SCEV *S) {
2204       switch (static_cast<SCEVTypes>(S->getSCEVType())) {
2205       case scConstant:
2206         return false;
2207       case scAddRecExpr:
2208       case scTruncate:
2209       case scZeroExtend:
2210       case scSignExtend:
2211       case scAddExpr:
2212       case scMulExpr:
2213       case scUMaxExpr:
2214       case scSMaxExpr:
2215       case scUDivExpr:
2216         return true;
2217       case scUnknown:
2218         return checkSCEVUnknown(cast<SCEVUnknown>(S));
2219       case scCouldNotCompute:
2220         llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
2221       }
2222       return false;
2223     }
2224 
2225     bool isDone() { return Found; }
2226   };
2227 
2228   FindDominatedSCEVUnknown FSU(L, DT, LI);
2229   SCEVTraversal<FindDominatedSCEVUnknown> ST(FSU);
2230   ST.visitAll(S);
2231   return !FSU.Found;
2232 }
2233 
2234 /// Get a canonical add expression, or something simpler if possible.
2235 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2236                                         SCEV::NoWrapFlags Flags,
2237                                         unsigned Depth) {
2238   assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2239          "only nuw or nsw allowed");
2240   assert(!Ops.empty() && "Cannot get empty add!");
2241   if (Ops.size() == 1) return Ops[0];
2242 #ifndef NDEBUG
2243   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2244   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2245     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2246            "SCEVAddExpr operand types don't match!");
2247 #endif
2248 
2249   // Sort by complexity, this groups all similar expression types together.
2250   GroupByComplexity(Ops, &LI, DT);
2251 
2252   Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags);
2253 
2254   // If there are any constants, fold them together.
2255   unsigned Idx = 0;
2256   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2257     ++Idx;
2258     assert(Idx < Ops.size());
2259     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2260       // We found two constants, fold them together!
2261       Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
2262       if (Ops.size() == 2) return Ops[0];
2263       Ops.erase(Ops.begin()+1);  // Erase the folded element
2264       LHSC = cast<SCEVConstant>(Ops[0]);
2265     }
2266 
2267     // If we are left with a constant zero being added, strip it off.
2268     if (LHSC->getValue()->isZero()) {
2269       Ops.erase(Ops.begin());
2270       --Idx;
2271     }
2272 
2273     if (Ops.size() == 1) return Ops[0];
2274   }
2275 
2276   // Limit recursion calls depth.
2277   if (Depth > MaxArithDepth)
2278     return getOrCreateAddExpr(Ops, Flags);
2279 
2280   // Okay, check to see if the same value occurs in the operand list more than
2281   // once.  If so, merge them together into an multiply expression.  Since we
2282   // sorted the list, these values are required to be adjacent.
2283   Type *Ty = Ops[0]->getType();
2284   bool FoundMatch = false;
2285   for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2286     if (Ops[i] == Ops[i+1]) {      //  X + Y + Y  -->  X + Y*2
2287       // Scan ahead to count how many equal operands there are.
2288       unsigned Count = 2;
2289       while (i+Count != e && Ops[i+Count] == Ops[i])
2290         ++Count;
2291       // Merge the values into a multiply.
2292       const SCEV *Scale = getConstant(Ty, Count);
2293       const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1);
2294       if (Ops.size() == Count)
2295         return Mul;
2296       Ops[i] = Mul;
2297       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2298       --i; e -= Count - 1;
2299       FoundMatch = true;
2300     }
2301   if (FoundMatch)
2302     return getAddExpr(Ops, Flags);
2303 
2304   // Check for truncates. If all the operands are truncated from the same
2305   // type, see if factoring out the truncate would permit the result to be
2306   // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
2307   // if the contents of the resulting outer trunc fold to something simple.
2308   for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
2309     const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
2310     Type *DstType = Trunc->getType();
2311     Type *SrcType = Trunc->getOperand()->getType();
2312     SmallVector<const SCEV *, 8> LargeOps;
2313     bool Ok = true;
2314     // Check all the operands to see if they can be represented in the
2315     // source type of the truncate.
2316     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2317       if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2318         if (T->getOperand()->getType() != SrcType) {
2319           Ok = false;
2320           break;
2321         }
2322         LargeOps.push_back(T->getOperand());
2323       } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2324         LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2325       } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
2326         SmallVector<const SCEV *, 8> LargeMulOps;
2327         for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2328           if (const SCEVTruncateExpr *T =
2329                 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2330             if (T->getOperand()->getType() != SrcType) {
2331               Ok = false;
2332               break;
2333             }
2334             LargeMulOps.push_back(T->getOperand());
2335           } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2336             LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2337           } else {
2338             Ok = false;
2339             break;
2340           }
2341         }
2342         if (Ok)
2343           LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1));
2344       } else {
2345         Ok = false;
2346         break;
2347       }
2348     }
2349     if (Ok) {
2350       // Evaluate the expression in the larger type.
2351       const SCEV *Fold = getAddExpr(LargeOps, Flags, Depth + 1);
2352       // If it folds to something simple, use it. Otherwise, don't.
2353       if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2354         return getTruncateExpr(Fold, DstType);
2355     }
2356   }
2357 
2358   // Skip past any other cast SCEVs.
2359   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2360     ++Idx;
2361 
2362   // If there are add operands they would be next.
2363   if (Idx < Ops.size()) {
2364     bool DeletedAdd = false;
2365     while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2366       if (Ops.size() > AddOpsInlineThreshold ||
2367           Add->getNumOperands() > AddOpsInlineThreshold)
2368         break;
2369       // If we have an add, expand the add operands onto the end of the operands
2370       // list.
2371       Ops.erase(Ops.begin()+Idx);
2372       Ops.append(Add->op_begin(), Add->op_end());
2373       DeletedAdd = true;
2374     }
2375 
2376     // If we deleted at least one add, we added operands to the end of the list,
2377     // and they are not necessarily sorted.  Recurse to resort and resimplify
2378     // any operands we just acquired.
2379     if (DeletedAdd)
2380       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2381   }
2382 
2383   // Skip over the add expression until we get to a multiply.
2384   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2385     ++Idx;
2386 
2387   // Check to see if there are any folding opportunities present with
2388   // operands multiplied by constant values.
2389   if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2390     uint64_t BitWidth = getTypeSizeInBits(Ty);
2391     DenseMap<const SCEV *, APInt> M;
2392     SmallVector<const SCEV *, 8> NewOps;
2393     APInt AccumulatedConstant(BitWidth, 0);
2394     if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2395                                      Ops.data(), Ops.size(),
2396                                      APInt(BitWidth, 1), *this)) {
2397       struct APIntCompare {
2398         bool operator()(const APInt &LHS, const APInt &RHS) const {
2399           return LHS.ult(RHS);
2400         }
2401       };
2402 
2403       // Some interesting folding opportunity is present, so its worthwhile to
2404       // re-generate the operands list. Group the operands by constant scale,
2405       // to avoid multiplying by the same constant scale multiple times.
2406       std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
2407       for (const SCEV *NewOp : NewOps)
2408         MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2409       // Re-generate the operands list.
2410       Ops.clear();
2411       if (AccumulatedConstant != 0)
2412         Ops.push_back(getConstant(AccumulatedConstant));
2413       for (auto &MulOp : MulOpLists)
2414         if (MulOp.first != 0)
2415           Ops.push_back(getMulExpr(
2416               getConstant(MulOp.first),
2417               getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1),
2418               SCEV::FlagAnyWrap, Depth + 1));
2419       if (Ops.empty())
2420         return getZero(Ty);
2421       if (Ops.size() == 1)
2422         return Ops[0];
2423       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2424     }
2425   }
2426 
2427   // If we are adding something to a multiply expression, make sure the
2428   // something is not already an operand of the multiply.  If so, merge it into
2429   // the multiply.
2430   for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2431     const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2432     for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2433       const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2434       if (isa<SCEVConstant>(MulOpSCEV))
2435         continue;
2436       for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
2437         if (MulOpSCEV == Ops[AddOp]) {
2438           // Fold W + X + (X * Y * Z)  -->  W + (X * ((Y*Z)+1))
2439           const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
2440           if (Mul->getNumOperands() != 2) {
2441             // If the multiply has more than two operands, we must get the
2442             // Y*Z term.
2443             SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2444                                                 Mul->op_begin()+MulOp);
2445             MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2446             InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2447           }
2448           SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul};
2449           const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2450           const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV,
2451                                             SCEV::FlagAnyWrap, Depth + 1);
2452           if (Ops.size() == 2) return OuterMul;
2453           if (AddOp < Idx) {
2454             Ops.erase(Ops.begin()+AddOp);
2455             Ops.erase(Ops.begin()+Idx-1);
2456           } else {
2457             Ops.erase(Ops.begin()+Idx);
2458             Ops.erase(Ops.begin()+AddOp-1);
2459           }
2460           Ops.push_back(OuterMul);
2461           return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2462         }
2463 
2464       // Check this multiply against other multiplies being added together.
2465       for (unsigned OtherMulIdx = Idx+1;
2466            OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2467            ++OtherMulIdx) {
2468         const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
2469         // If MulOp occurs in OtherMul, we can fold the two multiplies
2470         // together.
2471         for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2472              OMulOp != e; ++OMulOp)
2473           if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2474             // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
2475             const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
2476             if (Mul->getNumOperands() != 2) {
2477               SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2478                                                   Mul->op_begin()+MulOp);
2479               MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2480               InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2481             }
2482             const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
2483             if (OtherMul->getNumOperands() != 2) {
2484               SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
2485                                                   OtherMul->op_begin()+OMulOp);
2486               MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
2487               InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2488             }
2489             SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2};
2490             const SCEV *InnerMulSum =
2491                 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2492             const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum,
2493                                               SCEV::FlagAnyWrap, Depth + 1);
2494             if (Ops.size() == 2) return OuterMul;
2495             Ops.erase(Ops.begin()+Idx);
2496             Ops.erase(Ops.begin()+OtherMulIdx-1);
2497             Ops.push_back(OuterMul);
2498             return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2499           }
2500       }
2501     }
2502   }
2503 
2504   // If there are any add recurrences in the operands list, see if any other
2505   // added values are loop invariant.  If so, we can fold them into the
2506   // recurrence.
2507   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2508     ++Idx;
2509 
2510   // Scan over all recurrences, trying to fold loop invariants into them.
2511   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2512     // Scan all of the other operands to this add and add them to the vector if
2513     // they are loop invariant w.r.t. the recurrence.
2514     SmallVector<const SCEV *, 8> LIOps;
2515     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2516     const Loop *AddRecLoop = AddRec->getLoop();
2517     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2518       if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2519         LIOps.push_back(Ops[i]);
2520         Ops.erase(Ops.begin()+i);
2521         --i; --e;
2522       }
2523 
2524     // If we found some loop invariants, fold them into the recurrence.
2525     if (!LIOps.empty()) {
2526       //  NLI + LI + {Start,+,Step}  -->  NLI + {LI+Start,+,Step}
2527       LIOps.push_back(AddRec->getStart());
2528 
2529       SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2530                                              AddRec->op_end());
2531       // This follows from the fact that the no-wrap flags on the outer add
2532       // expression are applicable on the 0th iteration, when the add recurrence
2533       // will be equal to its start value.
2534       AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1);
2535 
2536       // Build the new addrec. Propagate the NUW and NSW flags if both the
2537       // outer add and the inner addrec are guaranteed to have no overflow.
2538       // Always propagate NW.
2539       Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2540       const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2541 
2542       // If all of the other operands were loop invariant, we are done.
2543       if (Ops.size() == 1) return NewRec;
2544 
2545       // Otherwise, add the folded AddRec by the non-invariant parts.
2546       for (unsigned i = 0;; ++i)
2547         if (Ops[i] == AddRec) {
2548           Ops[i] = NewRec;
2549           break;
2550         }
2551       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2552     }
2553 
2554     // Okay, if there weren't any loop invariants to be folded, check to see if
2555     // there are multiple AddRec's with the same loop induction variable being
2556     // added together.  If so, we can fold them.
2557     for (unsigned OtherIdx = Idx+1;
2558          OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2559          ++OtherIdx) {
2560       // We expect the AddRecExpr's to be sorted in reverse dominance order,
2561       // so that the 1st found AddRecExpr is dominated by all others.
2562       assert(DT.dominates(
2563            cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
2564            AddRec->getLoop()->getHeader()) &&
2565         "AddRecExprs are not sorted in reverse dominance order?");
2566       if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2567         // Other + {A,+,B}<L> + {C,+,D}<L>  -->  Other + {A+C,+,B+D}<L>
2568         SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2569                                                AddRec->op_end());
2570         for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2571              ++OtherIdx) {
2572           const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2573           if (OtherAddRec->getLoop() == AddRecLoop) {
2574             for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2575                  i != e; ++i) {
2576               if (i >= AddRecOps.size()) {
2577                 AddRecOps.append(OtherAddRec->op_begin()+i,
2578                                  OtherAddRec->op_end());
2579                 break;
2580               }
2581               SmallVector<const SCEV *, 2> TwoOps = {
2582                   AddRecOps[i], OtherAddRec->getOperand(i)};
2583               AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2584             }
2585             Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2586           }
2587         }
2588         // Step size has changed, so we cannot guarantee no self-wraparound.
2589         Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2590         return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2591       }
2592     }
2593 
2594     // Otherwise couldn't fold anything into this recurrence.  Move onto the
2595     // next one.
2596   }
2597 
2598   // Okay, it looks like we really DO need an add expr.  Check to see if we
2599   // already have one, otherwise create a new one.
2600   return getOrCreateAddExpr(Ops, Flags);
2601 }
2602 
2603 const SCEV *
2604 ScalarEvolution::getOrCreateAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2605                                     SCEV::NoWrapFlags Flags) {
2606   FoldingSetNodeID ID;
2607   ID.AddInteger(scAddExpr);
2608   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2609     ID.AddPointer(Ops[i]);
2610   void *IP = nullptr;
2611   SCEVAddExpr *S =
2612       static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2613   if (!S) {
2614     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2615     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2616     S = new (SCEVAllocator)
2617         SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
2618     UniqueSCEVs.InsertNode(S, IP);
2619   }
2620   S->setNoWrapFlags(Flags);
2621   return S;
2622 }
2623 
2624 const SCEV *
2625 ScalarEvolution::getOrCreateMulExpr(SmallVectorImpl<const SCEV *> &Ops,
2626                                     SCEV::NoWrapFlags Flags) {
2627   FoldingSetNodeID ID;
2628   ID.AddInteger(scMulExpr);
2629   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2630     ID.AddPointer(Ops[i]);
2631   void *IP = nullptr;
2632   SCEVMulExpr *S =
2633     static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2634   if (!S) {
2635     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2636     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2637     S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2638                                         O, Ops.size());
2639     UniqueSCEVs.InsertNode(S, IP);
2640   }
2641   S->setNoWrapFlags(Flags);
2642   return S;
2643 }
2644 
2645 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2646   uint64_t k = i*j;
2647   if (j > 1 && k / j != i) Overflow = true;
2648   return k;
2649 }
2650 
2651 /// Compute the result of "n choose k", the binomial coefficient.  If an
2652 /// intermediate computation overflows, Overflow will be set and the return will
2653 /// be garbage. Overflow is not cleared on absence of overflow.
2654 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2655   // We use the multiplicative formula:
2656   //     n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2657   // At each iteration, we take the n-th term of the numeral and divide by the
2658   // (k-n)th term of the denominator.  This division will always produce an
2659   // integral result, and helps reduce the chance of overflow in the
2660   // intermediate computations. However, we can still overflow even when the
2661   // final result would fit.
2662 
2663   if (n == 0 || n == k) return 1;
2664   if (k > n) return 0;
2665 
2666   if (k > n/2)
2667     k = n-k;
2668 
2669   uint64_t r = 1;
2670   for (uint64_t i = 1; i <= k; ++i) {
2671     r = umul_ov(r, n-(i-1), Overflow);
2672     r /= i;
2673   }
2674   return r;
2675 }
2676 
2677 /// Determine if any of the operands in this SCEV are a constant or if
2678 /// any of the add or multiply expressions in this SCEV contain a constant.
2679 static bool containsConstantSomewhere(const SCEV *StartExpr) {
2680   SmallVector<const SCEV *, 4> Ops;
2681   Ops.push_back(StartExpr);
2682   while (!Ops.empty()) {
2683     const SCEV *CurrentExpr = Ops.pop_back_val();
2684     if (isa<SCEVConstant>(*CurrentExpr))
2685       return true;
2686 
2687     if (isa<SCEVAddExpr>(*CurrentExpr) || isa<SCEVMulExpr>(*CurrentExpr)) {
2688       const auto *CurrentNAry = cast<SCEVNAryExpr>(CurrentExpr);
2689       Ops.append(CurrentNAry->op_begin(), CurrentNAry->op_end());
2690     }
2691   }
2692   return false;
2693 }
2694 
2695 /// Get a canonical multiply expression, or something simpler if possible.
2696 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
2697                                         SCEV::NoWrapFlags Flags,
2698                                         unsigned Depth) {
2699   assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&
2700          "only nuw or nsw allowed");
2701   assert(!Ops.empty() && "Cannot get empty mul!");
2702   if (Ops.size() == 1) return Ops[0];
2703 #ifndef NDEBUG
2704   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2705   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2706     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2707            "SCEVMulExpr operand types don't match!");
2708 #endif
2709 
2710   // Sort by complexity, this groups all similar expression types together.
2711   GroupByComplexity(Ops, &LI, DT);
2712 
2713   Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags);
2714 
2715   // Limit recursion calls depth.
2716   if (Depth > MaxArithDepth)
2717     return getOrCreateMulExpr(Ops, Flags);
2718 
2719   // If there are any constants, fold them together.
2720   unsigned Idx = 0;
2721   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2722 
2723     // C1*(C2+V) -> C1*C2 + C1*V
2724     if (Ops.size() == 2)
2725         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
2726           // If any of Add's ops are Adds or Muls with a constant,
2727           // apply this transformation as well.
2728           if (Add->getNumOperands() == 2)
2729             if (containsConstantSomewhere(Add))
2730               return getAddExpr(getMulExpr(LHSC, Add->getOperand(0),
2731                                            SCEV::FlagAnyWrap, Depth + 1),
2732                                 getMulExpr(LHSC, Add->getOperand(1),
2733                                            SCEV::FlagAnyWrap, Depth + 1),
2734                                 SCEV::FlagAnyWrap, Depth + 1);
2735 
2736     ++Idx;
2737     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2738       // We found two constants, fold them together!
2739       ConstantInt *Fold =
2740           ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt());
2741       Ops[0] = getConstant(Fold);
2742       Ops.erase(Ops.begin()+1);  // Erase the folded element
2743       if (Ops.size() == 1) return Ops[0];
2744       LHSC = cast<SCEVConstant>(Ops[0]);
2745     }
2746 
2747     // If we are left with a constant one being multiplied, strip it off.
2748     if (cast<SCEVConstant>(Ops[0])->getValue()->isOne()) {
2749       Ops.erase(Ops.begin());
2750       --Idx;
2751     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
2752       // If we have a multiply of zero, it will always be zero.
2753       return Ops[0];
2754     } else if (Ops[0]->isAllOnesValue()) {
2755       // If we have a mul by -1 of an add, try distributing the -1 among the
2756       // add operands.
2757       if (Ops.size() == 2) {
2758         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
2759           SmallVector<const SCEV *, 4> NewOps;
2760           bool AnyFolded = false;
2761           for (const SCEV *AddOp : Add->operands()) {
2762             const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap,
2763                                          Depth + 1);
2764             if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
2765             NewOps.push_back(Mul);
2766           }
2767           if (AnyFolded)
2768             return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1);
2769         } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
2770           // Negation preserves a recurrence's no self-wrap property.
2771           SmallVector<const SCEV *, 4> Operands;
2772           for (const SCEV *AddRecOp : AddRec->operands())
2773             Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap,
2774                                           Depth + 1));
2775 
2776           return getAddRecExpr(Operands, AddRec->getLoop(),
2777                                AddRec->getNoWrapFlags(SCEV::FlagNW));
2778         }
2779       }
2780     }
2781 
2782     if (Ops.size() == 1)
2783       return Ops[0];
2784   }
2785 
2786   // Skip over the add expression until we get to a multiply.
2787   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2788     ++Idx;
2789 
2790   // If there are mul operands inline them all into this expression.
2791   if (Idx < Ops.size()) {
2792     bool DeletedMul = false;
2793     while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2794       if (Ops.size() > MulOpsInlineThreshold)
2795         break;
2796       // If we have an mul, expand the mul operands onto the end of the
2797       // operands list.
2798       Ops.erase(Ops.begin()+Idx);
2799       Ops.append(Mul->op_begin(), Mul->op_end());
2800       DeletedMul = true;
2801     }
2802 
2803     // If we deleted at least one mul, we added operands to the end of the
2804     // list, and they are not necessarily sorted.  Recurse to resort and
2805     // resimplify any operands we just acquired.
2806     if (DeletedMul)
2807       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2808   }
2809 
2810   // If there are any add recurrences in the operands list, see if any other
2811   // added values are loop invariant.  If so, we can fold them into the
2812   // recurrence.
2813   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2814     ++Idx;
2815 
2816   // Scan over all recurrences, trying to fold loop invariants into them.
2817   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2818     // Scan all of the other operands to this mul and add them to the vector
2819     // if they are loop invariant w.r.t. the recurrence.
2820     SmallVector<const SCEV *, 8> LIOps;
2821     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2822     const Loop *AddRecLoop = AddRec->getLoop();
2823     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2824       if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2825         LIOps.push_back(Ops[i]);
2826         Ops.erase(Ops.begin()+i);
2827         --i; --e;
2828       }
2829 
2830     // If we found some loop invariants, fold them into the recurrence.
2831     if (!LIOps.empty()) {
2832       //  NLI * LI * {Start,+,Step}  -->  NLI * {LI*Start,+,LI*Step}
2833       SmallVector<const SCEV *, 4> NewOps;
2834       NewOps.reserve(AddRec->getNumOperands());
2835       const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1);
2836       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
2837         NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
2838                                     SCEV::FlagAnyWrap, Depth + 1));
2839 
2840       // Build the new addrec. Propagate the NUW and NSW flags if both the
2841       // outer mul and the inner addrec are guaranteed to have no overflow.
2842       //
2843       // No self-wrap cannot be guaranteed after changing the step size, but
2844       // will be inferred if either NUW or NSW is true.
2845       Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW));
2846       const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
2847 
2848       // If all of the other operands were loop invariant, we are done.
2849       if (Ops.size() == 1) return NewRec;
2850 
2851       // Otherwise, multiply the folded AddRec by the non-invariant parts.
2852       for (unsigned i = 0;; ++i)
2853         if (Ops[i] == AddRec) {
2854           Ops[i] = NewRec;
2855           break;
2856         }
2857       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2858     }
2859 
2860     // Okay, if there weren't any loop invariants to be folded, check to see
2861     // if there are multiple AddRec's with the same loop induction variable
2862     // being multiplied together.  If so, we can fold them.
2863 
2864     // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
2865     // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
2866     //       choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
2867     //   ]]],+,...up to x=2n}.
2868     // Note that the arguments to choose() are always integers with values
2869     // known at compile time, never SCEV objects.
2870     //
2871     // The implementation avoids pointless extra computations when the two
2872     // addrec's are of different length (mathematically, it's equivalent to
2873     // an infinite stream of zeros on the right).
2874     bool OpsModified = false;
2875     for (unsigned OtherIdx = Idx+1;
2876          OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2877          ++OtherIdx) {
2878       const SCEVAddRecExpr *OtherAddRec =
2879         dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2880       if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
2881         continue;
2882 
2883       // Limit max number of arguments to avoid creation of unreasonably big
2884       // SCEVAddRecs with very complex operands.
2885       if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
2886           MaxAddRecSize)
2887         continue;
2888 
2889       bool Overflow = false;
2890       Type *Ty = AddRec->getType();
2891       bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
2892       SmallVector<const SCEV*, 7> AddRecOps;
2893       for (int x = 0, xe = AddRec->getNumOperands() +
2894              OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
2895         const SCEV *Term = getZero(Ty);
2896         for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
2897           uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
2898           for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
2899                  ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
2900                z < ze && !Overflow; ++z) {
2901             uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
2902             uint64_t Coeff;
2903             if (LargerThan64Bits)
2904               Coeff = umul_ov(Coeff1, Coeff2, Overflow);
2905             else
2906               Coeff = Coeff1*Coeff2;
2907             const SCEV *CoeffTerm = getConstant(Ty, Coeff);
2908             const SCEV *Term1 = AddRec->getOperand(y-z);
2909             const SCEV *Term2 = OtherAddRec->getOperand(z);
2910             Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1, Term2,
2911                                                SCEV::FlagAnyWrap, Depth + 1),
2912                               SCEV::FlagAnyWrap, Depth + 1);
2913           }
2914         }
2915         AddRecOps.push_back(Term);
2916       }
2917       if (!Overflow) {
2918         const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
2919                                               SCEV::FlagAnyWrap);
2920         if (Ops.size() == 2) return NewAddRec;
2921         Ops[Idx] = NewAddRec;
2922         Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2923         OpsModified = true;
2924         AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
2925         if (!AddRec)
2926           break;
2927       }
2928     }
2929     if (OpsModified)
2930       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2931 
2932     // Otherwise couldn't fold anything into this recurrence.  Move onto the
2933     // next one.
2934   }
2935 
2936   // Okay, it looks like we really DO need an mul expr.  Check to see if we
2937   // already have one, otherwise create a new one.
2938   return getOrCreateMulExpr(Ops, Flags);
2939 }
2940 
2941 /// Get a canonical unsigned division expression, or something simpler if
2942 /// possible.
2943 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
2944                                          const SCEV *RHS) {
2945   assert(getEffectiveSCEVType(LHS->getType()) ==
2946          getEffectiveSCEVType(RHS->getType()) &&
2947          "SCEVUDivExpr operand types don't match!");
2948 
2949   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
2950     if (RHSC->getValue()->isOne())
2951       return LHS;                               // X udiv 1 --> x
2952     // If the denominator is zero, the result of the udiv is undefined. Don't
2953     // try to analyze it, because the resolution chosen here may differ from
2954     // the resolution chosen in other parts of the compiler.
2955     if (!RHSC->getValue()->isZero()) {
2956       // Determine if the division can be folded into the operands of
2957       // its operands.
2958       // TODO: Generalize this to non-constants by using known-bits information.
2959       Type *Ty = LHS->getType();
2960       unsigned LZ = RHSC->getAPInt().countLeadingZeros();
2961       unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
2962       // For non-power-of-two values, effectively round the value up to the
2963       // nearest power of two.
2964       if (!RHSC->getAPInt().isPowerOf2())
2965         ++MaxShiftAmt;
2966       IntegerType *ExtTy =
2967         IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
2968       if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
2969         if (const SCEVConstant *Step =
2970             dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
2971           // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
2972           const APInt &StepInt = Step->getAPInt();
2973           const APInt &DivInt = RHSC->getAPInt();
2974           if (!StepInt.urem(DivInt) &&
2975               getZeroExtendExpr(AR, ExtTy) ==
2976               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2977                             getZeroExtendExpr(Step, ExtTy),
2978                             AR->getLoop(), SCEV::FlagAnyWrap)) {
2979             SmallVector<const SCEV *, 4> Operands;
2980             for (const SCEV *Op : AR->operands())
2981               Operands.push_back(getUDivExpr(Op, RHS));
2982             return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
2983           }
2984           /// Get a canonical UDivExpr for a recurrence.
2985           /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
2986           // We can currently only fold X%N if X is constant.
2987           const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
2988           if (StartC && !DivInt.urem(StepInt) &&
2989               getZeroExtendExpr(AR, ExtTy) ==
2990               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2991                             getZeroExtendExpr(Step, ExtTy),
2992                             AR->getLoop(), SCEV::FlagAnyWrap)) {
2993             const APInt &StartInt = StartC->getAPInt();
2994             const APInt &StartRem = StartInt.urem(StepInt);
2995             if (StartRem != 0)
2996               LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step,
2997                                   AR->getLoop(), SCEV::FlagNW);
2998           }
2999         }
3000       // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
3001       if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
3002         SmallVector<const SCEV *, 4> Operands;
3003         for (const SCEV *Op : M->operands())
3004           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3005         if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
3006           // Find an operand that's safely divisible.
3007           for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3008             const SCEV *Op = M->getOperand(i);
3009             const SCEV *Div = getUDivExpr(Op, RHSC);
3010             if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
3011               Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
3012                                                       M->op_end());
3013               Operands[i] = Div;
3014               return getMulExpr(Operands);
3015             }
3016           }
3017       }
3018       // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
3019       if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
3020         SmallVector<const SCEV *, 4> Operands;
3021         for (const SCEV *Op : A->operands())
3022           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3023         if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
3024           Operands.clear();
3025           for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
3026             const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
3027             if (isa<SCEVUDivExpr>(Op) ||
3028                 getMulExpr(Op, RHS) != A->getOperand(i))
3029               break;
3030             Operands.push_back(Op);
3031           }
3032           if (Operands.size() == A->getNumOperands())
3033             return getAddExpr(Operands);
3034         }
3035       }
3036 
3037       // Fold if both operands are constant.
3038       if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
3039         Constant *LHSCV = LHSC->getValue();
3040         Constant *RHSCV = RHSC->getValue();
3041         return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
3042                                                                    RHSCV)));
3043       }
3044     }
3045   }
3046 
3047   FoldingSetNodeID ID;
3048   ID.AddInteger(scUDivExpr);
3049   ID.AddPointer(LHS);
3050   ID.AddPointer(RHS);
3051   void *IP = nullptr;
3052   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3053   SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
3054                                              LHS, RHS);
3055   UniqueSCEVs.InsertNode(S, IP);
3056   return S;
3057 }
3058 
3059 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
3060   APInt A = C1->getAPInt().abs();
3061   APInt B = C2->getAPInt().abs();
3062   uint32_t ABW = A.getBitWidth();
3063   uint32_t BBW = B.getBitWidth();
3064 
3065   if (ABW > BBW)
3066     B = B.zext(ABW);
3067   else if (ABW < BBW)
3068     A = A.zext(BBW);
3069 
3070   return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B));
3071 }
3072 
3073 /// Get a canonical unsigned division expression, or something simpler if
3074 /// possible. There is no representation for an exact udiv in SCEV IR, but we
3075 /// can attempt to remove factors from the LHS and RHS.  We can't do this when
3076 /// it's not exact because the udiv may be clearing bits.
3077 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
3078                                               const SCEV *RHS) {
3079   // TODO: we could try to find factors in all sorts of things, but for now we
3080   // just deal with u/exact (multiply, constant). See SCEVDivision towards the
3081   // end of this file for inspiration.
3082 
3083   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
3084   if (!Mul || !Mul->hasNoUnsignedWrap())
3085     return getUDivExpr(LHS, RHS);
3086 
3087   if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
3088     // If the mulexpr multiplies by a constant, then that constant must be the
3089     // first element of the mulexpr.
3090     if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
3091       if (LHSCst == RHSCst) {
3092         SmallVector<const SCEV *, 2> Operands;
3093         Operands.append(Mul->op_begin() + 1, Mul->op_end());
3094         return getMulExpr(Operands);
3095       }
3096 
3097       // We can't just assume that LHSCst divides RHSCst cleanly, it could be
3098       // that there's a factor provided by one of the other terms. We need to
3099       // check.
3100       APInt Factor = gcd(LHSCst, RHSCst);
3101       if (!Factor.isIntN(1)) {
3102         LHSCst =
3103             cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
3104         RHSCst =
3105             cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
3106         SmallVector<const SCEV *, 2> Operands;
3107         Operands.push_back(LHSCst);
3108         Operands.append(Mul->op_begin() + 1, Mul->op_end());
3109         LHS = getMulExpr(Operands);
3110         RHS = RHSCst;
3111         Mul = dyn_cast<SCEVMulExpr>(LHS);
3112         if (!Mul)
3113           return getUDivExactExpr(LHS, RHS);
3114       }
3115     }
3116   }
3117 
3118   for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3119     if (Mul->getOperand(i) == RHS) {
3120       SmallVector<const SCEV *, 2> Operands;
3121       Operands.append(Mul->op_begin(), Mul->op_begin() + i);
3122       Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
3123       return getMulExpr(Operands);
3124     }
3125   }
3126 
3127   return getUDivExpr(LHS, RHS);
3128 }
3129 
3130 /// Get an add recurrence expression for the specified loop.  Simplify the
3131 /// expression as much as possible.
3132 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
3133                                            const Loop *L,
3134                                            SCEV::NoWrapFlags Flags) {
3135   SmallVector<const SCEV *, 4> Operands;
3136   Operands.push_back(Start);
3137   if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3138     if (StepChrec->getLoop() == L) {
3139       Operands.append(StepChrec->op_begin(), StepChrec->op_end());
3140       return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
3141     }
3142 
3143   Operands.push_back(Step);
3144   return getAddRecExpr(Operands, L, Flags);
3145 }
3146 
3147 /// Get an add recurrence expression for the specified loop.  Simplify the
3148 /// expression as much as possible.
3149 const SCEV *
3150 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
3151                                const Loop *L, SCEV::NoWrapFlags Flags) {
3152   if (Operands.size() == 1) return Operands[0];
3153 #ifndef NDEBUG
3154   Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
3155   for (unsigned i = 1, e = Operands.size(); i != e; ++i)
3156     assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
3157            "SCEVAddRecExpr operand types don't match!");
3158   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3159     assert(isLoopInvariant(Operands[i], L) &&
3160            "SCEVAddRecExpr operand is not loop-invariant!");
3161 #endif
3162 
3163   if (Operands.back()->isZero()) {
3164     Operands.pop_back();
3165     return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0}  -->  X
3166   }
3167 
3168   // It's tempting to want to call getMaxBackedgeTakenCount count here and
3169   // use that information to infer NUW and NSW flags. However, computing a
3170   // BE count requires calling getAddRecExpr, so we may not yet have a
3171   // meaningful BE count at this point (and if we don't, we'd be stuck
3172   // with a SCEVCouldNotCompute as the cached BE count).
3173 
3174   Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
3175 
3176   // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3177   if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3178     const Loop *NestedLoop = NestedAR->getLoop();
3179     if (L->contains(NestedLoop)
3180             ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3181             : (!NestedLoop->contains(L) &&
3182                DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3183       SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
3184                                                   NestedAR->op_end());
3185       Operands[0] = NestedAR->getStart();
3186       // AddRecs require their operands be loop-invariant with respect to their
3187       // loops. Don't perform this transformation if it would break this
3188       // requirement.
3189       bool AllInvariant = all_of(
3190           Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3191 
3192       if (AllInvariant) {
3193         // Create a recurrence for the outer loop with the same step size.
3194         //
3195         // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3196         // inner recurrence has the same property.
3197         SCEV::NoWrapFlags OuterFlags =
3198           maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3199 
3200         NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3201         AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3202           return isLoopInvariant(Op, NestedLoop);
3203         });
3204 
3205         if (AllInvariant) {
3206           // Ok, both add recurrences are valid after the transformation.
3207           //
3208           // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3209           // the outer recurrence has the same property.
3210           SCEV::NoWrapFlags InnerFlags =
3211             maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
3212           return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3213         }
3214       }
3215       // Reset Operands to its original state.
3216       Operands[0] = NestedAR;
3217     }
3218   }
3219 
3220   // Okay, it looks like we really DO need an addrec expr.  Check to see if we
3221   // already have one, otherwise create a new one.
3222   FoldingSetNodeID ID;
3223   ID.AddInteger(scAddRecExpr);
3224   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3225     ID.AddPointer(Operands[i]);
3226   ID.AddPointer(L);
3227   void *IP = nullptr;
3228   SCEVAddRecExpr *S =
3229     static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3230   if (!S) {
3231     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
3232     std::uninitialized_copy(Operands.begin(), Operands.end(), O);
3233     S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
3234                                            O, Operands.size(), L);
3235     UniqueSCEVs.InsertNode(S, IP);
3236   }
3237   S->setNoWrapFlags(Flags);
3238   return S;
3239 }
3240 
3241 const SCEV *
3242 ScalarEvolution::getGEPExpr(GEPOperator *GEP,
3243                             const SmallVectorImpl<const SCEV *> &IndexExprs) {
3244   const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3245   // getSCEV(Base)->getType() has the same address space as Base->getType()
3246   // because SCEV::getType() preserves the address space.
3247   Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType());
3248   // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP
3249   // instruction to its SCEV, because the Instruction may be guarded by control
3250   // flow and the no-overflow bits may not be valid for the expression in any
3251   // context. This can be fixed similarly to how these flags are handled for
3252   // adds.
3253   SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW
3254                                              : SCEV::FlagAnyWrap;
3255 
3256   const SCEV *TotalOffset = getZero(IntPtrTy);
3257   // The array size is unimportant. The first thing we do on CurTy is getting
3258   // its element type.
3259   Type *CurTy = ArrayType::get(GEP->getSourceElementType(), 0);
3260   for (const SCEV *IndexExpr : IndexExprs) {
3261     // Compute the (potentially symbolic) offset in bytes for this index.
3262     if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3263       // For a struct, add the member offset.
3264       ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3265       unsigned FieldNo = Index->getZExtValue();
3266       const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo);
3267 
3268       // Add the field offset to the running total offset.
3269       TotalOffset = getAddExpr(TotalOffset, FieldOffset);
3270 
3271       // Update CurTy to the type of the field at Index.
3272       CurTy = STy->getTypeAtIndex(Index);
3273     } else {
3274       // Update CurTy to its element type.
3275       CurTy = cast<SequentialType>(CurTy)->getElementType();
3276       // For an array, add the element offset, explicitly scaled.
3277       const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy);
3278       // Getelementptr indices are signed.
3279       IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy);
3280 
3281       // Multiply the index by the element size to compute the element offset.
3282       const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap);
3283 
3284       // Add the element offset to the running total offset.
3285       TotalOffset = getAddExpr(TotalOffset, LocalOffset);
3286     }
3287   }
3288 
3289   // Add the total offset from all the GEP indices to the base.
3290   return getAddExpr(BaseExpr, TotalOffset, Wrap);
3291 }
3292 
3293 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
3294                                          const SCEV *RHS) {
3295   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3296   return getSMaxExpr(Ops);
3297 }
3298 
3299 const SCEV *
3300 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3301   assert(!Ops.empty() && "Cannot get empty smax!");
3302   if (Ops.size() == 1) return Ops[0];
3303 #ifndef NDEBUG
3304   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3305   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3306     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3307            "SCEVSMaxExpr operand types don't match!");
3308 #endif
3309 
3310   // Sort by complexity, this groups all similar expression types together.
3311   GroupByComplexity(Ops, &LI, DT);
3312 
3313   // If there are any constants, fold them together.
3314   unsigned Idx = 0;
3315   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3316     ++Idx;
3317     assert(Idx < Ops.size());
3318     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3319       // We found two constants, fold them together!
3320       ConstantInt *Fold = ConstantInt::get(
3321           getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt()));
3322       Ops[0] = getConstant(Fold);
3323       Ops.erase(Ops.begin()+1);  // Erase the folded element
3324       if (Ops.size() == 1) return Ops[0];
3325       LHSC = cast<SCEVConstant>(Ops[0]);
3326     }
3327 
3328     // If we are left with a constant minimum-int, strip it off.
3329     if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
3330       Ops.erase(Ops.begin());
3331       --Idx;
3332     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
3333       // If we have an smax with a constant maximum-int, it will always be
3334       // maximum-int.
3335       return Ops[0];
3336     }
3337 
3338     if (Ops.size() == 1) return Ops[0];
3339   }
3340 
3341   // Find the first SMax
3342   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
3343     ++Idx;
3344 
3345   // Check to see if one of the operands is an SMax. If so, expand its operands
3346   // onto our operand list, and recurse to simplify.
3347   if (Idx < Ops.size()) {
3348     bool DeletedSMax = false;
3349     while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
3350       Ops.erase(Ops.begin()+Idx);
3351       Ops.append(SMax->op_begin(), SMax->op_end());
3352       DeletedSMax = true;
3353     }
3354 
3355     if (DeletedSMax)
3356       return getSMaxExpr(Ops);
3357   }
3358 
3359   // Okay, check to see if the same value occurs in the operand list twice.  If
3360   // so, delete one.  Since we sorted the list, these values are required to
3361   // be adjacent.
3362   for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
3363     //  X smax Y smax Y  -->  X smax Y
3364     //  X smax Y         -->  X, if X is always greater than Y
3365     if (Ops[i] == Ops[i+1] ||
3366         isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
3367       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3368       --i; --e;
3369     } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
3370       Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3371       --i; --e;
3372     }
3373 
3374   if (Ops.size() == 1) return Ops[0];
3375 
3376   assert(!Ops.empty() && "Reduced smax down to nothing!");
3377 
3378   // Okay, it looks like we really DO need an smax expr.  Check to see if we
3379   // already have one, otherwise create a new one.
3380   FoldingSetNodeID ID;
3381   ID.AddInteger(scSMaxExpr);
3382   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3383     ID.AddPointer(Ops[i]);
3384   void *IP = nullptr;
3385   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3386   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3387   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3388   SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
3389                                              O, Ops.size());
3390   UniqueSCEVs.InsertNode(S, IP);
3391   return S;
3392 }
3393 
3394 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
3395                                          const SCEV *RHS) {
3396   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3397   return getUMaxExpr(Ops);
3398 }
3399 
3400 const SCEV *
3401 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3402   assert(!Ops.empty() && "Cannot get empty umax!");
3403   if (Ops.size() == 1) return Ops[0];
3404 #ifndef NDEBUG
3405   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3406   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3407     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3408            "SCEVUMaxExpr operand types don't match!");
3409 #endif
3410 
3411   // Sort by complexity, this groups all similar expression types together.
3412   GroupByComplexity(Ops, &LI, DT);
3413 
3414   // If there are any constants, fold them together.
3415   unsigned Idx = 0;
3416   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3417     ++Idx;
3418     assert(Idx < Ops.size());
3419     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3420       // We found two constants, fold them together!
3421       ConstantInt *Fold = ConstantInt::get(
3422           getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt()));
3423       Ops[0] = getConstant(Fold);
3424       Ops.erase(Ops.begin()+1);  // Erase the folded element
3425       if (Ops.size() == 1) return Ops[0];
3426       LHSC = cast<SCEVConstant>(Ops[0]);
3427     }
3428 
3429     // If we are left with a constant minimum-int, strip it off.
3430     if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
3431       Ops.erase(Ops.begin());
3432       --Idx;
3433     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
3434       // If we have an umax with a constant maximum-int, it will always be
3435       // maximum-int.
3436       return Ops[0];
3437     }
3438 
3439     if (Ops.size() == 1) return Ops[0];
3440   }
3441 
3442   // Find the first UMax
3443   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
3444     ++Idx;
3445 
3446   // Check to see if one of the operands is a UMax. If so, expand its operands
3447   // onto our operand list, and recurse to simplify.
3448   if (Idx < Ops.size()) {
3449     bool DeletedUMax = false;
3450     while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
3451       Ops.erase(Ops.begin()+Idx);
3452       Ops.append(UMax->op_begin(), UMax->op_end());
3453       DeletedUMax = true;
3454     }
3455 
3456     if (DeletedUMax)
3457       return getUMaxExpr(Ops);
3458   }
3459 
3460   // Okay, check to see if the same value occurs in the operand list twice.  If
3461   // so, delete one.  Since we sorted the list, these values are required to
3462   // be adjacent.
3463   for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
3464     //  X umax Y umax Y  -->  X umax Y
3465     //  X umax Y         -->  X, if X is always greater than Y
3466     if (Ops[i] == Ops[i+1] ||
3467         isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
3468       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3469       --i; --e;
3470     } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
3471       Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3472       --i; --e;
3473     }
3474 
3475   if (Ops.size() == 1) return Ops[0];
3476 
3477   assert(!Ops.empty() && "Reduced umax down to nothing!");
3478 
3479   // Okay, it looks like we really DO need a umax expr.  Check to see if we
3480   // already have one, otherwise create a new one.
3481   FoldingSetNodeID ID;
3482   ID.AddInteger(scUMaxExpr);
3483   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3484     ID.AddPointer(Ops[i]);
3485   void *IP = nullptr;
3486   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3487   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3488   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3489   SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
3490                                              O, Ops.size());
3491   UniqueSCEVs.InsertNode(S, IP);
3492   return S;
3493 }
3494 
3495 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
3496                                          const SCEV *RHS) {
3497   // ~smax(~x, ~y) == smin(x, y).
3498   return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3499 }
3500 
3501 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
3502                                          const SCEV *RHS) {
3503   // ~umax(~x, ~y) == umin(x, y)
3504   return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3505 }
3506 
3507 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
3508   // We can bypass creating a target-independent
3509   // constant expression and then folding it back into a ConstantInt.
3510   // This is just a compile-time optimization.
3511   return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
3512 }
3513 
3514 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
3515                                              StructType *STy,
3516                                              unsigned FieldNo) {
3517   // We can bypass creating a target-independent
3518   // constant expression and then folding it back into a ConstantInt.
3519   // This is just a compile-time optimization.
3520   return getConstant(
3521       IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
3522 }
3523 
3524 const SCEV *ScalarEvolution::getUnknown(Value *V) {
3525   // Don't attempt to do anything other than create a SCEVUnknown object
3526   // here.  createSCEV only calls getUnknown after checking for all other
3527   // interesting possibilities, and any other code that calls getUnknown
3528   // is doing so in order to hide a value from SCEV canonicalization.
3529 
3530   FoldingSetNodeID ID;
3531   ID.AddInteger(scUnknown);
3532   ID.AddPointer(V);
3533   void *IP = nullptr;
3534   if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3535     assert(cast<SCEVUnknown>(S)->getValue() == V &&
3536            "Stale SCEVUnknown in uniquing map!");
3537     return S;
3538   }
3539   SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3540                                             FirstUnknown);
3541   FirstUnknown = cast<SCEVUnknown>(S);
3542   UniqueSCEVs.InsertNode(S, IP);
3543   return S;
3544 }
3545 
3546 //===----------------------------------------------------------------------===//
3547 //            Basic SCEV Analysis and PHI Idiom Recognition Code
3548 //
3549 
3550 /// Test if values of the given type are analyzable within the SCEV
3551 /// framework. This primarily includes integer types, and it can optionally
3552 /// include pointer types if the ScalarEvolution class has access to
3553 /// target-specific information.
3554 bool ScalarEvolution::isSCEVable(Type *Ty) const {
3555   // Integers and pointers are always SCEVable.
3556   return Ty->isIntegerTy() || Ty->isPointerTy();
3557 }
3558 
3559 /// Return the size in bits of the specified type, for which isSCEVable must
3560 /// return true.
3561 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
3562   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3563   return getDataLayout().getTypeSizeInBits(Ty);
3564 }
3565 
3566 /// Return a type with the same bitwidth as the given type and which represents
3567 /// how SCEV will treat the given type, for which isSCEVable must return
3568 /// true. For pointer types, this is the pointer-sized integer type.
3569 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
3570   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3571 
3572   if (Ty->isIntegerTy())
3573     return Ty;
3574 
3575   // The only other support type is pointer.
3576   assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
3577   return getDataLayout().getIntPtrType(Ty);
3578 }
3579 
3580 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const {
3581   return  getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
3582 }
3583 
3584 const SCEV *ScalarEvolution::getCouldNotCompute() {
3585   return CouldNotCompute.get();
3586 }
3587 
3588 bool ScalarEvolution::checkValidity(const SCEV *S) const {
3589   bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
3590     auto *SU = dyn_cast<SCEVUnknown>(S);
3591     return SU && SU->getValue() == nullptr;
3592   });
3593 
3594   return !ContainsNulls;
3595 }
3596 
3597 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
3598   HasRecMapType::iterator I = HasRecMap.find(S);
3599   if (I != HasRecMap.end())
3600     return I->second;
3601 
3602   bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>);
3603   HasRecMap.insert({S, FoundAddRec});
3604   return FoundAddRec;
3605 }
3606 
3607 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}.
3608 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an
3609 /// offset I, then return {S', I}, else return {\p S, nullptr}.
3610 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) {
3611   const auto *Add = dyn_cast<SCEVAddExpr>(S);
3612   if (!Add)
3613     return {S, nullptr};
3614 
3615   if (Add->getNumOperands() != 2)
3616     return {S, nullptr};
3617 
3618   auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0));
3619   if (!ConstOp)
3620     return {S, nullptr};
3621 
3622   return {Add->getOperand(1), ConstOp->getValue()};
3623 }
3624 
3625 /// Return the ValueOffsetPair set for \p S. \p S can be represented
3626 /// by the value and offset from any ValueOffsetPair in the set.
3627 SetVector<ScalarEvolution::ValueOffsetPair> *
3628 ScalarEvolution::getSCEVValues(const SCEV *S) {
3629   ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
3630   if (SI == ExprValueMap.end())
3631     return nullptr;
3632 #ifndef NDEBUG
3633   if (VerifySCEVMap) {
3634     // Check there is no dangling Value in the set returned.
3635     for (const auto &VE : SI->second)
3636       assert(ValueExprMap.count(VE.first));
3637   }
3638 #endif
3639   return &SI->second;
3640 }
3641 
3642 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
3643 /// cannot be used separately. eraseValueFromMap should be used to remove
3644 /// V from ValueExprMap and ExprValueMap at the same time.
3645 void ScalarEvolution::eraseValueFromMap(Value *V) {
3646   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3647   if (I != ValueExprMap.end()) {
3648     const SCEV *S = I->second;
3649     // Remove {V, 0} from the set of ExprValueMap[S]
3650     if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S))
3651       SV->remove({V, nullptr});
3652 
3653     // Remove {V, Offset} from the set of ExprValueMap[Stripped]
3654     const SCEV *Stripped;
3655     ConstantInt *Offset;
3656     std::tie(Stripped, Offset) = splitAddExpr(S);
3657     if (Offset != nullptr) {
3658       if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped))
3659         SV->remove({V, Offset});
3660     }
3661     ValueExprMap.erase(V);
3662   }
3663 }
3664 
3665 /// Return an existing SCEV if it exists, otherwise analyze the expression and
3666 /// create a new one.
3667 const SCEV *ScalarEvolution::getSCEV(Value *V) {
3668   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3669 
3670   const SCEV *S = getExistingSCEV(V);
3671   if (S == nullptr) {
3672     S = createSCEV(V);
3673     // During PHI resolution, it is possible to create two SCEVs for the same
3674     // V, so it is needed to double check whether V->S is inserted into
3675     // ValueExprMap before insert S->{V, 0} into ExprValueMap.
3676     std::pair<ValueExprMapType::iterator, bool> Pair =
3677         ValueExprMap.insert({SCEVCallbackVH(V, this), S});
3678     if (Pair.second) {
3679       ExprValueMap[S].insert({V, nullptr});
3680 
3681       // If S == Stripped + Offset, add Stripped -> {V, Offset} into
3682       // ExprValueMap.
3683       const SCEV *Stripped = S;
3684       ConstantInt *Offset = nullptr;
3685       std::tie(Stripped, Offset) = splitAddExpr(S);
3686       // If stripped is SCEVUnknown, don't bother to save
3687       // Stripped -> {V, offset}. It doesn't simplify and sometimes even
3688       // increase the complexity of the expansion code.
3689       // If V is GetElementPtrInst, don't save Stripped -> {V, offset}
3690       // because it may generate add/sub instead of GEP in SCEV expansion.
3691       if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) &&
3692           !isa<GetElementPtrInst>(V))
3693         ExprValueMap[Stripped].insert({V, Offset});
3694     }
3695   }
3696   return S;
3697 }
3698 
3699 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
3700   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3701 
3702   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3703   if (I != ValueExprMap.end()) {
3704     const SCEV *S = I->second;
3705     if (checkValidity(S))
3706       return S;
3707     eraseValueFromMap(V);
3708     forgetMemoizedResults(S);
3709   }
3710   return nullptr;
3711 }
3712 
3713 /// Return a SCEV corresponding to -V = -1*V
3714 ///
3715 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
3716                                              SCEV::NoWrapFlags Flags) {
3717   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3718     return getConstant(
3719                cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
3720 
3721   Type *Ty = V->getType();
3722   Ty = getEffectiveSCEVType(Ty);
3723   return getMulExpr(
3724       V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags);
3725 }
3726 
3727 /// Return a SCEV corresponding to ~V = -1-V
3728 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
3729   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3730     return getConstant(
3731                 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
3732 
3733   Type *Ty = V->getType();
3734   Ty = getEffectiveSCEVType(Ty);
3735   const SCEV *AllOnes =
3736                    getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
3737   return getMinusSCEV(AllOnes, V);
3738 }
3739 
3740 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
3741                                           SCEV::NoWrapFlags Flags,
3742                                           unsigned Depth) {
3743   // Fast path: X - X --> 0.
3744   if (LHS == RHS)
3745     return getZero(LHS->getType());
3746 
3747   // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
3748   // makes it so that we cannot make much use of NUW.
3749   auto AddFlags = SCEV::FlagAnyWrap;
3750   const bool RHSIsNotMinSigned =
3751       !getSignedRangeMin(RHS).isMinSignedValue();
3752   if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) {
3753     // Let M be the minimum representable signed value. Then (-1)*RHS
3754     // signed-wraps if and only if RHS is M. That can happen even for
3755     // a NSW subtraction because e.g. (-1)*M signed-wraps even though
3756     // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
3757     // (-1)*RHS, we need to prove that RHS != M.
3758     //
3759     // If LHS is non-negative and we know that LHS - RHS does not
3760     // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
3761     // either by proving that RHS > M or that LHS >= 0.
3762     if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
3763       AddFlags = SCEV::FlagNSW;
3764     }
3765   }
3766 
3767   // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
3768   // RHS is NSW and LHS >= 0.
3769   //
3770   // The difficulty here is that the NSW flag may have been proven
3771   // relative to a loop that is to be found in a recurrence in LHS and
3772   // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
3773   // larger scope than intended.
3774   auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3775 
3776   return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
3777 }
3778 
3779 const SCEV *
3780 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) {
3781   Type *SrcTy = V->getType();
3782   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3783          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3784          "Cannot truncate or zero extend with non-integer arguments!");
3785   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3786     return V;  // No conversion
3787   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
3788     return getTruncateExpr(V, Ty);
3789   return getZeroExtendExpr(V, Ty);
3790 }
3791 
3792 const SCEV *
3793 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
3794                                          Type *Ty) {
3795   Type *SrcTy = V->getType();
3796   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3797          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3798          "Cannot truncate or zero extend with non-integer arguments!");
3799   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3800     return V;  // No conversion
3801   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
3802     return getTruncateExpr(V, Ty);
3803   return getSignExtendExpr(V, Ty);
3804 }
3805 
3806 const SCEV *
3807 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
3808   Type *SrcTy = V->getType();
3809   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3810          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3811          "Cannot noop or zero extend with non-integer arguments!");
3812   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3813          "getNoopOrZeroExtend cannot truncate!");
3814   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3815     return V;  // No conversion
3816   return getZeroExtendExpr(V, Ty);
3817 }
3818 
3819 const SCEV *
3820 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
3821   Type *SrcTy = V->getType();
3822   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3823          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3824          "Cannot noop or sign extend with non-integer arguments!");
3825   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3826          "getNoopOrSignExtend cannot truncate!");
3827   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3828     return V;  // No conversion
3829   return getSignExtendExpr(V, Ty);
3830 }
3831 
3832 const SCEV *
3833 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
3834   Type *SrcTy = V->getType();
3835   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3836          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3837          "Cannot noop or any extend with non-integer arguments!");
3838   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3839          "getNoopOrAnyExtend cannot truncate!");
3840   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3841     return V;  // No conversion
3842   return getAnyExtendExpr(V, Ty);
3843 }
3844 
3845 const SCEV *
3846 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
3847   Type *SrcTy = V->getType();
3848   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3849          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3850          "Cannot truncate or noop with non-integer arguments!");
3851   assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
3852          "getTruncateOrNoop cannot extend!");
3853   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3854     return V;  // No conversion
3855   return getTruncateExpr(V, Ty);
3856 }
3857 
3858 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
3859                                                         const SCEV *RHS) {
3860   const SCEV *PromotedLHS = LHS;
3861   const SCEV *PromotedRHS = RHS;
3862 
3863   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3864     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3865   else
3866     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3867 
3868   return getUMaxExpr(PromotedLHS, PromotedRHS);
3869 }
3870 
3871 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
3872                                                         const SCEV *RHS) {
3873   const SCEV *PromotedLHS = LHS;
3874   const SCEV *PromotedRHS = RHS;
3875 
3876   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3877     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3878   else
3879     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3880 
3881   return getUMinExpr(PromotedLHS, PromotedRHS);
3882 }
3883 
3884 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
3885   // A pointer operand may evaluate to a nonpointer expression, such as null.
3886   if (!V->getType()->isPointerTy())
3887     return V;
3888 
3889   if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
3890     return getPointerBase(Cast->getOperand());
3891   } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
3892     const SCEV *PtrOp = nullptr;
3893     for (const SCEV *NAryOp : NAry->operands()) {
3894       if (NAryOp->getType()->isPointerTy()) {
3895         // Cannot find the base of an expression with multiple pointer operands.
3896         if (PtrOp)
3897           return V;
3898         PtrOp = NAryOp;
3899       }
3900     }
3901     if (!PtrOp)
3902       return V;
3903     return getPointerBase(PtrOp);
3904   }
3905   return V;
3906 }
3907 
3908 /// Push users of the given Instruction onto the given Worklist.
3909 static void
3910 PushDefUseChildren(Instruction *I,
3911                    SmallVectorImpl<Instruction *> &Worklist) {
3912   // Push the def-use children onto the Worklist stack.
3913   for (User *U : I->users())
3914     Worklist.push_back(cast<Instruction>(U));
3915 }
3916 
3917 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) {
3918   SmallVector<Instruction *, 16> Worklist;
3919   PushDefUseChildren(PN, Worklist);
3920 
3921   SmallPtrSet<Instruction *, 8> Visited;
3922   Visited.insert(PN);
3923   while (!Worklist.empty()) {
3924     Instruction *I = Worklist.pop_back_val();
3925     if (!Visited.insert(I).second)
3926       continue;
3927 
3928     auto It = ValueExprMap.find_as(static_cast<Value *>(I));
3929     if (It != ValueExprMap.end()) {
3930       const SCEV *Old = It->second;
3931 
3932       // Short-circuit the def-use traversal if the symbolic name
3933       // ceases to appear in expressions.
3934       if (Old != SymName && !hasOperand(Old, SymName))
3935         continue;
3936 
3937       // SCEVUnknown for a PHI either means that it has an unrecognized
3938       // structure, it's a PHI that's in the progress of being computed
3939       // by createNodeForPHI, or it's a single-value PHI. In the first case,
3940       // additional loop trip count information isn't going to change anything.
3941       // In the second case, createNodeForPHI will perform the necessary
3942       // updates on its own when it gets to that point. In the third, we do
3943       // want to forget the SCEVUnknown.
3944       if (!isa<PHINode>(I) ||
3945           !isa<SCEVUnknown>(Old) ||
3946           (I != PN && Old == SymName)) {
3947         eraseValueFromMap(It->first);
3948         forgetMemoizedResults(Old);
3949       }
3950     }
3951 
3952     PushDefUseChildren(I, Worklist);
3953   }
3954 }
3955 
3956 namespace {
3957 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
3958 public:
3959   static const SCEV *rewrite(const SCEV *S, const Loop *L,
3960                              ScalarEvolution &SE) {
3961     SCEVInitRewriter Rewriter(L, SE);
3962     const SCEV *Result = Rewriter.visit(S);
3963     return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
3964   }
3965 
3966   SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
3967       : SCEVRewriteVisitor(SE), L(L), Valid(true) {}
3968 
3969   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
3970     if (!SE.isLoopInvariant(Expr, L))
3971       Valid = false;
3972     return Expr;
3973   }
3974 
3975   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
3976     // Only allow AddRecExprs for this loop.
3977     if (Expr->getLoop() == L)
3978       return Expr->getStart();
3979     Valid = false;
3980     return Expr;
3981   }
3982 
3983   bool isValid() { return Valid; }
3984 
3985 private:
3986   const Loop *L;
3987   bool Valid;
3988 };
3989 
3990 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
3991 public:
3992   static const SCEV *rewrite(const SCEV *S, const Loop *L,
3993                              ScalarEvolution &SE) {
3994     SCEVShiftRewriter Rewriter(L, SE);
3995     const SCEV *Result = Rewriter.visit(S);
3996     return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
3997   }
3998 
3999   SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
4000       : SCEVRewriteVisitor(SE), L(L), Valid(true) {}
4001 
4002   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4003     // Only allow AddRecExprs for this loop.
4004     if (!SE.isLoopInvariant(Expr, L))
4005       Valid = false;
4006     return Expr;
4007   }
4008 
4009   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4010     if (Expr->getLoop() == L && Expr->isAffine())
4011       return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
4012     Valid = false;
4013     return Expr;
4014   }
4015   bool isValid() { return Valid; }
4016 
4017 private:
4018   const Loop *L;
4019   bool Valid;
4020 };
4021 } // end anonymous namespace
4022 
4023 SCEV::NoWrapFlags
4024 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
4025   if (!AR->isAffine())
4026     return SCEV::FlagAnyWrap;
4027 
4028   typedef OverflowingBinaryOperator OBO;
4029   SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
4030 
4031   if (!AR->hasNoSignedWrap()) {
4032     ConstantRange AddRecRange = getSignedRange(AR);
4033     ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
4034 
4035     auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4036         Instruction::Add, IncRange, OBO::NoSignedWrap);
4037     if (NSWRegion.contains(AddRecRange))
4038       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
4039   }
4040 
4041   if (!AR->hasNoUnsignedWrap()) {
4042     ConstantRange AddRecRange = getUnsignedRange(AR);
4043     ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
4044 
4045     auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4046         Instruction::Add, IncRange, OBO::NoUnsignedWrap);
4047     if (NUWRegion.contains(AddRecRange))
4048       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
4049   }
4050 
4051   return Result;
4052 }
4053 
4054 namespace {
4055 /// Represents an abstract binary operation.  This may exist as a
4056 /// normal instruction or constant expression, or may have been
4057 /// derived from an expression tree.
4058 struct BinaryOp {
4059   unsigned Opcode;
4060   Value *LHS;
4061   Value *RHS;
4062   bool IsNSW;
4063   bool IsNUW;
4064 
4065   /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
4066   /// constant expression.
4067   Operator *Op;
4068 
4069   explicit BinaryOp(Operator *Op)
4070       : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
4071         IsNSW(false), IsNUW(false), Op(Op) {
4072     if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
4073       IsNSW = OBO->hasNoSignedWrap();
4074       IsNUW = OBO->hasNoUnsignedWrap();
4075     }
4076   }
4077 
4078   explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
4079                     bool IsNUW = false)
4080       : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW),
4081         Op(nullptr) {}
4082 };
4083 }
4084 
4085 
4086 /// Try to map \p V into a BinaryOp, and return \c None on failure.
4087 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) {
4088   auto *Op = dyn_cast<Operator>(V);
4089   if (!Op)
4090     return None;
4091 
4092   // Implementation detail: all the cleverness here should happen without
4093   // creating new SCEV expressions -- our caller knowns tricks to avoid creating
4094   // SCEV expressions when possible, and we should not break that.
4095 
4096   switch (Op->getOpcode()) {
4097   case Instruction::Add:
4098   case Instruction::Sub:
4099   case Instruction::Mul:
4100   case Instruction::UDiv:
4101   case Instruction::And:
4102   case Instruction::Or:
4103   case Instruction::AShr:
4104   case Instruction::Shl:
4105     return BinaryOp(Op);
4106 
4107   case Instruction::Xor:
4108     if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
4109       // If the RHS of the xor is a signmask, then this is just an add.
4110       // Instcombine turns add of signmask into xor as a strength reduction step.
4111       if (RHSC->getValue().isSignMask())
4112         return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
4113     return BinaryOp(Op);
4114 
4115   case Instruction::LShr:
4116     // Turn logical shift right of a constant into a unsigned divide.
4117     if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
4118       uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
4119 
4120       // If the shift count is not less than the bitwidth, the result of
4121       // the shift is undefined. Don't try to analyze it, because the
4122       // resolution chosen here may differ from the resolution chosen in
4123       // other parts of the compiler.
4124       if (SA->getValue().ult(BitWidth)) {
4125         Constant *X =
4126             ConstantInt::get(SA->getContext(),
4127                              APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
4128         return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
4129       }
4130     }
4131     return BinaryOp(Op);
4132 
4133   case Instruction::ExtractValue: {
4134     auto *EVI = cast<ExtractValueInst>(Op);
4135     if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
4136       break;
4137 
4138     auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand());
4139     if (!CI)
4140       break;
4141 
4142     if (auto *F = CI->getCalledFunction())
4143       switch (F->getIntrinsicID()) {
4144       case Intrinsic::sadd_with_overflow:
4145       case Intrinsic::uadd_with_overflow: {
4146         if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT))
4147           return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4148                           CI->getArgOperand(1));
4149 
4150         // Now that we know that all uses of the arithmetic-result component of
4151         // CI are guarded by the overflow check, we can go ahead and pretend
4152         // that the arithmetic is non-overflowing.
4153         if (F->getIntrinsicID() == Intrinsic::sadd_with_overflow)
4154           return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4155                           CI->getArgOperand(1), /* IsNSW = */ true,
4156                           /* IsNUW = */ false);
4157         else
4158           return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4159                           CI->getArgOperand(1), /* IsNSW = */ false,
4160                           /* IsNUW*/ true);
4161       }
4162 
4163       case Intrinsic::ssub_with_overflow:
4164       case Intrinsic::usub_with_overflow:
4165         return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
4166                         CI->getArgOperand(1));
4167 
4168       case Intrinsic::smul_with_overflow:
4169       case Intrinsic::umul_with_overflow:
4170         return BinaryOp(Instruction::Mul, CI->getArgOperand(0),
4171                         CI->getArgOperand(1));
4172       default:
4173         break;
4174       }
4175   }
4176 
4177   default:
4178     break;
4179   }
4180 
4181   return None;
4182 }
4183 
4184 /// Helper function to createAddRecFromPHIWithCasts. We have a phi
4185 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
4186 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
4187 /// way. This function checks if \p Op, an operand of this SCEVAddExpr,
4188 /// follows one of the following patterns:
4189 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4190 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4191 /// If the SCEV expression of \p Op conforms with one of the expected patterns
4192 /// we return the type of the truncation operation, and indicate whether the
4193 /// truncated type should be treated as signed/unsigned by setting
4194 /// \p Signed to true/false, respectively.
4195 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
4196                                bool &Signed, ScalarEvolution &SE) {
4197 
4198   // The case where Op == SymbolicPHI (that is, with no type conversions on
4199   // the way) is handled by the regular add recurrence creating logic and
4200   // would have already been triggered in createAddRecForPHI. Reaching it here
4201   // means that createAddRecFromPHI had failed for this PHI before (e.g.,
4202   // because one of the other operands of the SCEVAddExpr updating this PHI is
4203   // not invariant).
4204   //
4205   // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
4206   // this case predicates that allow us to prove that Op == SymbolicPHI will
4207   // be added.
4208   if (Op == SymbolicPHI)
4209     return nullptr;
4210 
4211   unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
4212   unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
4213   if (SourceBits != NewBits)
4214     return nullptr;
4215 
4216   const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op);
4217   const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op);
4218   if (!SExt && !ZExt)
4219     return nullptr;
4220   const SCEVTruncateExpr *Trunc =
4221       SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand())
4222            : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand());
4223   if (!Trunc)
4224     return nullptr;
4225   const SCEV *X = Trunc->getOperand();
4226   if (X != SymbolicPHI)
4227     return nullptr;
4228   Signed = SExt ? true : false;
4229   return Trunc->getType();
4230 }
4231 
4232 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
4233   if (!PN->getType()->isIntegerTy())
4234     return nullptr;
4235   const Loop *L = LI.getLoopFor(PN->getParent());
4236   if (!L || L->getHeader() != PN->getParent())
4237     return nullptr;
4238   return L;
4239 }
4240 
4241 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
4242 // computation that updates the phi follows the following pattern:
4243 //   (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
4244 // which correspond to a phi->trunc->sext/zext->add->phi update chain.
4245 // If so, try to see if it can be rewritten as an AddRecExpr under some
4246 // Predicates. If successful, return them as a pair. Also cache the results
4247 // of the analysis.
4248 //
4249 // Example usage scenario:
4250 //    Say the Rewriter is called for the following SCEV:
4251 //         8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4252 //    where:
4253 //         %X = phi i64 (%Start, %BEValue)
4254 //    It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
4255 //    and call this function with %SymbolicPHI = %X.
4256 //
4257 //    The analysis will find that the value coming around the backedge has
4258 //    the following SCEV:
4259 //         BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4260 //    Upon concluding that this matches the desired pattern, the function
4261 //    will return the pair {NewAddRec, SmallPredsVec} where:
4262 //         NewAddRec = {%Start,+,%Step}
4263 //         SmallPredsVec = {P1, P2, P3} as follows:
4264 //           P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
4265 //           P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
4266 //           P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
4267 //    The returned pair means that SymbolicPHI can be rewritten into NewAddRec
4268 //    under the predicates {P1,P2,P3}.
4269 //    This predicated rewrite will be cached in PredicatedSCEVRewrites:
4270 //         PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
4271 //
4272 // TODO's:
4273 //
4274 // 1) Extend the Induction descriptor to also support inductions that involve
4275 //    casts: When needed (namely, when we are called in the context of the
4276 //    vectorizer induction analysis), a Set of cast instructions will be
4277 //    populated by this method, and provided back to isInductionPHI. This is
4278 //    needed to allow the vectorizer to properly record them to be ignored by
4279 //    the cost model and to avoid vectorizing them (otherwise these casts,
4280 //    which are redundant under the runtime overflow checks, will be
4281 //    vectorized, which can be costly).
4282 //
4283 // 2) Support additional induction/PHISCEV patterns: We also want to support
4284 //    inductions where the sext-trunc / zext-trunc operations (partly) occur
4285 //    after the induction update operation (the induction increment):
4286 //
4287 //      (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
4288 //    which correspond to a phi->add->trunc->sext/zext->phi update chain.
4289 //
4290 //      (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
4291 //    which correspond to a phi->trunc->add->sext/zext->phi update chain.
4292 //
4293 // 3) Outline common code with createAddRecFromPHI to avoid duplication.
4294 //
4295 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4296 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
4297   SmallVector<const SCEVPredicate *, 3> Predicates;
4298 
4299   // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
4300   // return an AddRec expression under some predicate.
4301 
4302   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
4303   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
4304   assert (L && "Expecting an integer loop header phi");
4305 
4306   // The loop may have multiple entrances or multiple exits; we can analyze
4307   // this phi as an addrec if it has a unique entry value and a unique
4308   // backedge value.
4309   Value *BEValueV = nullptr, *StartValueV = nullptr;
4310   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4311     Value *V = PN->getIncomingValue(i);
4312     if (L->contains(PN->getIncomingBlock(i))) {
4313       if (!BEValueV) {
4314         BEValueV = V;
4315       } else if (BEValueV != V) {
4316         BEValueV = nullptr;
4317         break;
4318       }
4319     } else if (!StartValueV) {
4320       StartValueV = V;
4321     } else if (StartValueV != V) {
4322       StartValueV = nullptr;
4323       break;
4324     }
4325   }
4326   if (!BEValueV || !StartValueV)
4327     return None;
4328 
4329   const SCEV *BEValue = getSCEV(BEValueV);
4330 
4331   // If the value coming around the backedge is an add with the symbolic
4332   // value we just inserted, possibly with casts that we can ignore under
4333   // an appropriate runtime guard, then we found a simple induction variable!
4334   const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
4335   if (!Add)
4336     return None;
4337 
4338   // If there is a single occurrence of the symbolic value, possibly
4339   // casted, replace it with a recurrence.
4340   unsigned FoundIndex = Add->getNumOperands();
4341   Type *TruncTy = nullptr;
4342   bool Signed;
4343   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4344     if ((TruncTy =
4345              isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
4346       if (FoundIndex == e) {
4347         FoundIndex = i;
4348         break;
4349       }
4350 
4351   if (FoundIndex == Add->getNumOperands())
4352     return None;
4353 
4354   // Create an add with everything but the specified operand.
4355   SmallVector<const SCEV *, 8> Ops;
4356   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4357     if (i != FoundIndex)
4358       Ops.push_back(Add->getOperand(i));
4359   const SCEV *Accum = getAddExpr(Ops);
4360 
4361   // The runtime checks will not be valid if the step amount is
4362   // varying inside the loop.
4363   if (!isLoopInvariant(Accum, L))
4364     return None;
4365 
4366 
4367   // *** Part2: Create the predicates
4368 
4369   // Analysis was successful: we have a phi-with-cast pattern for which we
4370   // can return an AddRec expression under the following predicates:
4371   //
4372   // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
4373   //     fits within the truncated type (does not overflow) for i = 0 to n-1.
4374   // P2: An Equal predicate that guarantees that
4375   //     Start = (Ext ix (Trunc iy (Start) to ix) to iy)
4376   // P3: An Equal predicate that guarantees that
4377   //     Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
4378   //
4379   // As we next prove, the above predicates guarantee that:
4380   //     Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
4381   //
4382   //
4383   // More formally, we want to prove that:
4384   //     Expr(i+1) = Start + (i+1) * Accum
4385   //               = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4386   //
4387   // Given that:
4388   // 1) Expr(0) = Start
4389   // 2) Expr(1) = Start + Accum
4390   //            = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
4391   // 3) Induction hypothesis (step i):
4392   //    Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
4393   //
4394   // Proof:
4395   //  Expr(i+1) =
4396   //   = Start + (i+1)*Accum
4397   //   = (Start + i*Accum) + Accum
4398   //   = Expr(i) + Accum
4399   //   = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
4400   //                                                             :: from step i
4401   //
4402   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
4403   //
4404   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
4405   //     + (Ext ix (Trunc iy (Accum) to ix) to iy)
4406   //     + Accum                                                     :: from P3
4407   //
4408   //   = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
4409   //     + Accum                            :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
4410   //
4411   //   = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
4412   //   = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4413   //
4414   // By induction, the same applies to all iterations 1<=i<n:
4415   //
4416 
4417   // Create a truncated addrec for which we will add a no overflow check (P1).
4418   const SCEV *StartVal = getSCEV(StartValueV);
4419   const SCEV *PHISCEV =
4420       getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
4421                     getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap);
4422   const auto *AR = cast<SCEVAddRecExpr>(PHISCEV);
4423 
4424   SCEVWrapPredicate::IncrementWrapFlags AddedFlags =
4425       Signed ? SCEVWrapPredicate::IncrementNSSW
4426              : SCEVWrapPredicate::IncrementNUSW;
4427   const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
4428   Predicates.push_back(AddRecPred);
4429 
4430   // Create the Equal Predicates P2,P3:
4431   auto AppendPredicate = [&](const SCEV *Expr) -> void {
4432     assert (isLoopInvariant(Expr, L) && "Expr is expected to be invariant");
4433     const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
4434     const SCEV *ExtendedExpr =
4435         Signed ? getSignExtendExpr(TruncatedExpr, Expr->getType())
4436                : getZeroExtendExpr(TruncatedExpr, Expr->getType());
4437     if (Expr != ExtendedExpr &&
4438         !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
4439       const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
4440       DEBUG (dbgs() << "Added Predicate: " << *Pred);
4441       Predicates.push_back(Pred);
4442     }
4443   };
4444 
4445   AppendPredicate(StartVal);
4446   AppendPredicate(Accum);
4447 
4448   // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
4449   // which the casts had been folded away. The caller can rewrite SymbolicPHI
4450   // into NewAR if it will also add the runtime overflow checks specified in
4451   // Predicates.
4452   auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap);
4453 
4454   std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
4455       std::make_pair(NewAR, Predicates);
4456   // Remember the result of the analysis for this SCEV at this locayyytion.
4457   PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
4458   return PredRewrite;
4459 }
4460 
4461 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4462 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) {
4463 
4464   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
4465   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
4466   if (!L)
4467     return None;
4468 
4469   // Check to see if we already analyzed this PHI.
4470   auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
4471   if (I != PredicatedSCEVRewrites.end()) {
4472     std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
4473         I->second;
4474     // Analysis was done before and failed to create an AddRec:
4475     if (Rewrite.first == SymbolicPHI)
4476       return None;
4477     // Analysis was done before and succeeded to create an AddRec under
4478     // a predicate:
4479     assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec");
4480     assert(!(Rewrite.second).empty() && "Expected to find Predicates");
4481     return Rewrite;
4482   }
4483 
4484   Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4485     Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
4486 
4487   // Record in the cache that the analysis failed
4488   if (!Rewrite) {
4489     SmallVector<const SCEVPredicate *, 3> Predicates;
4490     PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
4491     return None;
4492   }
4493 
4494   return Rewrite;
4495 }
4496 
4497 /// A helper function for createAddRecFromPHI to handle simple cases.
4498 ///
4499 /// This function tries to find an AddRec expression for the simplest (yet most
4500 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
4501 /// If it fails, createAddRecFromPHI will use a more general, but slow,
4502 /// technique for finding the AddRec expression.
4503 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
4504                                                       Value *BEValueV,
4505                                                       Value *StartValueV) {
4506   const Loop *L = LI.getLoopFor(PN->getParent());
4507   assert(L && L->getHeader() == PN->getParent());
4508   assert(BEValueV && StartValueV);
4509 
4510   auto BO = MatchBinaryOp(BEValueV, DT);
4511   if (!BO)
4512     return nullptr;
4513 
4514   if (BO->Opcode != Instruction::Add)
4515     return nullptr;
4516 
4517   const SCEV *Accum = nullptr;
4518   if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
4519     Accum = getSCEV(BO->RHS);
4520   else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
4521     Accum = getSCEV(BO->LHS);
4522 
4523   if (!Accum)
4524     return nullptr;
4525 
4526   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4527   if (BO->IsNUW)
4528     Flags = setFlags(Flags, SCEV::FlagNUW);
4529   if (BO->IsNSW)
4530     Flags = setFlags(Flags, SCEV::FlagNSW);
4531 
4532   const SCEV *StartVal = getSCEV(StartValueV);
4533   const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
4534 
4535   ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
4536 
4537   // We can add Flags to the post-inc expression only if we
4538   // know that it is *undefined behavior* for BEValueV to
4539   // overflow.
4540   if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
4541     if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
4542       (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
4543 
4544   return PHISCEV;
4545 }
4546 
4547 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
4548   const Loop *L = LI.getLoopFor(PN->getParent());
4549   if (!L || L->getHeader() != PN->getParent())
4550     return nullptr;
4551 
4552   // The loop may have multiple entrances or multiple exits; we can analyze
4553   // this phi as an addrec if it has a unique entry value and a unique
4554   // backedge value.
4555   Value *BEValueV = nullptr, *StartValueV = nullptr;
4556   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4557     Value *V = PN->getIncomingValue(i);
4558     if (L->contains(PN->getIncomingBlock(i))) {
4559       if (!BEValueV) {
4560         BEValueV = V;
4561       } else if (BEValueV != V) {
4562         BEValueV = nullptr;
4563         break;
4564       }
4565     } else if (!StartValueV) {
4566       StartValueV = V;
4567     } else if (StartValueV != V) {
4568       StartValueV = nullptr;
4569       break;
4570     }
4571   }
4572   if (!BEValueV || !StartValueV)
4573     return nullptr;
4574 
4575   assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
4576          "PHI node already processed?");
4577 
4578   // First, try to find AddRec expression without creating a fictituos symbolic
4579   // value for PN.
4580   if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
4581     return S;
4582 
4583   // Handle PHI node value symbolically.
4584   const SCEV *SymbolicName = getUnknown(PN);
4585   ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName});
4586 
4587   // Using this symbolic name for the PHI, analyze the value coming around
4588   // the back-edge.
4589   const SCEV *BEValue = getSCEV(BEValueV);
4590 
4591   // NOTE: If BEValue is loop invariant, we know that the PHI node just
4592   // has a special value for the first iteration of the loop.
4593 
4594   // If the value coming around the backedge is an add with the symbolic
4595   // value we just inserted, then we found a simple induction variable!
4596   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
4597     // If there is a single occurrence of the symbolic value, replace it
4598     // with a recurrence.
4599     unsigned FoundIndex = Add->getNumOperands();
4600     for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4601       if (Add->getOperand(i) == SymbolicName)
4602         if (FoundIndex == e) {
4603           FoundIndex = i;
4604           break;
4605         }
4606 
4607     if (FoundIndex != Add->getNumOperands()) {
4608       // Create an add with everything but the specified operand.
4609       SmallVector<const SCEV *, 8> Ops;
4610       for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4611         if (i != FoundIndex)
4612           Ops.push_back(Add->getOperand(i));
4613       const SCEV *Accum = getAddExpr(Ops);
4614 
4615       // This is not a valid addrec if the step amount is varying each
4616       // loop iteration, but is not itself an addrec in this loop.
4617       if (isLoopInvariant(Accum, L) ||
4618           (isa<SCEVAddRecExpr>(Accum) &&
4619            cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
4620         SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4621 
4622         if (auto BO = MatchBinaryOp(BEValueV, DT)) {
4623           if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
4624             if (BO->IsNUW)
4625               Flags = setFlags(Flags, SCEV::FlagNUW);
4626             if (BO->IsNSW)
4627               Flags = setFlags(Flags, SCEV::FlagNSW);
4628           }
4629         } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
4630           // If the increment is an inbounds GEP, then we know the address
4631           // space cannot be wrapped around. We cannot make any guarantee
4632           // about signed or unsigned overflow because pointers are
4633           // unsigned but we may have a negative index from the base
4634           // pointer. We can guarantee that no unsigned wrap occurs if the
4635           // indices form a positive value.
4636           if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
4637             Flags = setFlags(Flags, SCEV::FlagNW);
4638 
4639             const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
4640             if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
4641               Flags = setFlags(Flags, SCEV::FlagNUW);
4642           }
4643 
4644           // We cannot transfer nuw and nsw flags from subtraction
4645           // operations -- sub nuw X, Y is not the same as add nuw X, -Y
4646           // for instance.
4647         }
4648 
4649         const SCEV *StartVal = getSCEV(StartValueV);
4650         const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
4651 
4652         // Okay, for the entire analysis of this edge we assumed the PHI
4653         // to be symbolic.  We now need to go back and purge all of the
4654         // entries for the scalars that use the symbolic expression.
4655         forgetSymbolicName(PN, SymbolicName);
4656         ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
4657 
4658         // We can add Flags to the post-inc expression only if we
4659         // know that it is *undefined behavior* for BEValueV to
4660         // overflow.
4661         if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
4662           if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
4663             (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
4664 
4665         return PHISCEV;
4666       }
4667     }
4668   } else {
4669     // Otherwise, this could be a loop like this:
4670     //     i = 0;  for (j = 1; ..; ++j) { ....  i = j; }
4671     // In this case, j = {1,+,1}  and BEValue is j.
4672     // Because the other in-value of i (0) fits the evolution of BEValue
4673     // i really is an addrec evolution.
4674     //
4675     // We can generalize this saying that i is the shifted value of BEValue
4676     // by one iteration:
4677     //   PHI(f(0), f({1,+,1})) --> f({0,+,1})
4678     const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
4679     const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this);
4680     if (Shifted != getCouldNotCompute() &&
4681         Start != getCouldNotCompute()) {
4682       const SCEV *StartVal = getSCEV(StartValueV);
4683       if (Start == StartVal) {
4684         // Okay, for the entire analysis of this edge we assumed the PHI
4685         // to be symbolic.  We now need to go back and purge all of the
4686         // entries for the scalars that use the symbolic expression.
4687         forgetSymbolicName(PN, SymbolicName);
4688         ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted;
4689         return Shifted;
4690       }
4691     }
4692   }
4693 
4694   // Remove the temporary PHI node SCEV that has been inserted while intending
4695   // to create an AddRecExpr for this PHI node. We can not keep this temporary
4696   // as it will prevent later (possibly simpler) SCEV expressions to be added
4697   // to the ValueExprMap.
4698   eraseValueFromMap(PN);
4699 
4700   return nullptr;
4701 }
4702 
4703 // Checks if the SCEV S is available at BB.  S is considered available at BB
4704 // if S can be materialized at BB without introducing a fault.
4705 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
4706                                BasicBlock *BB) {
4707   struct CheckAvailable {
4708     bool TraversalDone = false;
4709     bool Available = true;
4710 
4711     const Loop *L = nullptr;  // The loop BB is in (can be nullptr)
4712     BasicBlock *BB = nullptr;
4713     DominatorTree &DT;
4714 
4715     CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
4716       : L(L), BB(BB), DT(DT) {}
4717 
4718     bool setUnavailable() {
4719       TraversalDone = true;
4720       Available = false;
4721       return false;
4722     }
4723 
4724     bool follow(const SCEV *S) {
4725       switch (S->getSCEVType()) {
4726       case scConstant: case scTruncate: case scZeroExtend: case scSignExtend:
4727       case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr:
4728         // These expressions are available if their operand(s) is/are.
4729         return true;
4730 
4731       case scAddRecExpr: {
4732         // We allow add recurrences that are on the loop BB is in, or some
4733         // outer loop.  This guarantees availability because the value of the
4734         // add recurrence at BB is simply the "current" value of the induction
4735         // variable.  We can relax this in the future; for instance an add
4736         // recurrence on a sibling dominating loop is also available at BB.
4737         const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
4738         if (L && (ARLoop == L || ARLoop->contains(L)))
4739           return true;
4740 
4741         return setUnavailable();
4742       }
4743 
4744       case scUnknown: {
4745         // For SCEVUnknown, we check for simple dominance.
4746         const auto *SU = cast<SCEVUnknown>(S);
4747         Value *V = SU->getValue();
4748 
4749         if (isa<Argument>(V))
4750           return false;
4751 
4752         if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
4753           return false;
4754 
4755         return setUnavailable();
4756       }
4757 
4758       case scUDivExpr:
4759       case scCouldNotCompute:
4760         // We do not try to smart about these at all.
4761         return setUnavailable();
4762       }
4763       llvm_unreachable("switch should be fully covered!");
4764     }
4765 
4766     bool isDone() { return TraversalDone; }
4767   };
4768 
4769   CheckAvailable CA(L, BB, DT);
4770   SCEVTraversal<CheckAvailable> ST(CA);
4771 
4772   ST.visitAll(S);
4773   return CA.Available;
4774 }
4775 
4776 // Try to match a control flow sequence that branches out at BI and merges back
4777 // at Merge into a "C ? LHS : RHS" select pattern.  Return true on a successful
4778 // match.
4779 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
4780                           Value *&C, Value *&LHS, Value *&RHS) {
4781   C = BI->getCondition();
4782 
4783   BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
4784   BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
4785 
4786   if (!LeftEdge.isSingleEdge())
4787     return false;
4788 
4789   assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
4790 
4791   Use &LeftUse = Merge->getOperandUse(0);
4792   Use &RightUse = Merge->getOperandUse(1);
4793 
4794   if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
4795     LHS = LeftUse;
4796     RHS = RightUse;
4797     return true;
4798   }
4799 
4800   if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
4801     LHS = RightUse;
4802     RHS = LeftUse;
4803     return true;
4804   }
4805 
4806   return false;
4807 }
4808 
4809 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
4810   auto IsReachable =
4811       [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
4812   if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
4813     const Loop *L = LI.getLoopFor(PN->getParent());
4814 
4815     // We don't want to break LCSSA, even in a SCEV expression tree.
4816     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
4817       if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
4818         return nullptr;
4819 
4820     // Try to match
4821     //
4822     //  br %cond, label %left, label %right
4823     // left:
4824     //  br label %merge
4825     // right:
4826     //  br label %merge
4827     // merge:
4828     //  V = phi [ %x, %left ], [ %y, %right ]
4829     //
4830     // as "select %cond, %x, %y"
4831 
4832     BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
4833     assert(IDom && "At least the entry block should dominate PN");
4834 
4835     auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
4836     Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
4837 
4838     if (BI && BI->isConditional() &&
4839         BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
4840         IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
4841         IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
4842       return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
4843   }
4844 
4845   return nullptr;
4846 }
4847 
4848 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
4849   if (const SCEV *S = createAddRecFromPHI(PN))
4850     return S;
4851 
4852   if (const SCEV *S = createNodeFromSelectLikePHI(PN))
4853     return S;
4854 
4855   // If the PHI has a single incoming value, follow that value, unless the
4856   // PHI's incoming blocks are in a different loop, in which case doing so
4857   // risks breaking LCSSA form. Instcombine would normally zap these, but
4858   // it doesn't have DominatorTree information, so it may miss cases.
4859   if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC}))
4860     if (LI.replacementPreservesLCSSAForm(PN, V))
4861       return getSCEV(V);
4862 
4863   // If it's not a loop phi, we can't handle it yet.
4864   return getUnknown(PN);
4865 }
4866 
4867 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I,
4868                                                       Value *Cond,
4869                                                       Value *TrueVal,
4870                                                       Value *FalseVal) {
4871   // Handle "constant" branch or select. This can occur for instance when a
4872   // loop pass transforms an inner loop and moves on to process the outer loop.
4873   if (auto *CI = dyn_cast<ConstantInt>(Cond))
4874     return getSCEV(CI->isOne() ? TrueVal : FalseVal);
4875 
4876   // Try to match some simple smax or umax patterns.
4877   auto *ICI = dyn_cast<ICmpInst>(Cond);
4878   if (!ICI)
4879     return getUnknown(I);
4880 
4881   Value *LHS = ICI->getOperand(0);
4882   Value *RHS = ICI->getOperand(1);
4883 
4884   switch (ICI->getPredicate()) {
4885   case ICmpInst::ICMP_SLT:
4886   case ICmpInst::ICMP_SLE:
4887     std::swap(LHS, RHS);
4888     LLVM_FALLTHROUGH;
4889   case ICmpInst::ICMP_SGT:
4890   case ICmpInst::ICMP_SGE:
4891     // a >s b ? a+x : b+x  ->  smax(a, b)+x
4892     // a >s b ? b+x : a+x  ->  smin(a, b)+x
4893     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
4894       const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType());
4895       const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType());
4896       const SCEV *LA = getSCEV(TrueVal);
4897       const SCEV *RA = getSCEV(FalseVal);
4898       const SCEV *LDiff = getMinusSCEV(LA, LS);
4899       const SCEV *RDiff = getMinusSCEV(RA, RS);
4900       if (LDiff == RDiff)
4901         return getAddExpr(getSMaxExpr(LS, RS), LDiff);
4902       LDiff = getMinusSCEV(LA, RS);
4903       RDiff = getMinusSCEV(RA, LS);
4904       if (LDiff == RDiff)
4905         return getAddExpr(getSMinExpr(LS, RS), LDiff);
4906     }
4907     break;
4908   case ICmpInst::ICMP_ULT:
4909   case ICmpInst::ICMP_ULE:
4910     std::swap(LHS, RHS);
4911     LLVM_FALLTHROUGH;
4912   case ICmpInst::ICMP_UGT:
4913   case ICmpInst::ICMP_UGE:
4914     // a >u b ? a+x : b+x  ->  umax(a, b)+x
4915     // a >u b ? b+x : a+x  ->  umin(a, b)+x
4916     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
4917       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4918       const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType());
4919       const SCEV *LA = getSCEV(TrueVal);
4920       const SCEV *RA = getSCEV(FalseVal);
4921       const SCEV *LDiff = getMinusSCEV(LA, LS);
4922       const SCEV *RDiff = getMinusSCEV(RA, RS);
4923       if (LDiff == RDiff)
4924         return getAddExpr(getUMaxExpr(LS, RS), LDiff);
4925       LDiff = getMinusSCEV(LA, RS);
4926       RDiff = getMinusSCEV(RA, LS);
4927       if (LDiff == RDiff)
4928         return getAddExpr(getUMinExpr(LS, RS), LDiff);
4929     }
4930     break;
4931   case ICmpInst::ICMP_NE:
4932     // n != 0 ? n+x : 1+x  ->  umax(n, 1)+x
4933     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
4934         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
4935       const SCEV *One = getOne(I->getType());
4936       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4937       const SCEV *LA = getSCEV(TrueVal);
4938       const SCEV *RA = getSCEV(FalseVal);
4939       const SCEV *LDiff = getMinusSCEV(LA, LS);
4940       const SCEV *RDiff = getMinusSCEV(RA, One);
4941       if (LDiff == RDiff)
4942         return getAddExpr(getUMaxExpr(One, LS), LDiff);
4943     }
4944     break;
4945   case ICmpInst::ICMP_EQ:
4946     // n == 0 ? 1+x : n+x  ->  umax(n, 1)+x
4947     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
4948         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
4949       const SCEV *One = getOne(I->getType());
4950       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4951       const SCEV *LA = getSCEV(TrueVal);
4952       const SCEV *RA = getSCEV(FalseVal);
4953       const SCEV *LDiff = getMinusSCEV(LA, One);
4954       const SCEV *RDiff = getMinusSCEV(RA, LS);
4955       if (LDiff == RDiff)
4956         return getAddExpr(getUMaxExpr(One, LS), LDiff);
4957     }
4958     break;
4959   default:
4960     break;
4961   }
4962 
4963   return getUnknown(I);
4964 }
4965 
4966 /// Expand GEP instructions into add and multiply operations. This allows them
4967 /// to be analyzed by regular SCEV code.
4968 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
4969   // Don't attempt to analyze GEPs over unsized objects.
4970   if (!GEP->getSourceElementType()->isSized())
4971     return getUnknown(GEP);
4972 
4973   SmallVector<const SCEV *, 4> IndexExprs;
4974   for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
4975     IndexExprs.push_back(getSCEV(*Index));
4976   return getGEPExpr(GEP, IndexExprs);
4977 }
4978 
4979 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) {
4980   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
4981     return C->getAPInt().countTrailingZeros();
4982 
4983   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
4984     return std::min(GetMinTrailingZeros(T->getOperand()),
4985                     (uint32_t)getTypeSizeInBits(T->getType()));
4986 
4987   if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
4988     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
4989     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
4990                ? getTypeSizeInBits(E->getType())
4991                : OpRes;
4992   }
4993 
4994   if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
4995     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
4996     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
4997                ? getTypeSizeInBits(E->getType())
4998                : OpRes;
4999   }
5000 
5001   if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
5002     // The result is the min of all operands results.
5003     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5004     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5005       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5006     return MinOpRes;
5007   }
5008 
5009   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
5010     // The result is the sum of all operands results.
5011     uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
5012     uint32_t BitWidth = getTypeSizeInBits(M->getType());
5013     for (unsigned i = 1, e = M->getNumOperands();
5014          SumOpRes != BitWidth && i != e; ++i)
5015       SumOpRes =
5016           std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth);
5017     return SumOpRes;
5018   }
5019 
5020   if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
5021     // The result is the min of all operands results.
5022     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5023     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5024       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5025     return MinOpRes;
5026   }
5027 
5028   if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
5029     // The result is the min of all operands results.
5030     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5031     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5032       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5033     return MinOpRes;
5034   }
5035 
5036   if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
5037     // The result is the min of all operands results.
5038     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5039     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5040       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5041     return MinOpRes;
5042   }
5043 
5044   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5045     // For a SCEVUnknown, ask ValueTracking.
5046     KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT);
5047     return Known.countMinTrailingZeros();
5048   }
5049 
5050   // SCEVUDivExpr
5051   return 0;
5052 }
5053 
5054 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
5055   auto I = MinTrailingZerosCache.find(S);
5056   if (I != MinTrailingZerosCache.end())
5057     return I->second;
5058 
5059   uint32_t Result = GetMinTrailingZerosImpl(S);
5060   auto InsertPair = MinTrailingZerosCache.insert({S, Result});
5061   assert(InsertPair.second && "Should insert a new key");
5062   return InsertPair.first->second;
5063 }
5064 
5065 /// Helper method to assign a range to V from metadata present in the IR.
5066 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
5067   if (Instruction *I = dyn_cast<Instruction>(V))
5068     if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
5069       return getConstantRangeFromMetadata(*MD);
5070 
5071   return None;
5072 }
5073 
5074 /// Determine the range for a particular SCEV.  If SignHint is
5075 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
5076 /// with a "cleaner" unsigned (resp. signed) representation.
5077 const ConstantRange &
5078 ScalarEvolution::getRangeRef(const SCEV *S,
5079                              ScalarEvolution::RangeSignHint SignHint) {
5080   DenseMap<const SCEV *, ConstantRange> &Cache =
5081       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
5082                                                        : SignedRanges;
5083 
5084   // See if we've computed this range already.
5085   DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
5086   if (I != Cache.end())
5087     return I->second;
5088 
5089   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5090     return setRange(C, SignHint, ConstantRange(C->getAPInt()));
5091 
5092   unsigned BitWidth = getTypeSizeInBits(S->getType());
5093   ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
5094 
5095   // If the value has known zeros, the maximum value will have those known zeros
5096   // as well.
5097   uint32_t TZ = GetMinTrailingZeros(S);
5098   if (TZ != 0) {
5099     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
5100       ConservativeResult =
5101           ConstantRange(APInt::getMinValue(BitWidth),
5102                         APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
5103     else
5104       ConservativeResult = ConstantRange(
5105           APInt::getSignedMinValue(BitWidth),
5106           APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
5107   }
5108 
5109   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
5110     ConstantRange X = getRangeRef(Add->getOperand(0), SignHint);
5111     for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
5112       X = X.add(getRangeRef(Add->getOperand(i), SignHint));
5113     return setRange(Add, SignHint, ConservativeResult.intersectWith(X));
5114   }
5115 
5116   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
5117     ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint);
5118     for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
5119       X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint));
5120     return setRange(Mul, SignHint, ConservativeResult.intersectWith(X));
5121   }
5122 
5123   if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
5124     ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint);
5125     for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
5126       X = X.smax(getRangeRef(SMax->getOperand(i), SignHint));
5127     return setRange(SMax, SignHint, ConservativeResult.intersectWith(X));
5128   }
5129 
5130   if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
5131     ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint);
5132     for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
5133       X = X.umax(getRangeRef(UMax->getOperand(i), SignHint));
5134     return setRange(UMax, SignHint, ConservativeResult.intersectWith(X));
5135   }
5136 
5137   if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
5138     ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint);
5139     ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint);
5140     return setRange(UDiv, SignHint,
5141                     ConservativeResult.intersectWith(X.udiv(Y)));
5142   }
5143 
5144   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
5145     ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint);
5146     return setRange(ZExt, SignHint,
5147                     ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
5148   }
5149 
5150   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
5151     ConstantRange X = getRangeRef(SExt->getOperand(), SignHint);
5152     return setRange(SExt, SignHint,
5153                     ConservativeResult.intersectWith(X.signExtend(BitWidth)));
5154   }
5155 
5156   if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
5157     ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint);
5158     return setRange(Trunc, SignHint,
5159                     ConservativeResult.intersectWith(X.truncate(BitWidth)));
5160   }
5161 
5162   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
5163     // If there's no unsigned wrap, the value will never be less than its
5164     // initial value.
5165     if (AddRec->hasNoUnsignedWrap())
5166       if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
5167         if (!C->getValue()->isZero())
5168           ConservativeResult = ConservativeResult.intersectWith(
5169               ConstantRange(C->getAPInt(), APInt(BitWidth, 0)));
5170 
5171     // If there's no signed wrap, and all the operands have the same sign or
5172     // zero, the value won't ever change sign.
5173     if (AddRec->hasNoSignedWrap()) {
5174       bool AllNonNeg = true;
5175       bool AllNonPos = true;
5176       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
5177         if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
5178         if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
5179       }
5180       if (AllNonNeg)
5181         ConservativeResult = ConservativeResult.intersectWith(
5182           ConstantRange(APInt(BitWidth, 0),
5183                         APInt::getSignedMinValue(BitWidth)));
5184       else if (AllNonPos)
5185         ConservativeResult = ConservativeResult.intersectWith(
5186           ConstantRange(APInt::getSignedMinValue(BitWidth),
5187                         APInt(BitWidth, 1)));
5188     }
5189 
5190     // TODO: non-affine addrec
5191     if (AddRec->isAffine()) {
5192       const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
5193       if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
5194           getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
5195         auto RangeFromAffine = getRangeForAffineAR(
5196             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
5197             BitWidth);
5198         if (!RangeFromAffine.isFullSet())
5199           ConservativeResult =
5200               ConservativeResult.intersectWith(RangeFromAffine);
5201 
5202         auto RangeFromFactoring = getRangeViaFactoring(
5203             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
5204             BitWidth);
5205         if (!RangeFromFactoring.isFullSet())
5206           ConservativeResult =
5207               ConservativeResult.intersectWith(RangeFromFactoring);
5208       }
5209     }
5210 
5211     return setRange(AddRec, SignHint, std::move(ConservativeResult));
5212   }
5213 
5214   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5215     // Check if the IR explicitly contains !range metadata.
5216     Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
5217     if (MDRange.hasValue())
5218       ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue());
5219 
5220     // Split here to avoid paying the compile-time cost of calling both
5221     // computeKnownBits and ComputeNumSignBits.  This restriction can be lifted
5222     // if needed.
5223     const DataLayout &DL = getDataLayout();
5224     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
5225       // For a SCEVUnknown, ask ValueTracking.
5226       KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
5227       if (Known.One != ~Known.Zero + 1)
5228         ConservativeResult =
5229             ConservativeResult.intersectWith(ConstantRange(Known.One,
5230                                                            ~Known.Zero + 1));
5231     } else {
5232       assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED &&
5233              "generalize as needed!");
5234       unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
5235       if (NS > 1)
5236         ConservativeResult = ConservativeResult.intersectWith(
5237             ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
5238                           APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1));
5239     }
5240 
5241     return setRange(U, SignHint, std::move(ConservativeResult));
5242   }
5243 
5244   return setRange(S, SignHint, std::move(ConservativeResult));
5245 }
5246 
5247 // Given a StartRange, Step and MaxBECount for an expression compute a range of
5248 // values that the expression can take. Initially, the expression has a value
5249 // from StartRange and then is changed by Step up to MaxBECount times. Signed
5250 // argument defines if we treat Step as signed or unsigned.
5251 static ConstantRange getRangeForAffineARHelper(APInt Step,
5252                                                const ConstantRange &StartRange,
5253                                                const APInt &MaxBECount,
5254                                                unsigned BitWidth, bool Signed) {
5255   // If either Step or MaxBECount is 0, then the expression won't change, and we
5256   // just need to return the initial range.
5257   if (Step == 0 || MaxBECount == 0)
5258     return StartRange;
5259 
5260   // If we don't know anything about the initial value (i.e. StartRange is
5261   // FullRange), then we don't know anything about the final range either.
5262   // Return FullRange.
5263   if (StartRange.isFullSet())
5264     return ConstantRange(BitWidth, /* isFullSet = */ true);
5265 
5266   // If Step is signed and negative, then we use its absolute value, but we also
5267   // note that we're moving in the opposite direction.
5268   bool Descending = Signed && Step.isNegative();
5269 
5270   if (Signed)
5271     // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
5272     // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
5273     // This equations hold true due to the well-defined wrap-around behavior of
5274     // APInt.
5275     Step = Step.abs();
5276 
5277   // Check if Offset is more than full span of BitWidth. If it is, the
5278   // expression is guaranteed to overflow.
5279   if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
5280     return ConstantRange(BitWidth, /* isFullSet = */ true);
5281 
5282   // Offset is by how much the expression can change. Checks above guarantee no
5283   // overflow here.
5284   APInt Offset = Step * MaxBECount;
5285 
5286   // Minimum value of the final range will match the minimal value of StartRange
5287   // if the expression is increasing and will be decreased by Offset otherwise.
5288   // Maximum value of the final range will match the maximal value of StartRange
5289   // if the expression is decreasing and will be increased by Offset otherwise.
5290   APInt StartLower = StartRange.getLower();
5291   APInt StartUpper = StartRange.getUpper() - 1;
5292   APInt MovedBoundary = Descending ? (StartLower - std::move(Offset))
5293                                    : (StartUpper + std::move(Offset));
5294 
5295   // It's possible that the new minimum/maximum value will fall into the initial
5296   // range (due to wrap around). This means that the expression can take any
5297   // value in this bitwidth, and we have to return full range.
5298   if (StartRange.contains(MovedBoundary))
5299     return ConstantRange(BitWidth, /* isFullSet = */ true);
5300 
5301   APInt NewLower =
5302       Descending ? std::move(MovedBoundary) : std::move(StartLower);
5303   APInt NewUpper =
5304       Descending ? std::move(StartUpper) : std::move(MovedBoundary);
5305   NewUpper += 1;
5306 
5307   // If we end up with full range, return a proper full range.
5308   if (NewLower == NewUpper)
5309     return ConstantRange(BitWidth, /* isFullSet = */ true);
5310 
5311   // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
5312   return ConstantRange(std::move(NewLower), std::move(NewUpper));
5313 }
5314 
5315 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
5316                                                    const SCEV *Step,
5317                                                    const SCEV *MaxBECount,
5318                                                    unsigned BitWidth) {
5319   assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&
5320          getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
5321          "Precondition!");
5322 
5323   MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType());
5324   APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount);
5325 
5326   // First, consider step signed.
5327   ConstantRange StartSRange = getSignedRange(Start);
5328   ConstantRange StepSRange = getSignedRange(Step);
5329 
5330   // If Step can be both positive and negative, we need to find ranges for the
5331   // maximum absolute step values in both directions and union them.
5332   ConstantRange SR =
5333       getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange,
5334                                 MaxBECountValue, BitWidth, /* Signed = */ true);
5335   SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(),
5336                                               StartSRange, MaxBECountValue,
5337                                               BitWidth, /* Signed = */ true));
5338 
5339   // Next, consider step unsigned.
5340   ConstantRange UR = getRangeForAffineARHelper(
5341       getUnsignedRangeMax(Step), getUnsignedRange(Start),
5342       MaxBECountValue, BitWidth, /* Signed = */ false);
5343 
5344   // Finally, intersect signed and unsigned ranges.
5345   return SR.intersectWith(UR);
5346 }
5347 
5348 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
5349                                                     const SCEV *Step,
5350                                                     const SCEV *MaxBECount,
5351                                                     unsigned BitWidth) {
5352   //    RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
5353   // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
5354 
5355   struct SelectPattern {
5356     Value *Condition = nullptr;
5357     APInt TrueValue;
5358     APInt FalseValue;
5359 
5360     explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
5361                            const SCEV *S) {
5362       Optional<unsigned> CastOp;
5363       APInt Offset(BitWidth, 0);
5364 
5365       assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&
5366              "Should be!");
5367 
5368       // Peel off a constant offset:
5369       if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
5370         // In the future we could consider being smarter here and handle
5371         // {Start+Step,+,Step} too.
5372         if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
5373           return;
5374 
5375         Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
5376         S = SA->getOperand(1);
5377       }
5378 
5379       // Peel off a cast operation
5380       if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) {
5381         CastOp = SCast->getSCEVType();
5382         S = SCast->getOperand();
5383       }
5384 
5385       using namespace llvm::PatternMatch;
5386 
5387       auto *SU = dyn_cast<SCEVUnknown>(S);
5388       const APInt *TrueVal, *FalseVal;
5389       if (!SU ||
5390           !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
5391                                           m_APInt(FalseVal)))) {
5392         Condition = nullptr;
5393         return;
5394       }
5395 
5396       TrueValue = *TrueVal;
5397       FalseValue = *FalseVal;
5398 
5399       // Re-apply the cast we peeled off earlier
5400       if (CastOp.hasValue())
5401         switch (*CastOp) {
5402         default:
5403           llvm_unreachable("Unknown SCEV cast type!");
5404 
5405         case scTruncate:
5406           TrueValue = TrueValue.trunc(BitWidth);
5407           FalseValue = FalseValue.trunc(BitWidth);
5408           break;
5409         case scZeroExtend:
5410           TrueValue = TrueValue.zext(BitWidth);
5411           FalseValue = FalseValue.zext(BitWidth);
5412           break;
5413         case scSignExtend:
5414           TrueValue = TrueValue.sext(BitWidth);
5415           FalseValue = FalseValue.sext(BitWidth);
5416           break;
5417         }
5418 
5419       // Re-apply the constant offset we peeled off earlier
5420       TrueValue += Offset;
5421       FalseValue += Offset;
5422     }
5423 
5424     bool isRecognized() { return Condition != nullptr; }
5425   };
5426 
5427   SelectPattern StartPattern(*this, BitWidth, Start);
5428   if (!StartPattern.isRecognized())
5429     return ConstantRange(BitWidth, /* isFullSet = */ true);
5430 
5431   SelectPattern StepPattern(*this, BitWidth, Step);
5432   if (!StepPattern.isRecognized())
5433     return ConstantRange(BitWidth, /* isFullSet = */ true);
5434 
5435   if (StartPattern.Condition != StepPattern.Condition) {
5436     // We don't handle this case today; but we could, by considering four
5437     // possibilities below instead of two. I'm not sure if there are cases where
5438     // that will help over what getRange already does, though.
5439     return ConstantRange(BitWidth, /* isFullSet = */ true);
5440   }
5441 
5442   // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
5443   // construct arbitrary general SCEV expressions here.  This function is called
5444   // from deep in the call stack, and calling getSCEV (on a sext instruction,
5445   // say) can end up caching a suboptimal value.
5446 
5447   // FIXME: without the explicit `this` receiver below, MSVC errors out with
5448   // C2352 and C2512 (otherwise it isn't needed).
5449 
5450   const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
5451   const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
5452   const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
5453   const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
5454 
5455   ConstantRange TrueRange =
5456       this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
5457   ConstantRange FalseRange =
5458       this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
5459 
5460   return TrueRange.unionWith(FalseRange);
5461 }
5462 
5463 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
5464   if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
5465   const BinaryOperator *BinOp = cast<BinaryOperator>(V);
5466 
5467   // Return early if there are no flags to propagate to the SCEV.
5468   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5469   if (BinOp->hasNoUnsignedWrap())
5470     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
5471   if (BinOp->hasNoSignedWrap())
5472     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
5473   if (Flags == SCEV::FlagAnyWrap)
5474     return SCEV::FlagAnyWrap;
5475 
5476   return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
5477 }
5478 
5479 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
5480   // Here we check that I is in the header of the innermost loop containing I,
5481   // since we only deal with instructions in the loop header. The actual loop we
5482   // need to check later will come from an add recurrence, but getting that
5483   // requires computing the SCEV of the operands, which can be expensive. This
5484   // check we can do cheaply to rule out some cases early.
5485   Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent());
5486   if (InnermostContainingLoop == nullptr ||
5487       InnermostContainingLoop->getHeader() != I->getParent())
5488     return false;
5489 
5490   // Only proceed if we can prove that I does not yield poison.
5491   if (!programUndefinedIfFullPoison(I))
5492     return false;
5493 
5494   // At this point we know that if I is executed, then it does not wrap
5495   // according to at least one of NSW or NUW. If I is not executed, then we do
5496   // not know if the calculation that I represents would wrap. Multiple
5497   // instructions can map to the same SCEV. If we apply NSW or NUW from I to
5498   // the SCEV, we must guarantee no wrapping for that SCEV also when it is
5499   // derived from other instructions that map to the same SCEV. We cannot make
5500   // that guarantee for cases where I is not executed. So we need to find the
5501   // loop that I is considered in relation to and prove that I is executed for
5502   // every iteration of that loop. That implies that the value that I
5503   // calculates does not wrap anywhere in the loop, so then we can apply the
5504   // flags to the SCEV.
5505   //
5506   // We check isLoopInvariant to disambiguate in case we are adding recurrences
5507   // from different loops, so that we know which loop to prove that I is
5508   // executed in.
5509   for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) {
5510     // I could be an extractvalue from a call to an overflow intrinsic.
5511     // TODO: We can do better here in some cases.
5512     if (!isSCEVable(I->getOperand(OpIndex)->getType()))
5513       return false;
5514     const SCEV *Op = getSCEV(I->getOperand(OpIndex));
5515     if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
5516       bool AllOtherOpsLoopInvariant = true;
5517       for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands();
5518            ++OtherOpIndex) {
5519         if (OtherOpIndex != OpIndex) {
5520           const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex));
5521           if (!isLoopInvariant(OtherOp, AddRec->getLoop())) {
5522             AllOtherOpsLoopInvariant = false;
5523             break;
5524           }
5525         }
5526       }
5527       if (AllOtherOpsLoopInvariant &&
5528           isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop()))
5529         return true;
5530     }
5531   }
5532   return false;
5533 }
5534 
5535 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
5536   // If we know that \c I can never be poison period, then that's enough.
5537   if (isSCEVExprNeverPoison(I))
5538     return true;
5539 
5540   // For an add recurrence specifically, we assume that infinite loops without
5541   // side effects are undefined behavior, and then reason as follows:
5542   //
5543   // If the add recurrence is poison in any iteration, it is poison on all
5544   // future iterations (since incrementing poison yields poison). If the result
5545   // of the add recurrence is fed into the loop latch condition and the loop
5546   // does not contain any throws or exiting blocks other than the latch, we now
5547   // have the ability to "choose" whether the backedge is taken or not (by
5548   // choosing a sufficiently evil value for the poison feeding into the branch)
5549   // for every iteration including and after the one in which \p I first became
5550   // poison.  There are two possibilities (let's call the iteration in which \p
5551   // I first became poison as K):
5552   //
5553   //  1. In the set of iterations including and after K, the loop body executes
5554   //     no side effects.  In this case executing the backege an infinte number
5555   //     of times will yield undefined behavior.
5556   //
5557   //  2. In the set of iterations including and after K, the loop body executes
5558   //     at least one side effect.  In this case, that specific instance of side
5559   //     effect is control dependent on poison, which also yields undefined
5560   //     behavior.
5561 
5562   auto *ExitingBB = L->getExitingBlock();
5563   auto *LatchBB = L->getLoopLatch();
5564   if (!ExitingBB || !LatchBB || ExitingBB != LatchBB)
5565     return false;
5566 
5567   SmallPtrSet<const Instruction *, 16> Pushed;
5568   SmallVector<const Instruction *, 8> PoisonStack;
5569 
5570   // We start by assuming \c I, the post-inc add recurrence, is poison.  Only
5571   // things that are known to be fully poison under that assumption go on the
5572   // PoisonStack.
5573   Pushed.insert(I);
5574   PoisonStack.push_back(I);
5575 
5576   bool LatchControlDependentOnPoison = false;
5577   while (!PoisonStack.empty() && !LatchControlDependentOnPoison) {
5578     const Instruction *Poison = PoisonStack.pop_back_val();
5579 
5580     for (auto *PoisonUser : Poison->users()) {
5581       if (propagatesFullPoison(cast<Instruction>(PoisonUser))) {
5582         if (Pushed.insert(cast<Instruction>(PoisonUser)).second)
5583           PoisonStack.push_back(cast<Instruction>(PoisonUser));
5584       } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) {
5585         assert(BI->isConditional() && "Only possibility!");
5586         if (BI->getParent() == LatchBB) {
5587           LatchControlDependentOnPoison = true;
5588           break;
5589         }
5590       }
5591     }
5592   }
5593 
5594   return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L);
5595 }
5596 
5597 ScalarEvolution::LoopProperties
5598 ScalarEvolution::getLoopProperties(const Loop *L) {
5599   typedef ScalarEvolution::LoopProperties LoopProperties;
5600 
5601   auto Itr = LoopPropertiesCache.find(L);
5602   if (Itr == LoopPropertiesCache.end()) {
5603     auto HasSideEffects = [](Instruction *I) {
5604       if (auto *SI = dyn_cast<StoreInst>(I))
5605         return !SI->isSimple();
5606 
5607       return I->mayHaveSideEffects();
5608     };
5609 
5610     LoopProperties LP = {/* HasNoAbnormalExits */ true,
5611                          /*HasNoSideEffects*/ true};
5612 
5613     for (auto *BB : L->getBlocks())
5614       for (auto &I : *BB) {
5615         if (!isGuaranteedToTransferExecutionToSuccessor(&I))
5616           LP.HasNoAbnormalExits = false;
5617         if (HasSideEffects(&I))
5618           LP.HasNoSideEffects = false;
5619         if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
5620           break; // We're already as pessimistic as we can get.
5621       }
5622 
5623     auto InsertPair = LoopPropertiesCache.insert({L, LP});
5624     assert(InsertPair.second && "We just checked!");
5625     Itr = InsertPair.first;
5626   }
5627 
5628   return Itr->second;
5629 }
5630 
5631 const SCEV *ScalarEvolution::createSCEV(Value *V) {
5632   if (!isSCEVable(V->getType()))
5633     return getUnknown(V);
5634 
5635   if (Instruction *I = dyn_cast<Instruction>(V)) {
5636     // Don't attempt to analyze instructions in blocks that aren't
5637     // reachable. Such instructions don't matter, and they aren't required
5638     // to obey basic rules for definitions dominating uses which this
5639     // analysis depends on.
5640     if (!DT.isReachableFromEntry(I->getParent()))
5641       return getUnknown(V);
5642   } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
5643     return getConstant(CI);
5644   else if (isa<ConstantPointerNull>(V))
5645     return getZero(V->getType());
5646   else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
5647     return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee());
5648   else if (!isa<ConstantExpr>(V))
5649     return getUnknown(V);
5650 
5651   Operator *U = cast<Operator>(V);
5652   if (auto BO = MatchBinaryOp(U, DT)) {
5653     switch (BO->Opcode) {
5654     case Instruction::Add: {
5655       // The simple thing to do would be to just call getSCEV on both operands
5656       // and call getAddExpr with the result. However if we're looking at a
5657       // bunch of things all added together, this can be quite inefficient,
5658       // because it leads to N-1 getAddExpr calls for N ultimate operands.
5659       // Instead, gather up all the operands and make a single getAddExpr call.
5660       // LLVM IR canonical form means we need only traverse the left operands.
5661       SmallVector<const SCEV *, 4> AddOps;
5662       do {
5663         if (BO->Op) {
5664           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
5665             AddOps.push_back(OpSCEV);
5666             break;
5667           }
5668 
5669           // If a NUW or NSW flag can be applied to the SCEV for this
5670           // addition, then compute the SCEV for this addition by itself
5671           // with a separate call to getAddExpr. We need to do that
5672           // instead of pushing the operands of the addition onto AddOps,
5673           // since the flags are only known to apply to this particular
5674           // addition - they may not apply to other additions that can be
5675           // formed with operands from AddOps.
5676           const SCEV *RHS = getSCEV(BO->RHS);
5677           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
5678           if (Flags != SCEV::FlagAnyWrap) {
5679             const SCEV *LHS = getSCEV(BO->LHS);
5680             if (BO->Opcode == Instruction::Sub)
5681               AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
5682             else
5683               AddOps.push_back(getAddExpr(LHS, RHS, Flags));
5684             break;
5685           }
5686         }
5687 
5688         if (BO->Opcode == Instruction::Sub)
5689           AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
5690         else
5691           AddOps.push_back(getSCEV(BO->RHS));
5692 
5693         auto NewBO = MatchBinaryOp(BO->LHS, DT);
5694         if (!NewBO || (NewBO->Opcode != Instruction::Add &&
5695                        NewBO->Opcode != Instruction::Sub)) {
5696           AddOps.push_back(getSCEV(BO->LHS));
5697           break;
5698         }
5699         BO = NewBO;
5700       } while (true);
5701 
5702       return getAddExpr(AddOps);
5703     }
5704 
5705     case Instruction::Mul: {
5706       SmallVector<const SCEV *, 4> MulOps;
5707       do {
5708         if (BO->Op) {
5709           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
5710             MulOps.push_back(OpSCEV);
5711             break;
5712           }
5713 
5714           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
5715           if (Flags != SCEV::FlagAnyWrap) {
5716             MulOps.push_back(
5717                 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags));
5718             break;
5719           }
5720         }
5721 
5722         MulOps.push_back(getSCEV(BO->RHS));
5723         auto NewBO = MatchBinaryOp(BO->LHS, DT);
5724         if (!NewBO || NewBO->Opcode != Instruction::Mul) {
5725           MulOps.push_back(getSCEV(BO->LHS));
5726           break;
5727         }
5728         BO = NewBO;
5729       } while (true);
5730 
5731       return getMulExpr(MulOps);
5732     }
5733     case Instruction::UDiv:
5734       return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
5735     case Instruction::Sub: {
5736       SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5737       if (BO->Op)
5738         Flags = getNoWrapFlagsFromUB(BO->Op);
5739       return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags);
5740     }
5741     case Instruction::And:
5742       // For an expression like x&255 that merely masks off the high bits,
5743       // use zext(trunc(x)) as the SCEV expression.
5744       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5745         if (CI->isZero())
5746           return getSCEV(BO->RHS);
5747         if (CI->isMinusOne())
5748           return getSCEV(BO->LHS);
5749         const APInt &A = CI->getValue();
5750 
5751         // Instcombine's ShrinkDemandedConstant may strip bits out of
5752         // constants, obscuring what would otherwise be a low-bits mask.
5753         // Use computeKnownBits to compute what ShrinkDemandedConstant
5754         // knew about to reconstruct a low-bits mask value.
5755         unsigned LZ = A.countLeadingZeros();
5756         unsigned TZ = A.countTrailingZeros();
5757         unsigned BitWidth = A.getBitWidth();
5758         KnownBits Known(BitWidth);
5759         computeKnownBits(BO->LHS, Known, getDataLayout(),
5760                          0, &AC, nullptr, &DT);
5761 
5762         APInt EffectiveMask =
5763             APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
5764         if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
5765           const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
5766           const SCEV *LHS = getSCEV(BO->LHS);
5767           const SCEV *ShiftedLHS = nullptr;
5768           if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
5769             if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
5770               // For an expression like (x * 8) & 8, simplify the multiply.
5771               unsigned MulZeros = OpC->getAPInt().countTrailingZeros();
5772               unsigned GCD = std::min(MulZeros, TZ);
5773               APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
5774               SmallVector<const SCEV*, 4> MulOps;
5775               MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD)));
5776               MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end());
5777               auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
5778               ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
5779             }
5780           }
5781           if (!ShiftedLHS)
5782             ShiftedLHS = getUDivExpr(LHS, MulCount);
5783           return getMulExpr(
5784               getZeroExtendExpr(
5785                   getTruncateExpr(ShiftedLHS,
5786                       IntegerType::get(getContext(), BitWidth - LZ - TZ)),
5787                   BO->LHS->getType()),
5788               MulCount);
5789         }
5790       }
5791       break;
5792 
5793     case Instruction::Or:
5794       // If the RHS of the Or is a constant, we may have something like:
5795       // X*4+1 which got turned into X*4|1.  Handle this as an Add so loop
5796       // optimizations will transparently handle this case.
5797       //
5798       // In order for this transformation to be safe, the LHS must be of the
5799       // form X*(2^n) and the Or constant must be less than 2^n.
5800       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5801         const SCEV *LHS = getSCEV(BO->LHS);
5802         const APInt &CIVal = CI->getValue();
5803         if (GetMinTrailingZeros(LHS) >=
5804             (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
5805           // Build a plain add SCEV.
5806           const SCEV *S = getAddExpr(LHS, getSCEV(CI));
5807           // If the LHS of the add was an addrec and it has no-wrap flags,
5808           // transfer the no-wrap flags, since an or won't introduce a wrap.
5809           if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
5810             const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
5811             const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags(
5812                 OldAR->getNoWrapFlags());
5813           }
5814           return S;
5815         }
5816       }
5817       break;
5818 
5819     case Instruction::Xor:
5820       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5821         // If the RHS of xor is -1, then this is a not operation.
5822         if (CI->isMinusOne())
5823           return getNotSCEV(getSCEV(BO->LHS));
5824 
5825         // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
5826         // This is a variant of the check for xor with -1, and it handles
5827         // the case where instcombine has trimmed non-demanded bits out
5828         // of an xor with -1.
5829         if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
5830           if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
5831             if (LBO->getOpcode() == Instruction::And &&
5832                 LCI->getValue() == CI->getValue())
5833               if (const SCEVZeroExtendExpr *Z =
5834                       dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
5835                 Type *UTy = BO->LHS->getType();
5836                 const SCEV *Z0 = Z->getOperand();
5837                 Type *Z0Ty = Z0->getType();
5838                 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
5839 
5840                 // If C is a low-bits mask, the zero extend is serving to
5841                 // mask off the high bits. Complement the operand and
5842                 // re-apply the zext.
5843                 if (CI->getValue().isMask(Z0TySize))
5844                   return getZeroExtendExpr(getNotSCEV(Z0), UTy);
5845 
5846                 // If C is a single bit, it may be in the sign-bit position
5847                 // before the zero-extend. In this case, represent the xor
5848                 // using an add, which is equivalent, and re-apply the zext.
5849                 APInt Trunc = CI->getValue().trunc(Z0TySize);
5850                 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
5851                     Trunc.isSignMask())
5852                   return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
5853                                            UTy);
5854               }
5855       }
5856       break;
5857 
5858   case Instruction::Shl:
5859     // Turn shift left of a constant amount into a multiply.
5860     if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
5861       uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
5862 
5863       // If the shift count is not less than the bitwidth, the result of
5864       // the shift is undefined. Don't try to analyze it, because the
5865       // resolution chosen here may differ from the resolution chosen in
5866       // other parts of the compiler.
5867       if (SA->getValue().uge(BitWidth))
5868         break;
5869 
5870       // It is currently not resolved how to interpret NSW for left
5871       // shift by BitWidth - 1, so we avoid applying flags in that
5872       // case. Remove this check (or this comment) once the situation
5873       // is resolved. See
5874       // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html
5875       // and http://reviews.llvm.org/D8890 .
5876       auto Flags = SCEV::FlagAnyWrap;
5877       if (BO->Op && SA->getValue().ult(BitWidth - 1))
5878         Flags = getNoWrapFlagsFromUB(BO->Op);
5879 
5880       Constant *X = ConstantInt::get(getContext(),
5881         APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
5882       return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags);
5883     }
5884     break;
5885 
5886     case Instruction::AShr:
5887       // AShr X, C, where C is a constant.
5888       ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
5889       if (!CI)
5890         break;
5891 
5892       Type *OuterTy = BO->LHS->getType();
5893       uint64_t BitWidth = getTypeSizeInBits(OuterTy);
5894       // If the shift count is not less than the bitwidth, the result of
5895       // the shift is undefined. Don't try to analyze it, because the
5896       // resolution chosen here may differ from the resolution chosen in
5897       // other parts of the compiler.
5898       if (CI->getValue().uge(BitWidth))
5899         break;
5900 
5901       if (CI->isZero())
5902         return getSCEV(BO->LHS); // shift by zero --> noop
5903 
5904       uint64_t AShrAmt = CI->getZExtValue();
5905       Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
5906 
5907       Operator *L = dyn_cast<Operator>(BO->LHS);
5908       if (L && L->getOpcode() == Instruction::Shl) {
5909         // X = Shl A, n
5910         // Y = AShr X, m
5911         // Both n and m are constant.
5912 
5913         const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
5914         if (L->getOperand(1) == BO->RHS)
5915           // For a two-shift sext-inreg, i.e. n = m,
5916           // use sext(trunc(x)) as the SCEV expression.
5917           return getSignExtendExpr(
5918               getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy);
5919 
5920         ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
5921         if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) {
5922           uint64_t ShlAmt = ShlAmtCI->getZExtValue();
5923           if (ShlAmt > AShrAmt) {
5924             // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
5925             // expression. We already checked that ShlAmt < BitWidth, so
5926             // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
5927             // ShlAmt - AShrAmt < Amt.
5928             APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
5929                                             ShlAmt - AShrAmt);
5930             return getSignExtendExpr(
5931                 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy),
5932                 getConstant(Mul)), OuterTy);
5933           }
5934         }
5935       }
5936       break;
5937     }
5938   }
5939 
5940   switch (U->getOpcode()) {
5941   case Instruction::Trunc:
5942     return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
5943 
5944   case Instruction::ZExt:
5945     return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
5946 
5947   case Instruction::SExt:
5948     return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
5949 
5950   case Instruction::BitCast:
5951     // BitCasts are no-op casts so we just eliminate the cast.
5952     if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
5953       return getSCEV(U->getOperand(0));
5954     break;
5955 
5956   // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
5957   // lead to pointer expressions which cannot safely be expanded to GEPs,
5958   // because ScalarEvolution doesn't respect the GEP aliasing rules when
5959   // simplifying integer expressions.
5960 
5961   case Instruction::GetElementPtr:
5962     return createNodeForGEP(cast<GEPOperator>(U));
5963 
5964   case Instruction::PHI:
5965     return createNodeForPHI(cast<PHINode>(U));
5966 
5967   case Instruction::Select:
5968     // U can also be a select constant expr, which let fall through.  Since
5969     // createNodeForSelect only works for a condition that is an `ICmpInst`, and
5970     // constant expressions cannot have instructions as operands, we'd have
5971     // returned getUnknown for a select constant expressions anyway.
5972     if (isa<Instruction>(U))
5973       return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0),
5974                                       U->getOperand(1), U->getOperand(2));
5975     break;
5976 
5977   case Instruction::Call:
5978   case Instruction::Invoke:
5979     if (Value *RV = CallSite(U).getReturnedArgOperand())
5980       return getSCEV(RV);
5981     break;
5982   }
5983 
5984   return getUnknown(V);
5985 }
5986 
5987 
5988 
5989 //===----------------------------------------------------------------------===//
5990 //                   Iteration Count Computation Code
5991 //
5992 
5993 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
5994   if (!ExitCount)
5995     return 0;
5996 
5997   ConstantInt *ExitConst = ExitCount->getValue();
5998 
5999   // Guard against huge trip counts.
6000   if (ExitConst->getValue().getActiveBits() > 32)
6001     return 0;
6002 
6003   // In case of integer overflow, this returns 0, which is correct.
6004   return ((unsigned)ExitConst->getZExtValue()) + 1;
6005 }
6006 
6007 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) {
6008   if (BasicBlock *ExitingBB = L->getExitingBlock())
6009     return getSmallConstantTripCount(L, ExitingBB);
6010 
6011   // No trip count information for multiple exits.
6012   return 0;
6013 }
6014 
6015 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L,
6016                                                     BasicBlock *ExitingBlock) {
6017   assert(ExitingBlock && "Must pass a non-null exiting block!");
6018   assert(L->isLoopExiting(ExitingBlock) &&
6019          "Exiting block must actually branch out of the loop!");
6020   const SCEVConstant *ExitCount =
6021       dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
6022   return getConstantTripCount(ExitCount);
6023 }
6024 
6025 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) {
6026   const auto *MaxExitCount =
6027       dyn_cast<SCEVConstant>(getMaxBackedgeTakenCount(L));
6028   return getConstantTripCount(MaxExitCount);
6029 }
6030 
6031 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) {
6032   if (BasicBlock *ExitingBB = L->getExitingBlock())
6033     return getSmallConstantTripMultiple(L, ExitingBB);
6034 
6035   // No trip multiple information for multiple exits.
6036   return 0;
6037 }
6038 
6039 /// Returns the largest constant divisor of the trip count of this loop as a
6040 /// normal unsigned value, if possible. This means that the actual trip count is
6041 /// always a multiple of the returned value (don't forget the trip count could
6042 /// very well be zero as well!).
6043 ///
6044 /// Returns 1 if the trip count is unknown or not guaranteed to be the
6045 /// multiple of a constant (which is also the case if the trip count is simply
6046 /// constant, use getSmallConstantTripCount for that case), Will also return 1
6047 /// if the trip count is very large (>= 2^32).
6048 ///
6049 /// As explained in the comments for getSmallConstantTripCount, this assumes
6050 /// that control exits the loop via ExitingBlock.
6051 unsigned
6052 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
6053                                               BasicBlock *ExitingBlock) {
6054   assert(ExitingBlock && "Must pass a non-null exiting block!");
6055   assert(L->isLoopExiting(ExitingBlock) &&
6056          "Exiting block must actually branch out of the loop!");
6057   const SCEV *ExitCount = getExitCount(L, ExitingBlock);
6058   if (ExitCount == getCouldNotCompute())
6059     return 1;
6060 
6061   // Get the trip count from the BE count by adding 1.
6062   const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType()));
6063 
6064   const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr);
6065   if (!TC)
6066     // Attempt to factor more general cases. Returns the greatest power of
6067     // two divisor. If overflow happens, the trip count expression is still
6068     // divisible by the greatest power of 2 divisor returned.
6069     return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr));
6070 
6071   ConstantInt *Result = TC->getValue();
6072 
6073   // Guard against huge trip counts (this requires checking
6074   // for zero to handle the case where the trip count == -1 and the
6075   // addition wraps).
6076   if (!Result || Result->getValue().getActiveBits() > 32 ||
6077       Result->getValue().getActiveBits() == 0)
6078     return 1;
6079 
6080   return (unsigned)Result->getZExtValue();
6081 }
6082 
6083 /// Get the expression for the number of loop iterations for which this loop is
6084 /// guaranteed not to exit via ExitingBlock. Otherwise return
6085 /// SCEVCouldNotCompute.
6086 const SCEV *ScalarEvolution::getExitCount(const Loop *L,
6087                                           BasicBlock *ExitingBlock) {
6088   return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
6089 }
6090 
6091 const SCEV *
6092 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
6093                                                  SCEVUnionPredicate &Preds) {
6094   return getPredicatedBackedgeTakenInfo(L).getExact(this, &Preds);
6095 }
6096 
6097 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
6098   return getBackedgeTakenInfo(L).getExact(this);
6099 }
6100 
6101 /// Similar to getBackedgeTakenCount, except return the least SCEV value that is
6102 /// known never to be less than the actual backedge taken count.
6103 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
6104   return getBackedgeTakenInfo(L).getMax(this);
6105 }
6106 
6107 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) {
6108   return getBackedgeTakenInfo(L).isMaxOrZero(this);
6109 }
6110 
6111 /// Push PHI nodes in the header of the given loop onto the given Worklist.
6112 static void
6113 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
6114   BasicBlock *Header = L->getHeader();
6115 
6116   // Push all Loop-header PHIs onto the Worklist stack.
6117   for (BasicBlock::iterator I = Header->begin();
6118        PHINode *PN = dyn_cast<PHINode>(I); ++I)
6119     Worklist.push_back(PN);
6120 }
6121 
6122 const ScalarEvolution::BackedgeTakenInfo &
6123 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
6124   auto &BTI = getBackedgeTakenInfo(L);
6125   if (BTI.hasFullInfo())
6126     return BTI;
6127 
6128   auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
6129 
6130   if (!Pair.second)
6131     return Pair.first->second;
6132 
6133   BackedgeTakenInfo Result =
6134       computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
6135 
6136   return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
6137 }
6138 
6139 const ScalarEvolution::BackedgeTakenInfo &
6140 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
6141   // Initially insert an invalid entry for this loop. If the insertion
6142   // succeeds, proceed to actually compute a backedge-taken count and
6143   // update the value. The temporary CouldNotCompute value tells SCEV
6144   // code elsewhere that it shouldn't attempt to request a new
6145   // backedge-taken count, which could result in infinite recursion.
6146   std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
6147       BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
6148   if (!Pair.second)
6149     return Pair.first->second;
6150 
6151   // computeBackedgeTakenCount may allocate memory for its result. Inserting it
6152   // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
6153   // must be cleared in this scope.
6154   BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
6155 
6156   if (Result.getExact(this) != getCouldNotCompute()) {
6157     assert(isLoopInvariant(Result.getExact(this), L) &&
6158            isLoopInvariant(Result.getMax(this), L) &&
6159            "Computed backedge-taken count isn't loop invariant for loop!");
6160     ++NumTripCountsComputed;
6161   }
6162   else if (Result.getMax(this) == getCouldNotCompute() &&
6163            isa<PHINode>(L->getHeader()->begin())) {
6164     // Only count loops that have phi nodes as not being computable.
6165     ++NumTripCountsNotComputed;
6166   }
6167 
6168   // Now that we know more about the trip count for this loop, forget any
6169   // existing SCEV values for PHI nodes in this loop since they are only
6170   // conservative estimates made without the benefit of trip count
6171   // information. This is similar to the code in forgetLoop, except that
6172   // it handles SCEVUnknown PHI nodes specially.
6173   if (Result.hasAnyInfo()) {
6174     SmallVector<Instruction *, 16> Worklist;
6175     PushLoopPHIs(L, Worklist);
6176 
6177     SmallPtrSet<Instruction *, 8> Visited;
6178     while (!Worklist.empty()) {
6179       Instruction *I = Worklist.pop_back_val();
6180       if (!Visited.insert(I).second)
6181         continue;
6182 
6183       ValueExprMapType::iterator It =
6184         ValueExprMap.find_as(static_cast<Value *>(I));
6185       if (It != ValueExprMap.end()) {
6186         const SCEV *Old = It->second;
6187 
6188         // SCEVUnknown for a PHI either means that it has an unrecognized
6189         // structure, or it's a PHI that's in the progress of being computed
6190         // by createNodeForPHI.  In the former case, additional loop trip
6191         // count information isn't going to change anything. In the later
6192         // case, createNodeForPHI will perform the necessary updates on its
6193         // own when it gets to that point.
6194         if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
6195           eraseValueFromMap(It->first);
6196           forgetMemoizedResults(Old);
6197         }
6198         if (PHINode *PN = dyn_cast<PHINode>(I))
6199           ConstantEvolutionLoopExitValue.erase(PN);
6200       }
6201 
6202       PushDefUseChildren(I, Worklist);
6203     }
6204   }
6205 
6206   // Re-lookup the insert position, since the call to
6207   // computeBackedgeTakenCount above could result in a
6208   // recusive call to getBackedgeTakenInfo (on a different
6209   // loop), which would invalidate the iterator computed
6210   // earlier.
6211   return BackedgeTakenCounts.find(L)->second = std::move(Result);
6212 }
6213 
6214 void ScalarEvolution::forgetLoop(const Loop *L) {
6215   // Drop any stored trip count value.
6216   auto RemoveLoopFromBackedgeMap =
6217       [L](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
6218         auto BTCPos = Map.find(L);
6219         if (BTCPos != Map.end()) {
6220           BTCPos->second.clear();
6221           Map.erase(BTCPos);
6222         }
6223       };
6224 
6225   RemoveLoopFromBackedgeMap(BackedgeTakenCounts);
6226   RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts);
6227 
6228   // Drop information about predicated SCEV rewrites for this loop.
6229   for (auto I = PredicatedSCEVRewrites.begin();
6230        I != PredicatedSCEVRewrites.end();) {
6231     std::pair<const SCEV *, const Loop *> Entry = I->first;
6232     if (Entry.second == L)
6233       PredicatedSCEVRewrites.erase(I++);
6234     else
6235       ++I;
6236   }
6237 
6238   // Drop information about expressions based on loop-header PHIs.
6239   SmallVector<Instruction *, 16> Worklist;
6240   PushLoopPHIs(L, Worklist);
6241 
6242   SmallPtrSet<Instruction *, 8> Visited;
6243   while (!Worklist.empty()) {
6244     Instruction *I = Worklist.pop_back_val();
6245     if (!Visited.insert(I).second)
6246       continue;
6247 
6248     ValueExprMapType::iterator It =
6249       ValueExprMap.find_as(static_cast<Value *>(I));
6250     if (It != ValueExprMap.end()) {
6251       eraseValueFromMap(It->first);
6252       forgetMemoizedResults(It->second);
6253       if (PHINode *PN = dyn_cast<PHINode>(I))
6254         ConstantEvolutionLoopExitValue.erase(PN);
6255     }
6256 
6257     PushDefUseChildren(I, Worklist);
6258   }
6259 
6260   for (auto I = ExitLimits.begin(); I != ExitLimits.end();) {
6261     auto &Query = I->first;
6262     if (Query.L == L)
6263       ExitLimits.erase(I++);
6264     else
6265       ++I;
6266   }
6267 
6268   // Forget all contained loops too, to avoid dangling entries in the
6269   // ValuesAtScopes map.
6270   for (Loop *I : *L)
6271     forgetLoop(I);
6272 
6273   LoopPropertiesCache.erase(L);
6274 }
6275 
6276 void ScalarEvolution::forgetValue(Value *V) {
6277   Instruction *I = dyn_cast<Instruction>(V);
6278   if (!I) return;
6279 
6280   // Drop information about expressions based on loop-header PHIs.
6281   SmallVector<Instruction *, 16> Worklist;
6282   Worklist.push_back(I);
6283 
6284   SmallPtrSet<Instruction *, 8> Visited;
6285   while (!Worklist.empty()) {
6286     I = Worklist.pop_back_val();
6287     if (!Visited.insert(I).second)
6288       continue;
6289 
6290     ValueExprMapType::iterator It =
6291       ValueExprMap.find_as(static_cast<Value *>(I));
6292     if (It != ValueExprMap.end()) {
6293       eraseValueFromMap(It->first);
6294       forgetMemoizedResults(It->second);
6295       if (PHINode *PN = dyn_cast<PHINode>(I))
6296         ConstantEvolutionLoopExitValue.erase(PN);
6297     }
6298 
6299     PushDefUseChildren(I, Worklist);
6300   }
6301 }
6302 
6303 /// Get the exact loop backedge taken count considering all loop exits. A
6304 /// computable result can only be returned for loops with a single exit.
6305 /// Returning the minimum taken count among all exits is incorrect because one
6306 /// of the loop's exit limit's may have been skipped. howFarToZero assumes that
6307 /// the limit of each loop test is never skipped. This is a valid assumption as
6308 /// long as the loop exits via that test. For precise results, it is the
6309 /// caller's responsibility to specify the relevant loop exit using
6310 /// getExact(ExitingBlock, SE).
6311 const SCEV *
6312 ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE,
6313                                              SCEVUnionPredicate *Preds) const {
6314   // If any exits were not computable, the loop is not computable.
6315   if (!isComplete() || ExitNotTaken.empty())
6316     return SE->getCouldNotCompute();
6317 
6318   const SCEV *BECount = nullptr;
6319   for (auto &ENT : ExitNotTaken) {
6320     assert(ENT.ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV");
6321 
6322     if (!BECount)
6323       BECount = ENT.ExactNotTaken;
6324     else if (BECount != ENT.ExactNotTaken)
6325       return SE->getCouldNotCompute();
6326     if (Preds && !ENT.hasAlwaysTruePredicate())
6327       Preds->add(ENT.Predicate.get());
6328 
6329     assert((Preds || ENT.hasAlwaysTruePredicate()) &&
6330            "Predicate should be always true!");
6331   }
6332 
6333   assert(BECount && "Invalid not taken count for loop exit");
6334   return BECount;
6335 }
6336 
6337 /// Get the exact not taken count for this loop exit.
6338 const SCEV *
6339 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock,
6340                                              ScalarEvolution *SE) const {
6341   for (auto &ENT : ExitNotTaken)
6342     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
6343       return ENT.ExactNotTaken;
6344 
6345   return SE->getCouldNotCompute();
6346 }
6347 
6348 /// getMax - Get the max backedge taken count for the loop.
6349 const SCEV *
6350 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const {
6351   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
6352     return !ENT.hasAlwaysTruePredicate();
6353   };
6354 
6355   if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax())
6356     return SE->getCouldNotCompute();
6357 
6358   assert((isa<SCEVCouldNotCompute>(getMax()) || isa<SCEVConstant>(getMax())) &&
6359          "No point in having a non-constant max backedge taken count!");
6360   return getMax();
6361 }
6362 
6363 bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const {
6364   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
6365     return !ENT.hasAlwaysTruePredicate();
6366   };
6367   return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
6368 }
6369 
6370 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S,
6371                                                     ScalarEvolution *SE) const {
6372   if (getMax() && getMax() != SE->getCouldNotCompute() &&
6373       SE->hasOperand(getMax(), S))
6374     return true;
6375 
6376   for (auto &ENT : ExitNotTaken)
6377     if (ENT.ExactNotTaken != SE->getCouldNotCompute() &&
6378         SE->hasOperand(ENT.ExactNotTaken, S))
6379       return true;
6380 
6381   return false;
6382 }
6383 
6384 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E)
6385     : ExactNotTaken(E), MaxNotTaken(E), MaxOrZero(false) {
6386   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6387           isa<SCEVConstant>(MaxNotTaken)) &&
6388          "No point in having a non-constant max backedge taken count!");
6389 }
6390 
6391 ScalarEvolution::ExitLimit::ExitLimit(
6392     const SCEV *E, const SCEV *M, bool MaxOrZero,
6393     ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList)
6394     : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) {
6395   assert((isa<SCEVCouldNotCompute>(ExactNotTaken) ||
6396           !isa<SCEVCouldNotCompute>(MaxNotTaken)) &&
6397          "Exact is not allowed to be less precise than Max");
6398   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6399           isa<SCEVConstant>(MaxNotTaken)) &&
6400          "No point in having a non-constant max backedge taken count!");
6401   for (auto *PredSet : PredSetList)
6402     for (auto *P : *PredSet)
6403       addPredicate(P);
6404 }
6405 
6406 ScalarEvolution::ExitLimit::ExitLimit(
6407     const SCEV *E, const SCEV *M, bool MaxOrZero,
6408     const SmallPtrSetImpl<const SCEVPredicate *> &PredSet)
6409     : ExitLimit(E, M, MaxOrZero, {&PredSet}) {
6410   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6411           isa<SCEVConstant>(MaxNotTaken)) &&
6412          "No point in having a non-constant max backedge taken count!");
6413 }
6414 
6415 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M,
6416                                       bool MaxOrZero)
6417     : ExitLimit(E, M, MaxOrZero, None) {
6418   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6419           isa<SCEVConstant>(MaxNotTaken)) &&
6420          "No point in having a non-constant max backedge taken count!");
6421 }
6422 
6423 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
6424 /// computable exit into a persistent ExitNotTakenInfo array.
6425 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
6426     SmallVectorImpl<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo>
6427         &&ExitCounts,
6428     bool Complete, const SCEV *MaxCount, bool MaxOrZero)
6429     : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) {
6430   typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo;
6431   ExitNotTaken.reserve(ExitCounts.size());
6432   std::transform(
6433       ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken),
6434       [&](const EdgeExitInfo &EEI) {
6435         BasicBlock *ExitBB = EEI.first;
6436         const ExitLimit &EL = EEI.second;
6437         if (EL.Predicates.empty())
6438           return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr);
6439 
6440         std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate);
6441         for (auto *Pred : EL.Predicates)
6442           Predicate->add(Pred);
6443 
6444         return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, std::move(Predicate));
6445       });
6446   assert((isa<SCEVCouldNotCompute>(MaxCount) || isa<SCEVConstant>(MaxCount)) &&
6447          "No point in having a non-constant max backedge taken count!");
6448 }
6449 
6450 /// Invalidate this result and free the ExitNotTakenInfo array.
6451 void ScalarEvolution::BackedgeTakenInfo::clear() {
6452   ExitNotTaken.clear();
6453 }
6454 
6455 /// Compute the number of times the backedge of the specified loop will execute.
6456 ScalarEvolution::BackedgeTakenInfo
6457 ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
6458                                            bool AllowPredicates) {
6459   SmallVector<BasicBlock *, 8> ExitingBlocks;
6460   L->getExitingBlocks(ExitingBlocks);
6461 
6462   typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo;
6463 
6464   SmallVector<EdgeExitInfo, 4> ExitCounts;
6465   bool CouldComputeBECount = true;
6466   BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
6467   const SCEV *MustExitMaxBECount = nullptr;
6468   const SCEV *MayExitMaxBECount = nullptr;
6469   bool MustExitMaxOrZero = false;
6470 
6471   // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
6472   // and compute maxBECount.
6473   // Do a union of all the predicates here.
6474   for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
6475     BasicBlock *ExitBB = ExitingBlocks[i];
6476     ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
6477 
6478     assert((AllowPredicates || EL.Predicates.empty()) &&
6479            "Predicated exit limit when predicates are not allowed!");
6480 
6481     // 1. For each exit that can be computed, add an entry to ExitCounts.
6482     // CouldComputeBECount is true only if all exits can be computed.
6483     if (EL.ExactNotTaken == getCouldNotCompute())
6484       // We couldn't compute an exact value for this exit, so
6485       // we won't be able to compute an exact value for the loop.
6486       CouldComputeBECount = false;
6487     else
6488       ExitCounts.emplace_back(ExitBB, EL);
6489 
6490     // 2. Derive the loop's MaxBECount from each exit's max number of
6491     // non-exiting iterations. Partition the loop exits into two kinds:
6492     // LoopMustExits and LoopMayExits.
6493     //
6494     // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
6495     // is a LoopMayExit.  If any computable LoopMustExit is found, then
6496     // MaxBECount is the minimum EL.MaxNotTaken of computable
6497     // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
6498     // EL.MaxNotTaken, where CouldNotCompute is considered greater than any
6499     // computable EL.MaxNotTaken.
6500     if (EL.MaxNotTaken != getCouldNotCompute() && Latch &&
6501         DT.dominates(ExitBB, Latch)) {
6502       if (!MustExitMaxBECount) {
6503         MustExitMaxBECount = EL.MaxNotTaken;
6504         MustExitMaxOrZero = EL.MaxOrZero;
6505       } else {
6506         MustExitMaxBECount =
6507             getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken);
6508       }
6509     } else if (MayExitMaxBECount != getCouldNotCompute()) {
6510       if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute())
6511         MayExitMaxBECount = EL.MaxNotTaken;
6512       else {
6513         MayExitMaxBECount =
6514             getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken);
6515       }
6516     }
6517   }
6518   const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
6519     (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
6520   // The loop backedge will be taken the maximum or zero times if there's
6521   // a single exit that must be taken the maximum or zero times.
6522   bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
6523   return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
6524                            MaxBECount, MaxOrZero);
6525 }
6526 
6527 ScalarEvolution::ExitLimit
6528 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
6529                                   bool AllowPredicates) {
6530   ExitLimitQuery Query(L, ExitingBlock, AllowPredicates);
6531   auto MaybeEL = ExitLimits.find(Query);
6532   if (MaybeEL != ExitLimits.end())
6533     return MaybeEL->second;
6534   ExitLimit EL = computeExitLimitImpl(L, ExitingBlock, AllowPredicates);
6535   ExitLimits.insert({Query, EL});
6536   return EL;
6537 }
6538 
6539 ScalarEvolution::ExitLimit
6540 ScalarEvolution::computeExitLimitImpl(const Loop *L, BasicBlock *ExitingBlock,
6541                                       bool AllowPredicates) {
6542 
6543   // Okay, we've chosen an exiting block.  See what condition causes us to exit
6544   // at this block and remember the exit block and whether all other targets
6545   // lead to the loop header.
6546   bool MustExecuteLoopHeader = true;
6547   BasicBlock *Exit = nullptr;
6548   for (auto *SBB : successors(ExitingBlock))
6549     if (!L->contains(SBB)) {
6550       if (Exit) // Multiple exit successors.
6551         return getCouldNotCompute();
6552       Exit = SBB;
6553     } else if (SBB != L->getHeader()) {
6554       MustExecuteLoopHeader = false;
6555     }
6556 
6557   // At this point, we know we have a conditional branch that determines whether
6558   // the loop is exited.  However, we don't know if the branch is executed each
6559   // time through the loop.  If not, then the execution count of the branch will
6560   // not be equal to the trip count of the loop.
6561   //
6562   // Currently we check for this by checking to see if the Exit branch goes to
6563   // the loop header.  If so, we know it will always execute the same number of
6564   // times as the loop.  We also handle the case where the exit block *is* the
6565   // loop header.  This is common for un-rotated loops.
6566   //
6567   // If both of those tests fail, walk up the unique predecessor chain to the
6568   // header, stopping if there is an edge that doesn't exit the loop. If the
6569   // header is reached, the execution count of the branch will be equal to the
6570   // trip count of the loop.
6571   //
6572   //  More extensive analysis could be done to handle more cases here.
6573   //
6574   if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) {
6575     // The simple checks failed, try climbing the unique predecessor chain
6576     // up to the header.
6577     bool Ok = false;
6578     for (BasicBlock *BB = ExitingBlock; BB; ) {
6579       BasicBlock *Pred = BB->getUniquePredecessor();
6580       if (!Pred)
6581         return getCouldNotCompute();
6582       TerminatorInst *PredTerm = Pred->getTerminator();
6583       for (const BasicBlock *PredSucc : PredTerm->successors()) {
6584         if (PredSucc == BB)
6585           continue;
6586         // If the predecessor has a successor that isn't BB and isn't
6587         // outside the loop, assume the worst.
6588         if (L->contains(PredSucc))
6589           return getCouldNotCompute();
6590       }
6591       if (Pred == L->getHeader()) {
6592         Ok = true;
6593         break;
6594       }
6595       BB = Pred;
6596     }
6597     if (!Ok)
6598       return getCouldNotCompute();
6599   }
6600 
6601   bool IsOnlyExit = (L->getExitingBlock() != nullptr);
6602   TerminatorInst *Term = ExitingBlock->getTerminator();
6603   if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
6604     assert(BI->isConditional() && "If unconditional, it can't be in loop!");
6605     // Proceed to the next level to examine the exit condition expression.
6606     return computeExitLimitFromCond(
6607         L, BI->getCondition(), BI->getSuccessor(0), BI->getSuccessor(1),
6608         /*ControlsExit=*/IsOnlyExit, AllowPredicates);
6609   }
6610 
6611   if (SwitchInst *SI = dyn_cast<SwitchInst>(Term))
6612     return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
6613                                                 /*ControlsExit=*/IsOnlyExit);
6614 
6615   return getCouldNotCompute();
6616 }
6617 
6618 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond(
6619     const Loop *L, Value *ExitCond, BasicBlock *TBB, BasicBlock *FBB,
6620     bool ControlsExit, bool AllowPredicates) {
6621   ScalarEvolution::ExitLimitCacheTy Cache(L, TBB, FBB, AllowPredicates);
6622   return computeExitLimitFromCondCached(Cache, L, ExitCond, TBB, FBB,
6623                                         ControlsExit, AllowPredicates);
6624 }
6625 
6626 Optional<ScalarEvolution::ExitLimit>
6627 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
6628                                       BasicBlock *TBB, BasicBlock *FBB,
6629                                       bool ControlsExit, bool AllowPredicates) {
6630   (void)this->L;
6631   (void)this->TBB;
6632   (void)this->FBB;
6633   (void)this->AllowPredicates;
6634 
6635   assert(this->L == L && this->TBB == TBB && this->FBB == FBB &&
6636          this->AllowPredicates == AllowPredicates &&
6637          "Variance in assumed invariant key components!");
6638   auto Itr = TripCountMap.find({ExitCond, ControlsExit});
6639   if (Itr == TripCountMap.end())
6640     return None;
6641   return Itr->second;
6642 }
6643 
6644 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
6645                                              BasicBlock *TBB, BasicBlock *FBB,
6646                                              bool ControlsExit,
6647                                              bool AllowPredicates,
6648                                              const ExitLimit &EL) {
6649   assert(this->L == L && this->TBB == TBB && this->FBB == FBB &&
6650          this->AllowPredicates == AllowPredicates &&
6651          "Variance in assumed invariant key components!");
6652 
6653   auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL});
6654   assert(InsertResult.second && "Expected successful insertion!");
6655   (void)InsertResult;
6656 }
6657 
6658 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
6659     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, BasicBlock *TBB,
6660     BasicBlock *FBB, bool ControlsExit, bool AllowPredicates) {
6661 
6662   if (auto MaybeEL =
6663           Cache.find(L, ExitCond, TBB, FBB, ControlsExit, AllowPredicates))
6664     return *MaybeEL;
6665 
6666   ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, TBB, FBB,
6667                                               ControlsExit, AllowPredicates);
6668   Cache.insert(L, ExitCond, TBB, FBB, ControlsExit, AllowPredicates, EL);
6669   return EL;
6670 }
6671 
6672 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
6673     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, BasicBlock *TBB,
6674     BasicBlock *FBB, bool ControlsExit, bool AllowPredicates) {
6675   // Check if the controlling expression for this loop is an And or Or.
6676   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
6677     if (BO->getOpcode() == Instruction::And) {
6678       // Recurse on the operands of the and.
6679       bool EitherMayExit = L->contains(TBB);
6680       ExitLimit EL0 = computeExitLimitFromCondCached(
6681           Cache, L, BO->getOperand(0), TBB, FBB, ControlsExit && !EitherMayExit,
6682           AllowPredicates);
6683       ExitLimit EL1 = computeExitLimitFromCondCached(
6684           Cache, L, BO->getOperand(1), TBB, FBB, ControlsExit && !EitherMayExit,
6685           AllowPredicates);
6686       const SCEV *BECount = getCouldNotCompute();
6687       const SCEV *MaxBECount = getCouldNotCompute();
6688       if (EitherMayExit) {
6689         // Both conditions must be true for the loop to continue executing.
6690         // Choose the less conservative count.
6691         if (EL0.ExactNotTaken == getCouldNotCompute() ||
6692             EL1.ExactNotTaken == getCouldNotCompute())
6693           BECount = getCouldNotCompute();
6694         else
6695           BECount =
6696               getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
6697         if (EL0.MaxNotTaken == getCouldNotCompute())
6698           MaxBECount = EL1.MaxNotTaken;
6699         else if (EL1.MaxNotTaken == getCouldNotCompute())
6700           MaxBECount = EL0.MaxNotTaken;
6701         else
6702           MaxBECount =
6703               getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
6704       } else {
6705         // Both conditions must be true at the same time for the loop to exit.
6706         // For now, be conservative.
6707         assert(L->contains(FBB) && "Loop block has no successor in loop!");
6708         if (EL0.MaxNotTaken == EL1.MaxNotTaken)
6709           MaxBECount = EL0.MaxNotTaken;
6710         if (EL0.ExactNotTaken == EL1.ExactNotTaken)
6711           BECount = EL0.ExactNotTaken;
6712       }
6713 
6714       // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
6715       // to be more aggressive when computing BECount than when computing
6716       // MaxBECount.  In these cases it is possible for EL0.ExactNotTaken and
6717       // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
6718       // to not.
6719       if (isa<SCEVCouldNotCompute>(MaxBECount) &&
6720           !isa<SCEVCouldNotCompute>(BECount))
6721         MaxBECount = getConstant(getUnsignedRangeMax(BECount));
6722 
6723       return ExitLimit(BECount, MaxBECount, false,
6724                        {&EL0.Predicates, &EL1.Predicates});
6725     }
6726     if (BO->getOpcode() == Instruction::Or) {
6727       // Recurse on the operands of the or.
6728       bool EitherMayExit = L->contains(FBB);
6729       ExitLimit EL0 = computeExitLimitFromCondCached(
6730           Cache, L, BO->getOperand(0), TBB, FBB, ControlsExit && !EitherMayExit,
6731           AllowPredicates);
6732       ExitLimit EL1 = computeExitLimitFromCondCached(
6733           Cache, L, BO->getOperand(1), TBB, FBB, ControlsExit && !EitherMayExit,
6734           AllowPredicates);
6735       const SCEV *BECount = getCouldNotCompute();
6736       const SCEV *MaxBECount = getCouldNotCompute();
6737       if (EitherMayExit) {
6738         // Both conditions must be false for the loop to continue executing.
6739         // Choose the less conservative count.
6740         if (EL0.ExactNotTaken == getCouldNotCompute() ||
6741             EL1.ExactNotTaken == getCouldNotCompute())
6742           BECount = getCouldNotCompute();
6743         else
6744           BECount =
6745               getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
6746         if (EL0.MaxNotTaken == getCouldNotCompute())
6747           MaxBECount = EL1.MaxNotTaken;
6748         else if (EL1.MaxNotTaken == getCouldNotCompute())
6749           MaxBECount = EL0.MaxNotTaken;
6750         else
6751           MaxBECount =
6752               getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
6753       } else {
6754         // Both conditions must be false at the same time for the loop to exit.
6755         // For now, be conservative.
6756         assert(L->contains(TBB) && "Loop block has no successor in loop!");
6757         if (EL0.MaxNotTaken == EL1.MaxNotTaken)
6758           MaxBECount = EL0.MaxNotTaken;
6759         if (EL0.ExactNotTaken == EL1.ExactNotTaken)
6760           BECount = EL0.ExactNotTaken;
6761       }
6762 
6763       return ExitLimit(BECount, MaxBECount, false,
6764                        {&EL0.Predicates, &EL1.Predicates});
6765     }
6766   }
6767 
6768   // With an icmp, it may be feasible to compute an exact backedge-taken count.
6769   // Proceed to the next level to examine the icmp.
6770   if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
6771     ExitLimit EL =
6772         computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit);
6773     if (EL.hasFullInfo() || !AllowPredicates)
6774       return EL;
6775 
6776     // Try again, but use SCEV predicates this time.
6777     return computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit,
6778                                     /*AllowPredicates=*/true);
6779   }
6780 
6781   // Check for a constant condition. These are normally stripped out by
6782   // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
6783   // preserve the CFG and is temporarily leaving constant conditions
6784   // in place.
6785   if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
6786     if (L->contains(FBB) == !CI->getZExtValue())
6787       // The backedge is always taken.
6788       return getCouldNotCompute();
6789     else
6790       // The backedge is never taken.
6791       return getZero(CI->getType());
6792   }
6793 
6794   // If it's not an integer or pointer comparison then compute it the hard way.
6795   return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
6796 }
6797 
6798 ScalarEvolution::ExitLimit
6799 ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
6800                                           ICmpInst *ExitCond,
6801                                           BasicBlock *TBB,
6802                                           BasicBlock *FBB,
6803                                           bool ControlsExit,
6804                                           bool AllowPredicates) {
6805 
6806   // If the condition was exit on true, convert the condition to exit on false
6807   ICmpInst::Predicate Cond;
6808   if (!L->contains(FBB))
6809     Cond = ExitCond->getPredicate();
6810   else
6811     Cond = ExitCond->getInversePredicate();
6812 
6813   // Handle common loops like: for (X = "string"; *X; ++X)
6814   if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
6815     if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
6816       ExitLimit ItCnt =
6817         computeLoadConstantCompareExitLimit(LI, RHS, L, Cond);
6818       if (ItCnt.hasAnyInfo())
6819         return ItCnt;
6820     }
6821 
6822   const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
6823   const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
6824 
6825   // Try to evaluate any dependencies out of the loop.
6826   LHS = getSCEVAtScope(LHS, L);
6827   RHS = getSCEVAtScope(RHS, L);
6828 
6829   // At this point, we would like to compute how many iterations of the
6830   // loop the predicate will return true for these inputs.
6831   if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
6832     // If there is a loop-invariant, force it into the RHS.
6833     std::swap(LHS, RHS);
6834     Cond = ICmpInst::getSwappedPredicate(Cond);
6835   }
6836 
6837   // Simplify the operands before analyzing them.
6838   (void)SimplifyICmpOperands(Cond, LHS, RHS);
6839 
6840   // If we have a comparison of a chrec against a constant, try to use value
6841   // ranges to answer this query.
6842   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
6843     if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
6844       if (AddRec->getLoop() == L) {
6845         // Form the constant range.
6846         ConstantRange CompRange =
6847             ConstantRange::makeExactICmpRegion(Cond, RHSC->getAPInt());
6848 
6849         const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
6850         if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
6851       }
6852 
6853   switch (Cond) {
6854   case ICmpInst::ICMP_NE: {                     // while (X != Y)
6855     // Convert to: while (X-Y != 0)
6856     ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit,
6857                                 AllowPredicates);
6858     if (EL.hasAnyInfo()) return EL;
6859     break;
6860   }
6861   case ICmpInst::ICMP_EQ: {                     // while (X == Y)
6862     // Convert to: while (X-Y == 0)
6863     ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
6864     if (EL.hasAnyInfo()) return EL;
6865     break;
6866   }
6867   case ICmpInst::ICMP_SLT:
6868   case ICmpInst::ICMP_ULT: {                    // while (X < Y)
6869     bool IsSigned = Cond == ICmpInst::ICMP_SLT;
6870     ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit,
6871                                     AllowPredicates);
6872     if (EL.hasAnyInfo()) return EL;
6873     break;
6874   }
6875   case ICmpInst::ICMP_SGT:
6876   case ICmpInst::ICMP_UGT: {                    // while (X > Y)
6877     bool IsSigned = Cond == ICmpInst::ICMP_SGT;
6878     ExitLimit EL =
6879         howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
6880                             AllowPredicates);
6881     if (EL.hasAnyInfo()) return EL;
6882     break;
6883   }
6884   default:
6885     break;
6886   }
6887 
6888   auto *ExhaustiveCount =
6889       computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
6890 
6891   if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
6892     return ExhaustiveCount;
6893 
6894   return computeShiftCompareExitLimit(ExitCond->getOperand(0),
6895                                       ExitCond->getOperand(1), L, Cond);
6896 }
6897 
6898 ScalarEvolution::ExitLimit
6899 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
6900                                                       SwitchInst *Switch,
6901                                                       BasicBlock *ExitingBlock,
6902                                                       bool ControlsExit) {
6903   assert(!L->contains(ExitingBlock) && "Not an exiting block!");
6904 
6905   // Give up if the exit is the default dest of a switch.
6906   if (Switch->getDefaultDest() == ExitingBlock)
6907     return getCouldNotCompute();
6908 
6909   assert(L->contains(Switch->getDefaultDest()) &&
6910          "Default case must not exit the loop!");
6911   const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
6912   const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
6913 
6914   // while (X != Y) --> while (X-Y != 0)
6915   ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
6916   if (EL.hasAnyInfo())
6917     return EL;
6918 
6919   return getCouldNotCompute();
6920 }
6921 
6922 static ConstantInt *
6923 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
6924                                 ScalarEvolution &SE) {
6925   const SCEV *InVal = SE.getConstant(C);
6926   const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
6927   assert(isa<SCEVConstant>(Val) &&
6928          "Evaluation of SCEV at constant didn't fold correctly?");
6929   return cast<SCEVConstant>(Val)->getValue();
6930 }
6931 
6932 /// Given an exit condition of 'icmp op load X, cst', try to see if we can
6933 /// compute the backedge execution count.
6934 ScalarEvolution::ExitLimit
6935 ScalarEvolution::computeLoadConstantCompareExitLimit(
6936   LoadInst *LI,
6937   Constant *RHS,
6938   const Loop *L,
6939   ICmpInst::Predicate predicate) {
6940 
6941   if (LI->isVolatile()) return getCouldNotCompute();
6942 
6943   // Check to see if the loaded pointer is a getelementptr of a global.
6944   // TODO: Use SCEV instead of manually grubbing with GEPs.
6945   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
6946   if (!GEP) return getCouldNotCompute();
6947 
6948   // Make sure that it is really a constant global we are gepping, with an
6949   // initializer, and make sure the first IDX is really 0.
6950   GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
6951   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
6952       GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
6953       !cast<Constant>(GEP->getOperand(1))->isNullValue())
6954     return getCouldNotCompute();
6955 
6956   // Okay, we allow one non-constant index into the GEP instruction.
6957   Value *VarIdx = nullptr;
6958   std::vector<Constant*> Indexes;
6959   unsigned VarIdxNum = 0;
6960   for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
6961     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
6962       Indexes.push_back(CI);
6963     } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
6964       if (VarIdx) return getCouldNotCompute();  // Multiple non-constant idx's.
6965       VarIdx = GEP->getOperand(i);
6966       VarIdxNum = i-2;
6967       Indexes.push_back(nullptr);
6968     }
6969 
6970   // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
6971   if (!VarIdx)
6972     return getCouldNotCompute();
6973 
6974   // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
6975   // Check to see if X is a loop variant variable value now.
6976   const SCEV *Idx = getSCEV(VarIdx);
6977   Idx = getSCEVAtScope(Idx, L);
6978 
6979   // We can only recognize very limited forms of loop index expressions, in
6980   // particular, only affine AddRec's like {C1,+,C2}.
6981   const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
6982   if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
6983       !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
6984       !isa<SCEVConstant>(IdxExpr->getOperand(1)))
6985     return getCouldNotCompute();
6986 
6987   unsigned MaxSteps = MaxBruteForceIterations;
6988   for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
6989     ConstantInt *ItCst = ConstantInt::get(
6990                            cast<IntegerType>(IdxExpr->getType()), IterationNum);
6991     ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
6992 
6993     // Form the GEP offset.
6994     Indexes[VarIdxNum] = Val;
6995 
6996     Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
6997                                                          Indexes);
6998     if (!Result) break;  // Cannot compute!
6999 
7000     // Evaluate the condition for this iteration.
7001     Result = ConstantExpr::getICmp(predicate, Result, RHS);
7002     if (!isa<ConstantInt>(Result)) break;  // Couldn't decide for sure
7003     if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
7004       ++NumArrayLenItCounts;
7005       return getConstant(ItCst);   // Found terminating iteration!
7006     }
7007   }
7008   return getCouldNotCompute();
7009 }
7010 
7011 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
7012     Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
7013   ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
7014   if (!RHS)
7015     return getCouldNotCompute();
7016 
7017   const BasicBlock *Latch = L->getLoopLatch();
7018   if (!Latch)
7019     return getCouldNotCompute();
7020 
7021   const BasicBlock *Predecessor = L->getLoopPredecessor();
7022   if (!Predecessor)
7023     return getCouldNotCompute();
7024 
7025   // Return true if V is of the form "LHS `shift_op` <positive constant>".
7026   // Return LHS in OutLHS and shift_opt in OutOpCode.
7027   auto MatchPositiveShift =
7028       [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
7029 
7030     using namespace PatternMatch;
7031 
7032     ConstantInt *ShiftAmt;
7033     if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7034       OutOpCode = Instruction::LShr;
7035     else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7036       OutOpCode = Instruction::AShr;
7037     else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7038       OutOpCode = Instruction::Shl;
7039     else
7040       return false;
7041 
7042     return ShiftAmt->getValue().isStrictlyPositive();
7043   };
7044 
7045   // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
7046   //
7047   // loop:
7048   //   %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
7049   //   %iv.shifted = lshr i32 %iv, <positive constant>
7050   //
7051   // Return true on a successful match.  Return the corresponding PHI node (%iv
7052   // above) in PNOut and the opcode of the shift operation in OpCodeOut.
7053   auto MatchShiftRecurrence =
7054       [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
7055     Optional<Instruction::BinaryOps> PostShiftOpCode;
7056 
7057     {
7058       Instruction::BinaryOps OpC;
7059       Value *V;
7060 
7061       // If we encounter a shift instruction, "peel off" the shift operation,
7062       // and remember that we did so.  Later when we inspect %iv's backedge
7063       // value, we will make sure that the backedge value uses the same
7064       // operation.
7065       //
7066       // Note: the peeled shift operation does not have to be the same
7067       // instruction as the one feeding into the PHI's backedge value.  We only
7068       // really care about it being the same *kind* of shift instruction --
7069       // that's all that is required for our later inferences to hold.
7070       if (MatchPositiveShift(LHS, V, OpC)) {
7071         PostShiftOpCode = OpC;
7072         LHS = V;
7073       }
7074     }
7075 
7076     PNOut = dyn_cast<PHINode>(LHS);
7077     if (!PNOut || PNOut->getParent() != L->getHeader())
7078       return false;
7079 
7080     Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
7081     Value *OpLHS;
7082 
7083     return
7084         // The backedge value for the PHI node must be a shift by a positive
7085         // amount
7086         MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
7087 
7088         // of the PHI node itself
7089         OpLHS == PNOut &&
7090 
7091         // and the kind of shift should be match the kind of shift we peeled
7092         // off, if any.
7093         (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut);
7094   };
7095 
7096   PHINode *PN;
7097   Instruction::BinaryOps OpCode;
7098   if (!MatchShiftRecurrence(LHS, PN, OpCode))
7099     return getCouldNotCompute();
7100 
7101   const DataLayout &DL = getDataLayout();
7102 
7103   // The key rationale for this optimization is that for some kinds of shift
7104   // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
7105   // within a finite number of iterations.  If the condition guarding the
7106   // backedge (in the sense that the backedge is taken if the condition is true)
7107   // is false for the value the shift recurrence stabilizes to, then we know
7108   // that the backedge is taken only a finite number of times.
7109 
7110   ConstantInt *StableValue = nullptr;
7111   switch (OpCode) {
7112   default:
7113     llvm_unreachable("Impossible case!");
7114 
7115   case Instruction::AShr: {
7116     // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
7117     // bitwidth(K) iterations.
7118     Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
7119     KnownBits Known = computeKnownBits(FirstValue, DL, 0, nullptr,
7120                                        Predecessor->getTerminator(), &DT);
7121     auto *Ty = cast<IntegerType>(RHS->getType());
7122     if (Known.isNonNegative())
7123       StableValue = ConstantInt::get(Ty, 0);
7124     else if (Known.isNegative())
7125       StableValue = ConstantInt::get(Ty, -1, true);
7126     else
7127       return getCouldNotCompute();
7128 
7129     break;
7130   }
7131   case Instruction::LShr:
7132   case Instruction::Shl:
7133     // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
7134     // stabilize to 0 in at most bitwidth(K) iterations.
7135     StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
7136     break;
7137   }
7138 
7139   auto *Result =
7140       ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
7141   assert(Result->getType()->isIntegerTy(1) &&
7142          "Otherwise cannot be an operand to a branch instruction");
7143 
7144   if (Result->isZeroValue()) {
7145     unsigned BitWidth = getTypeSizeInBits(RHS->getType());
7146     const SCEV *UpperBound =
7147         getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
7148     return ExitLimit(getCouldNotCompute(), UpperBound, false);
7149   }
7150 
7151   return getCouldNotCompute();
7152 }
7153 
7154 /// Return true if we can constant fold an instruction of the specified type,
7155 /// assuming that all operands were constants.
7156 static bool CanConstantFold(const Instruction *I) {
7157   if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
7158       isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
7159       isa<LoadInst>(I))
7160     return true;
7161 
7162   if (const CallInst *CI = dyn_cast<CallInst>(I))
7163     if (const Function *F = CI->getCalledFunction())
7164       return canConstantFoldCallTo(CI, F);
7165   return false;
7166 }
7167 
7168 /// Determine whether this instruction can constant evolve within this loop
7169 /// assuming its operands can all constant evolve.
7170 static bool canConstantEvolve(Instruction *I, const Loop *L) {
7171   // An instruction outside of the loop can't be derived from a loop PHI.
7172   if (!L->contains(I)) return false;
7173 
7174   if (isa<PHINode>(I)) {
7175     // We don't currently keep track of the control flow needed to evaluate
7176     // PHIs, so we cannot handle PHIs inside of loops.
7177     return L->getHeader() == I->getParent();
7178   }
7179 
7180   // If we won't be able to constant fold this expression even if the operands
7181   // are constants, bail early.
7182   return CanConstantFold(I);
7183 }
7184 
7185 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
7186 /// recursing through each instruction operand until reaching a loop header phi.
7187 static PHINode *
7188 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
7189                                DenseMap<Instruction *, PHINode *> &PHIMap,
7190                                unsigned Depth) {
7191   if (Depth > MaxConstantEvolvingDepth)
7192     return nullptr;
7193 
7194   // Otherwise, we can evaluate this instruction if all of its operands are
7195   // constant or derived from a PHI node themselves.
7196   PHINode *PHI = nullptr;
7197   for (Value *Op : UseInst->operands()) {
7198     if (isa<Constant>(Op)) continue;
7199 
7200     Instruction *OpInst = dyn_cast<Instruction>(Op);
7201     if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
7202 
7203     PHINode *P = dyn_cast<PHINode>(OpInst);
7204     if (!P)
7205       // If this operand is already visited, reuse the prior result.
7206       // We may have P != PHI if this is the deepest point at which the
7207       // inconsistent paths meet.
7208       P = PHIMap.lookup(OpInst);
7209     if (!P) {
7210       // Recurse and memoize the results, whether a phi is found or not.
7211       // This recursive call invalidates pointers into PHIMap.
7212       P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1);
7213       PHIMap[OpInst] = P;
7214     }
7215     if (!P)
7216       return nullptr;  // Not evolving from PHI
7217     if (PHI && PHI != P)
7218       return nullptr;  // Evolving from multiple different PHIs.
7219     PHI = P;
7220   }
7221   // This is a expression evolving from a constant PHI!
7222   return PHI;
7223 }
7224 
7225 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
7226 /// in the loop that V is derived from.  We allow arbitrary operations along the
7227 /// way, but the operands of an operation must either be constants or a value
7228 /// derived from a constant PHI.  If this expression does not fit with these
7229 /// constraints, return null.
7230 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
7231   Instruction *I = dyn_cast<Instruction>(V);
7232   if (!I || !canConstantEvolve(I, L)) return nullptr;
7233 
7234   if (PHINode *PN = dyn_cast<PHINode>(I))
7235     return PN;
7236 
7237   // Record non-constant instructions contained by the loop.
7238   DenseMap<Instruction *, PHINode *> PHIMap;
7239   return getConstantEvolvingPHIOperands(I, L, PHIMap, 0);
7240 }
7241 
7242 /// EvaluateExpression - Given an expression that passes the
7243 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
7244 /// in the loop has the value PHIVal.  If we can't fold this expression for some
7245 /// reason, return null.
7246 static Constant *EvaluateExpression(Value *V, const Loop *L,
7247                                     DenseMap<Instruction *, Constant *> &Vals,
7248                                     const DataLayout &DL,
7249                                     const TargetLibraryInfo *TLI) {
7250   // Convenient constant check, but redundant for recursive calls.
7251   if (Constant *C = dyn_cast<Constant>(V)) return C;
7252   Instruction *I = dyn_cast<Instruction>(V);
7253   if (!I) return nullptr;
7254 
7255   if (Constant *C = Vals.lookup(I)) return C;
7256 
7257   // An instruction inside the loop depends on a value outside the loop that we
7258   // weren't given a mapping for, or a value such as a call inside the loop.
7259   if (!canConstantEvolve(I, L)) return nullptr;
7260 
7261   // An unmapped PHI can be due to a branch or another loop inside this loop,
7262   // or due to this not being the initial iteration through a loop where we
7263   // couldn't compute the evolution of this particular PHI last time.
7264   if (isa<PHINode>(I)) return nullptr;
7265 
7266   std::vector<Constant*> Operands(I->getNumOperands());
7267 
7268   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
7269     Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
7270     if (!Operand) {
7271       Operands[i] = dyn_cast<Constant>(I->getOperand(i));
7272       if (!Operands[i]) return nullptr;
7273       continue;
7274     }
7275     Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
7276     Vals[Operand] = C;
7277     if (!C) return nullptr;
7278     Operands[i] = C;
7279   }
7280 
7281   if (CmpInst *CI = dyn_cast<CmpInst>(I))
7282     return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
7283                                            Operands[1], DL, TLI);
7284   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
7285     if (!LI->isVolatile())
7286       return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
7287   }
7288   return ConstantFoldInstOperands(I, Operands, DL, TLI);
7289 }
7290 
7291 
7292 // If every incoming value to PN except the one for BB is a specific Constant,
7293 // return that, else return nullptr.
7294 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
7295   Constant *IncomingVal = nullptr;
7296 
7297   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
7298     if (PN->getIncomingBlock(i) == BB)
7299       continue;
7300 
7301     auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
7302     if (!CurrentVal)
7303       return nullptr;
7304 
7305     if (IncomingVal != CurrentVal) {
7306       if (IncomingVal)
7307         return nullptr;
7308       IncomingVal = CurrentVal;
7309     }
7310   }
7311 
7312   return IncomingVal;
7313 }
7314 
7315 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
7316 /// in the header of its containing loop, we know the loop executes a
7317 /// constant number of times, and the PHI node is just a recurrence
7318 /// involving constants, fold it.
7319 Constant *
7320 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
7321                                                    const APInt &BEs,
7322                                                    const Loop *L) {
7323   auto I = ConstantEvolutionLoopExitValue.find(PN);
7324   if (I != ConstantEvolutionLoopExitValue.end())
7325     return I->second;
7326 
7327   if (BEs.ugt(MaxBruteForceIterations))
7328     return ConstantEvolutionLoopExitValue[PN] = nullptr;  // Not going to evaluate it.
7329 
7330   Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
7331 
7332   DenseMap<Instruction *, Constant *> CurrentIterVals;
7333   BasicBlock *Header = L->getHeader();
7334   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
7335 
7336   BasicBlock *Latch = L->getLoopLatch();
7337   if (!Latch)
7338     return nullptr;
7339 
7340   for (auto &I : *Header) {
7341     PHINode *PHI = dyn_cast<PHINode>(&I);
7342     if (!PHI) break;
7343     auto *StartCST = getOtherIncomingValue(PHI, Latch);
7344     if (!StartCST) continue;
7345     CurrentIterVals[PHI] = StartCST;
7346   }
7347   if (!CurrentIterVals.count(PN))
7348     return RetVal = nullptr;
7349 
7350   Value *BEValue = PN->getIncomingValueForBlock(Latch);
7351 
7352   // Execute the loop symbolically to determine the exit value.
7353   if (BEs.getActiveBits() >= 32)
7354     return RetVal = nullptr; // More than 2^32-1 iterations?? Not doing it!
7355 
7356   unsigned NumIterations = BEs.getZExtValue(); // must be in range
7357   unsigned IterationNum = 0;
7358   const DataLayout &DL = getDataLayout();
7359   for (; ; ++IterationNum) {
7360     if (IterationNum == NumIterations)
7361       return RetVal = CurrentIterVals[PN];  // Got exit value!
7362 
7363     // Compute the value of the PHIs for the next iteration.
7364     // EvaluateExpression adds non-phi values to the CurrentIterVals map.
7365     DenseMap<Instruction *, Constant *> NextIterVals;
7366     Constant *NextPHI =
7367         EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
7368     if (!NextPHI)
7369       return nullptr;        // Couldn't evaluate!
7370     NextIterVals[PN] = NextPHI;
7371 
7372     bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
7373 
7374     // Also evaluate the other PHI nodes.  However, we don't get to stop if we
7375     // cease to be able to evaluate one of them or if they stop evolving,
7376     // because that doesn't necessarily prevent us from computing PN.
7377     SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
7378     for (const auto &I : CurrentIterVals) {
7379       PHINode *PHI = dyn_cast<PHINode>(I.first);
7380       if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
7381       PHIsToCompute.emplace_back(PHI, I.second);
7382     }
7383     // We use two distinct loops because EvaluateExpression may invalidate any
7384     // iterators into CurrentIterVals.
7385     for (const auto &I : PHIsToCompute) {
7386       PHINode *PHI = I.first;
7387       Constant *&NextPHI = NextIterVals[PHI];
7388       if (!NextPHI) {   // Not already computed.
7389         Value *BEValue = PHI->getIncomingValueForBlock(Latch);
7390         NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
7391       }
7392       if (NextPHI != I.second)
7393         StoppedEvolving = false;
7394     }
7395 
7396     // If all entries in CurrentIterVals == NextIterVals then we can stop
7397     // iterating, the loop can't continue to change.
7398     if (StoppedEvolving)
7399       return RetVal = CurrentIterVals[PN];
7400 
7401     CurrentIterVals.swap(NextIterVals);
7402   }
7403 }
7404 
7405 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
7406                                                           Value *Cond,
7407                                                           bool ExitWhen) {
7408   PHINode *PN = getConstantEvolvingPHI(Cond, L);
7409   if (!PN) return getCouldNotCompute();
7410 
7411   // If the loop is canonicalized, the PHI will have exactly two entries.
7412   // That's the only form we support here.
7413   if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
7414 
7415   DenseMap<Instruction *, Constant *> CurrentIterVals;
7416   BasicBlock *Header = L->getHeader();
7417   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
7418 
7419   BasicBlock *Latch = L->getLoopLatch();
7420   assert(Latch && "Should follow from NumIncomingValues == 2!");
7421 
7422   for (auto &I : *Header) {
7423     PHINode *PHI = dyn_cast<PHINode>(&I);
7424     if (!PHI)
7425       break;
7426     auto *StartCST = getOtherIncomingValue(PHI, Latch);
7427     if (!StartCST) continue;
7428     CurrentIterVals[PHI] = StartCST;
7429   }
7430   if (!CurrentIterVals.count(PN))
7431     return getCouldNotCompute();
7432 
7433   // Okay, we find a PHI node that defines the trip count of this loop.  Execute
7434   // the loop symbolically to determine when the condition gets a value of
7435   // "ExitWhen".
7436   unsigned MaxIterations = MaxBruteForceIterations;   // Limit analysis.
7437   const DataLayout &DL = getDataLayout();
7438   for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
7439     auto *CondVal = dyn_cast_or_null<ConstantInt>(
7440         EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
7441 
7442     // Couldn't symbolically evaluate.
7443     if (!CondVal) return getCouldNotCompute();
7444 
7445     if (CondVal->getValue() == uint64_t(ExitWhen)) {
7446       ++NumBruteForceTripCountsComputed;
7447       return getConstant(Type::getInt32Ty(getContext()), IterationNum);
7448     }
7449 
7450     // Update all the PHI nodes for the next iteration.
7451     DenseMap<Instruction *, Constant *> NextIterVals;
7452 
7453     // Create a list of which PHIs we need to compute. We want to do this before
7454     // calling EvaluateExpression on them because that may invalidate iterators
7455     // into CurrentIterVals.
7456     SmallVector<PHINode *, 8> PHIsToCompute;
7457     for (const auto &I : CurrentIterVals) {
7458       PHINode *PHI = dyn_cast<PHINode>(I.first);
7459       if (!PHI || PHI->getParent() != Header) continue;
7460       PHIsToCompute.push_back(PHI);
7461     }
7462     for (PHINode *PHI : PHIsToCompute) {
7463       Constant *&NextPHI = NextIterVals[PHI];
7464       if (NextPHI) continue;    // Already computed!
7465 
7466       Value *BEValue = PHI->getIncomingValueForBlock(Latch);
7467       NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
7468     }
7469     CurrentIterVals.swap(NextIterVals);
7470   }
7471 
7472   // Too many iterations were needed to evaluate.
7473   return getCouldNotCompute();
7474 }
7475 
7476 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
7477   SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
7478       ValuesAtScopes[V];
7479   // Check to see if we've folded this expression at this loop before.
7480   for (auto &LS : Values)
7481     if (LS.first == L)
7482       return LS.second ? LS.second : V;
7483 
7484   Values.emplace_back(L, nullptr);
7485 
7486   // Otherwise compute it.
7487   const SCEV *C = computeSCEVAtScope(V, L);
7488   for (auto &LS : reverse(ValuesAtScopes[V]))
7489     if (LS.first == L) {
7490       LS.second = C;
7491       break;
7492     }
7493   return C;
7494 }
7495 
7496 /// This builds up a Constant using the ConstantExpr interface.  That way, we
7497 /// will return Constants for objects which aren't represented by a
7498 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
7499 /// Returns NULL if the SCEV isn't representable as a Constant.
7500 static Constant *BuildConstantFromSCEV(const SCEV *V) {
7501   switch (static_cast<SCEVTypes>(V->getSCEVType())) {
7502     case scCouldNotCompute:
7503     case scAddRecExpr:
7504       break;
7505     case scConstant:
7506       return cast<SCEVConstant>(V)->getValue();
7507     case scUnknown:
7508       return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
7509     case scSignExtend: {
7510       const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
7511       if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
7512         return ConstantExpr::getSExt(CastOp, SS->getType());
7513       break;
7514     }
7515     case scZeroExtend: {
7516       const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
7517       if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
7518         return ConstantExpr::getZExt(CastOp, SZ->getType());
7519       break;
7520     }
7521     case scTruncate: {
7522       const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
7523       if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
7524         return ConstantExpr::getTrunc(CastOp, ST->getType());
7525       break;
7526     }
7527     case scAddExpr: {
7528       const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
7529       if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
7530         if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
7531           unsigned AS = PTy->getAddressSpace();
7532           Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
7533           C = ConstantExpr::getBitCast(C, DestPtrTy);
7534         }
7535         for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
7536           Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
7537           if (!C2) return nullptr;
7538 
7539           // First pointer!
7540           if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
7541             unsigned AS = C2->getType()->getPointerAddressSpace();
7542             std::swap(C, C2);
7543             Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
7544             // The offsets have been converted to bytes.  We can add bytes to an
7545             // i8* by GEP with the byte count in the first index.
7546             C = ConstantExpr::getBitCast(C, DestPtrTy);
7547           }
7548 
7549           // Don't bother trying to sum two pointers. We probably can't
7550           // statically compute a load that results from it anyway.
7551           if (C2->getType()->isPointerTy())
7552             return nullptr;
7553 
7554           if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
7555             if (PTy->getElementType()->isStructTy())
7556               C2 = ConstantExpr::getIntegerCast(
7557                   C2, Type::getInt32Ty(C->getContext()), true);
7558             C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2);
7559           } else
7560             C = ConstantExpr::getAdd(C, C2);
7561         }
7562         return C;
7563       }
7564       break;
7565     }
7566     case scMulExpr: {
7567       const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
7568       if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
7569         // Don't bother with pointers at all.
7570         if (C->getType()->isPointerTy()) return nullptr;
7571         for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
7572           Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
7573           if (!C2 || C2->getType()->isPointerTy()) return nullptr;
7574           C = ConstantExpr::getMul(C, C2);
7575         }
7576         return C;
7577       }
7578       break;
7579     }
7580     case scUDivExpr: {
7581       const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
7582       if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
7583         if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
7584           if (LHS->getType() == RHS->getType())
7585             return ConstantExpr::getUDiv(LHS, RHS);
7586       break;
7587     }
7588     case scSMaxExpr:
7589     case scUMaxExpr:
7590       break; // TODO: smax, umax.
7591   }
7592   return nullptr;
7593 }
7594 
7595 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
7596   if (isa<SCEVConstant>(V)) return V;
7597 
7598   // If this instruction is evolved from a constant-evolving PHI, compute the
7599   // exit value from the loop without using SCEVs.
7600   if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
7601     if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
7602       const Loop *LI = this->LI[I->getParent()];
7603       if (LI && LI->getParentLoop() == L)  // Looking for loop exit value.
7604         if (PHINode *PN = dyn_cast<PHINode>(I))
7605           if (PN->getParent() == LI->getHeader()) {
7606             // Okay, there is no closed form solution for the PHI node.  Check
7607             // to see if the loop that contains it has a known backedge-taken
7608             // count.  If so, we may be able to force computation of the exit
7609             // value.
7610             const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
7611             if (const SCEVConstant *BTCC =
7612                   dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
7613               // Okay, we know how many times the containing loop executes.  If
7614               // this is a constant evolving PHI node, get the final value at
7615               // the specified iteration number.
7616               Constant *RV =
7617                   getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI);
7618               if (RV) return getSCEV(RV);
7619             }
7620           }
7621 
7622       // Okay, this is an expression that we cannot symbolically evaluate
7623       // into a SCEV.  Check to see if it's possible to symbolically evaluate
7624       // the arguments into constants, and if so, try to constant propagate the
7625       // result.  This is particularly useful for computing loop exit values.
7626       if (CanConstantFold(I)) {
7627         SmallVector<Constant *, 4> Operands;
7628         bool MadeImprovement = false;
7629         for (Value *Op : I->operands()) {
7630           if (Constant *C = dyn_cast<Constant>(Op)) {
7631             Operands.push_back(C);
7632             continue;
7633           }
7634 
7635           // If any of the operands is non-constant and if they are
7636           // non-integer and non-pointer, don't even try to analyze them
7637           // with scev techniques.
7638           if (!isSCEVable(Op->getType()))
7639             return V;
7640 
7641           const SCEV *OrigV = getSCEV(Op);
7642           const SCEV *OpV = getSCEVAtScope(OrigV, L);
7643           MadeImprovement |= OrigV != OpV;
7644 
7645           Constant *C = BuildConstantFromSCEV(OpV);
7646           if (!C) return V;
7647           if (C->getType() != Op->getType())
7648             C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
7649                                                               Op->getType(),
7650                                                               false),
7651                                       C, Op->getType());
7652           Operands.push_back(C);
7653         }
7654 
7655         // Check to see if getSCEVAtScope actually made an improvement.
7656         if (MadeImprovement) {
7657           Constant *C = nullptr;
7658           const DataLayout &DL = getDataLayout();
7659           if (const CmpInst *CI = dyn_cast<CmpInst>(I))
7660             C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
7661                                                 Operands[1], DL, &TLI);
7662           else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
7663             if (!LI->isVolatile())
7664               C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
7665           } else
7666             C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
7667           if (!C) return V;
7668           return getSCEV(C);
7669         }
7670       }
7671     }
7672 
7673     // This is some other type of SCEVUnknown, just return it.
7674     return V;
7675   }
7676 
7677   if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
7678     // Avoid performing the look-up in the common case where the specified
7679     // expression has no loop-variant portions.
7680     for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
7681       const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
7682       if (OpAtScope != Comm->getOperand(i)) {
7683         // Okay, at least one of these operands is loop variant but might be
7684         // foldable.  Build a new instance of the folded commutative expression.
7685         SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
7686                                             Comm->op_begin()+i);
7687         NewOps.push_back(OpAtScope);
7688 
7689         for (++i; i != e; ++i) {
7690           OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
7691           NewOps.push_back(OpAtScope);
7692         }
7693         if (isa<SCEVAddExpr>(Comm))
7694           return getAddExpr(NewOps);
7695         if (isa<SCEVMulExpr>(Comm))
7696           return getMulExpr(NewOps);
7697         if (isa<SCEVSMaxExpr>(Comm))
7698           return getSMaxExpr(NewOps);
7699         if (isa<SCEVUMaxExpr>(Comm))
7700           return getUMaxExpr(NewOps);
7701         llvm_unreachable("Unknown commutative SCEV type!");
7702       }
7703     }
7704     // If we got here, all operands are loop invariant.
7705     return Comm;
7706   }
7707 
7708   if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
7709     const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
7710     const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
7711     if (LHS == Div->getLHS() && RHS == Div->getRHS())
7712       return Div;   // must be loop invariant
7713     return getUDivExpr(LHS, RHS);
7714   }
7715 
7716   // If this is a loop recurrence for a loop that does not contain L, then we
7717   // are dealing with the final value computed by the loop.
7718   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
7719     // First, attempt to evaluate each operand.
7720     // Avoid performing the look-up in the common case where the specified
7721     // expression has no loop-variant portions.
7722     for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
7723       const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
7724       if (OpAtScope == AddRec->getOperand(i))
7725         continue;
7726 
7727       // Okay, at least one of these operands is loop variant but might be
7728       // foldable.  Build a new instance of the folded commutative expression.
7729       SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
7730                                           AddRec->op_begin()+i);
7731       NewOps.push_back(OpAtScope);
7732       for (++i; i != e; ++i)
7733         NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
7734 
7735       const SCEV *FoldedRec =
7736         getAddRecExpr(NewOps, AddRec->getLoop(),
7737                       AddRec->getNoWrapFlags(SCEV::FlagNW));
7738       AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
7739       // The addrec may be folded to a nonrecurrence, for example, if the
7740       // induction variable is multiplied by zero after constant folding. Go
7741       // ahead and return the folded value.
7742       if (!AddRec)
7743         return FoldedRec;
7744       break;
7745     }
7746 
7747     // If the scope is outside the addrec's loop, evaluate it by using the
7748     // loop exit value of the addrec.
7749     if (!AddRec->getLoop()->contains(L)) {
7750       // To evaluate this recurrence, we need to know how many times the AddRec
7751       // loop iterates.  Compute this now.
7752       const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
7753       if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
7754 
7755       // Then, evaluate the AddRec.
7756       return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
7757     }
7758 
7759     return AddRec;
7760   }
7761 
7762   if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
7763     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
7764     if (Op == Cast->getOperand())
7765       return Cast;  // must be loop invariant
7766     return getZeroExtendExpr(Op, Cast->getType());
7767   }
7768 
7769   if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
7770     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
7771     if (Op == Cast->getOperand())
7772       return Cast;  // must be loop invariant
7773     return getSignExtendExpr(Op, Cast->getType());
7774   }
7775 
7776   if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
7777     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
7778     if (Op == Cast->getOperand())
7779       return Cast;  // must be loop invariant
7780     return getTruncateExpr(Op, Cast->getType());
7781   }
7782 
7783   llvm_unreachable("Unknown SCEV type!");
7784 }
7785 
7786 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
7787   return getSCEVAtScope(getSCEV(V), L);
7788 }
7789 
7790 /// Finds the minimum unsigned root of the following equation:
7791 ///
7792 ///     A * X = B (mod N)
7793 ///
7794 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
7795 /// A and B isn't important.
7796 ///
7797 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
7798 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B,
7799                                                ScalarEvolution &SE) {
7800   uint32_t BW = A.getBitWidth();
7801   assert(BW == SE.getTypeSizeInBits(B->getType()));
7802   assert(A != 0 && "A must be non-zero.");
7803 
7804   // 1. D = gcd(A, N)
7805   //
7806   // The gcd of A and N may have only one prime factor: 2. The number of
7807   // trailing zeros in A is its multiplicity
7808   uint32_t Mult2 = A.countTrailingZeros();
7809   // D = 2^Mult2
7810 
7811   // 2. Check if B is divisible by D.
7812   //
7813   // B is divisible by D if and only if the multiplicity of prime factor 2 for B
7814   // is not less than multiplicity of this prime factor for D.
7815   if (SE.GetMinTrailingZeros(B) < Mult2)
7816     return SE.getCouldNotCompute();
7817 
7818   // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
7819   // modulo (N / D).
7820   //
7821   // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
7822   // (N / D) in general. The inverse itself always fits into BW bits, though,
7823   // so we immediately truncate it.
7824   APInt AD = A.lshr(Mult2).zext(BW + 1);  // AD = A / D
7825   APInt Mod(BW + 1, 0);
7826   Mod.setBit(BW - Mult2);  // Mod = N / D
7827   APInt I = AD.multiplicativeInverse(Mod).trunc(BW);
7828 
7829   // 4. Compute the minimum unsigned root of the equation:
7830   // I * (B / D) mod (N / D)
7831   // To simplify the computation, we factor out the divide by D:
7832   // (I * B mod N) / D
7833   const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
7834   return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
7835 }
7836 
7837 /// Find the roots of the quadratic equation for the given quadratic chrec
7838 /// {L,+,M,+,N}.  This returns either the two roots (which might be the same) or
7839 /// two SCEVCouldNotCompute objects.
7840 ///
7841 static Optional<std::pair<const SCEVConstant *,const SCEVConstant *>>
7842 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
7843   assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
7844   const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
7845   const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
7846   const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
7847 
7848   // We currently can only solve this if the coefficients are constants.
7849   if (!LC || !MC || !NC)
7850     return None;
7851 
7852   uint32_t BitWidth = LC->getAPInt().getBitWidth();
7853   const APInt &L = LC->getAPInt();
7854   const APInt &M = MC->getAPInt();
7855   const APInt &N = NC->getAPInt();
7856   APInt Two(BitWidth, 2);
7857 
7858   // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
7859 
7860   // The A coefficient is N/2
7861   APInt A = N.sdiv(Two);
7862 
7863   // The B coefficient is M-N/2
7864   APInt B = M;
7865   B -= A; // A is the same as N/2.
7866 
7867   // The C coefficient is L.
7868   const APInt& C = L;
7869 
7870   // Compute the B^2-4ac term.
7871   APInt SqrtTerm = B;
7872   SqrtTerm *= B;
7873   SqrtTerm -= 4 * (A * C);
7874 
7875   if (SqrtTerm.isNegative()) {
7876     // The loop is provably infinite.
7877     return None;
7878   }
7879 
7880   // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
7881   // integer value or else APInt::sqrt() will assert.
7882   APInt SqrtVal = SqrtTerm.sqrt();
7883 
7884   // Compute the two solutions for the quadratic formula.
7885   // The divisions must be performed as signed divisions.
7886   APInt NegB = -std::move(B);
7887   APInt TwoA = std::move(A);
7888   TwoA <<= 1;
7889   if (TwoA.isNullValue())
7890     return None;
7891 
7892   LLVMContext &Context = SE.getContext();
7893 
7894   ConstantInt *Solution1 =
7895     ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
7896   ConstantInt *Solution2 =
7897     ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
7898 
7899   return std::make_pair(cast<SCEVConstant>(SE.getConstant(Solution1)),
7900                         cast<SCEVConstant>(SE.getConstant(Solution2)));
7901 }
7902 
7903 ScalarEvolution::ExitLimit
7904 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit,
7905                               bool AllowPredicates) {
7906 
7907   // This is only used for loops with a "x != y" exit test. The exit condition
7908   // is now expressed as a single expression, V = x-y. So the exit test is
7909   // effectively V != 0.  We know and take advantage of the fact that this
7910   // expression only being used in a comparison by zero context.
7911 
7912   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
7913   // If the value is a constant
7914   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
7915     // If the value is already zero, the branch will execute zero times.
7916     if (C->getValue()->isZero()) return C;
7917     return getCouldNotCompute();  // Otherwise it will loop infinitely.
7918   }
7919 
7920   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
7921   if (!AddRec && AllowPredicates)
7922     // Try to make this an AddRec using runtime tests, in the first X
7923     // iterations of this loop, where X is the SCEV expression found by the
7924     // algorithm below.
7925     AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
7926 
7927   if (!AddRec || AddRec->getLoop() != L)
7928     return getCouldNotCompute();
7929 
7930   // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
7931   // the quadratic equation to solve it.
7932   if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
7933     if (auto Roots = SolveQuadraticEquation(AddRec, *this)) {
7934       const SCEVConstant *R1 = Roots->first;
7935       const SCEVConstant *R2 = Roots->second;
7936       // Pick the smallest positive root value.
7937       if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
7938               CmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
7939         if (!CB->getZExtValue())
7940           std::swap(R1, R2); // R1 is the minimum root now.
7941 
7942         // We can only use this value if the chrec ends up with an exact zero
7943         // value at this index.  When solving for "X*X != 5", for example, we
7944         // should not accept a root of 2.
7945         const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
7946         if (Val->isZero())
7947           // We found a quadratic root!
7948           return ExitLimit(R1, R1, false, Predicates);
7949       }
7950     }
7951     return getCouldNotCompute();
7952   }
7953 
7954   // Otherwise we can only handle this if it is affine.
7955   if (!AddRec->isAffine())
7956     return getCouldNotCompute();
7957 
7958   // If this is an affine expression, the execution count of this branch is
7959   // the minimum unsigned root of the following equation:
7960   //
7961   //     Start + Step*N = 0 (mod 2^BW)
7962   //
7963   // equivalent to:
7964   //
7965   //             Step*N = -Start (mod 2^BW)
7966   //
7967   // where BW is the common bit width of Start and Step.
7968 
7969   // Get the initial value for the loop.
7970   const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
7971   const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
7972 
7973   // For now we handle only constant steps.
7974   //
7975   // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
7976   // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
7977   // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
7978   // We have not yet seen any such cases.
7979   const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
7980   if (!StepC || StepC->getValue()->isZero())
7981     return getCouldNotCompute();
7982 
7983   // For positive steps (counting up until unsigned overflow):
7984   //   N = -Start/Step (as unsigned)
7985   // For negative steps (counting down to zero):
7986   //   N = Start/-Step
7987   // First compute the unsigned distance from zero in the direction of Step.
7988   bool CountDown = StepC->getAPInt().isNegative();
7989   const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
7990 
7991   // Handle unitary steps, which cannot wraparound.
7992   // 1*N = -Start; -1*N = Start (mod 2^BW), so:
7993   //   N = Distance (as unsigned)
7994   if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) {
7995     APInt MaxBECount = getUnsignedRangeMax(Distance);
7996 
7997     // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
7998     // we end up with a loop whose backedge-taken count is n - 1.  Detect this
7999     // case, and see if we can improve the bound.
8000     //
8001     // Explicitly handling this here is necessary because getUnsignedRange
8002     // isn't context-sensitive; it doesn't know that we only care about the
8003     // range inside the loop.
8004     const SCEV *Zero = getZero(Distance->getType());
8005     const SCEV *One = getOne(Distance->getType());
8006     const SCEV *DistancePlusOne = getAddExpr(Distance, One);
8007     if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
8008       // If Distance + 1 doesn't overflow, we can compute the maximum distance
8009       // as "unsigned_max(Distance + 1) - 1".
8010       ConstantRange CR = getUnsignedRange(DistancePlusOne);
8011       MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1);
8012     }
8013     return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates);
8014   }
8015 
8016   // If the condition controls loop exit (the loop exits only if the expression
8017   // is true) and the addition is no-wrap we can use unsigned divide to
8018   // compute the backedge count.  In this case, the step may not divide the
8019   // distance, but we don't care because if the condition is "missed" the loop
8020   // will have undefined behavior due to wrapping.
8021   if (ControlsExit && AddRec->hasNoSelfWrap() &&
8022       loopHasNoAbnormalExits(AddRec->getLoop())) {
8023     const SCEV *Exact =
8024         getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
8025     const SCEV *Max =
8026         Exact == getCouldNotCompute()
8027             ? Exact
8028             : getConstant(getUnsignedRangeMax(Exact));
8029     return ExitLimit(Exact, Max, false, Predicates);
8030   }
8031 
8032   // Solve the general equation.
8033   const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(),
8034                                                getNegativeSCEV(Start), *this);
8035   const SCEV *M = E == getCouldNotCompute()
8036                       ? E
8037                       : getConstant(getUnsignedRangeMax(E));
8038   return ExitLimit(E, M, false, Predicates);
8039 }
8040 
8041 ScalarEvolution::ExitLimit
8042 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
8043   // Loops that look like: while (X == 0) are very strange indeed.  We don't
8044   // handle them yet except for the trivial case.  This could be expanded in the
8045   // future as needed.
8046 
8047   // If the value is a constant, check to see if it is known to be non-zero
8048   // already.  If so, the backedge will execute zero times.
8049   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
8050     if (!C->getValue()->isZero())
8051       return getZero(C->getType());
8052     return getCouldNotCompute();  // Otherwise it will loop infinitely.
8053   }
8054 
8055   // We could implement others, but I really doubt anyone writes loops like
8056   // this, and if they did, they would already be constant folded.
8057   return getCouldNotCompute();
8058 }
8059 
8060 std::pair<BasicBlock *, BasicBlock *>
8061 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
8062   // If the block has a unique predecessor, then there is no path from the
8063   // predecessor to the block that does not go through the direct edge
8064   // from the predecessor to the block.
8065   if (BasicBlock *Pred = BB->getSinglePredecessor())
8066     return {Pred, BB};
8067 
8068   // A loop's header is defined to be a block that dominates the loop.
8069   // If the header has a unique predecessor outside the loop, it must be
8070   // a block that has exactly one successor that can reach the loop.
8071   if (Loop *L = LI.getLoopFor(BB))
8072     return {L->getLoopPredecessor(), L->getHeader()};
8073 
8074   return {nullptr, nullptr};
8075 }
8076 
8077 /// SCEV structural equivalence is usually sufficient for testing whether two
8078 /// expressions are equal, however for the purposes of looking for a condition
8079 /// guarding a loop, it can be useful to be a little more general, since a
8080 /// front-end may have replicated the controlling expression.
8081 ///
8082 static bool HasSameValue(const SCEV *A, const SCEV *B) {
8083   // Quick check to see if they are the same SCEV.
8084   if (A == B) return true;
8085 
8086   auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
8087     // Not all instructions that are "identical" compute the same value.  For
8088     // instance, two distinct alloca instructions allocating the same type are
8089     // identical and do not read memory; but compute distinct values.
8090     return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
8091   };
8092 
8093   // Otherwise, if they're both SCEVUnknown, it's possible that they hold
8094   // two different instructions with the same value. Check for this case.
8095   if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
8096     if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
8097       if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
8098         if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
8099           if (ComputesEqualValues(AI, BI))
8100             return true;
8101 
8102   // Otherwise assume they may have a different value.
8103   return false;
8104 }
8105 
8106 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
8107                                            const SCEV *&LHS, const SCEV *&RHS,
8108                                            unsigned Depth) {
8109   bool Changed = false;
8110 
8111   // If we hit the max recursion limit bail out.
8112   if (Depth >= 3)
8113     return false;
8114 
8115   // Canonicalize a constant to the right side.
8116   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
8117     // Check for both operands constant.
8118     if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
8119       if (ConstantExpr::getICmp(Pred,
8120                                 LHSC->getValue(),
8121                                 RHSC->getValue())->isNullValue())
8122         goto trivially_false;
8123       else
8124         goto trivially_true;
8125     }
8126     // Otherwise swap the operands to put the constant on the right.
8127     std::swap(LHS, RHS);
8128     Pred = ICmpInst::getSwappedPredicate(Pred);
8129     Changed = true;
8130   }
8131 
8132   // If we're comparing an addrec with a value which is loop-invariant in the
8133   // addrec's loop, put the addrec on the left. Also make a dominance check,
8134   // as both operands could be addrecs loop-invariant in each other's loop.
8135   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
8136     const Loop *L = AR->getLoop();
8137     if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
8138       std::swap(LHS, RHS);
8139       Pred = ICmpInst::getSwappedPredicate(Pred);
8140       Changed = true;
8141     }
8142   }
8143 
8144   // If there's a constant operand, canonicalize comparisons with boundary
8145   // cases, and canonicalize *-or-equal comparisons to regular comparisons.
8146   if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
8147     const APInt &RA = RC->getAPInt();
8148 
8149     bool SimplifiedByConstantRange = false;
8150 
8151     if (!ICmpInst::isEquality(Pred)) {
8152       ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA);
8153       if (ExactCR.isFullSet())
8154         goto trivially_true;
8155       else if (ExactCR.isEmptySet())
8156         goto trivially_false;
8157 
8158       APInt NewRHS;
8159       CmpInst::Predicate NewPred;
8160       if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
8161           ICmpInst::isEquality(NewPred)) {
8162         // We were able to convert an inequality to an equality.
8163         Pred = NewPred;
8164         RHS = getConstant(NewRHS);
8165         Changed = SimplifiedByConstantRange = true;
8166       }
8167     }
8168 
8169     if (!SimplifiedByConstantRange) {
8170       switch (Pred) {
8171       default:
8172         break;
8173       case ICmpInst::ICMP_EQ:
8174       case ICmpInst::ICMP_NE:
8175         // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
8176         if (!RA)
8177           if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
8178             if (const SCEVMulExpr *ME =
8179                     dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
8180               if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
8181                   ME->getOperand(0)->isAllOnesValue()) {
8182                 RHS = AE->getOperand(1);
8183                 LHS = ME->getOperand(1);
8184                 Changed = true;
8185               }
8186         break;
8187 
8188 
8189         // The "Should have been caught earlier!" messages refer to the fact
8190         // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
8191         // should have fired on the corresponding cases, and canonicalized the
8192         // check to trivially_true or trivially_false.
8193 
8194       case ICmpInst::ICMP_UGE:
8195         assert(!RA.isMinValue() && "Should have been caught earlier!");
8196         Pred = ICmpInst::ICMP_UGT;
8197         RHS = getConstant(RA - 1);
8198         Changed = true;
8199         break;
8200       case ICmpInst::ICMP_ULE:
8201         assert(!RA.isMaxValue() && "Should have been caught earlier!");
8202         Pred = ICmpInst::ICMP_ULT;
8203         RHS = getConstant(RA + 1);
8204         Changed = true;
8205         break;
8206       case ICmpInst::ICMP_SGE:
8207         assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
8208         Pred = ICmpInst::ICMP_SGT;
8209         RHS = getConstant(RA - 1);
8210         Changed = true;
8211         break;
8212       case ICmpInst::ICMP_SLE:
8213         assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
8214         Pred = ICmpInst::ICMP_SLT;
8215         RHS = getConstant(RA + 1);
8216         Changed = true;
8217         break;
8218       }
8219     }
8220   }
8221 
8222   // Check for obvious equality.
8223   if (HasSameValue(LHS, RHS)) {
8224     if (ICmpInst::isTrueWhenEqual(Pred))
8225       goto trivially_true;
8226     if (ICmpInst::isFalseWhenEqual(Pred))
8227       goto trivially_false;
8228   }
8229 
8230   // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
8231   // adding or subtracting 1 from one of the operands.
8232   switch (Pred) {
8233   case ICmpInst::ICMP_SLE:
8234     if (!getSignedRangeMax(RHS).isMaxSignedValue()) {
8235       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
8236                        SCEV::FlagNSW);
8237       Pred = ICmpInst::ICMP_SLT;
8238       Changed = true;
8239     } else if (!getSignedRangeMin(LHS).isMinSignedValue()) {
8240       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
8241                        SCEV::FlagNSW);
8242       Pred = ICmpInst::ICMP_SLT;
8243       Changed = true;
8244     }
8245     break;
8246   case ICmpInst::ICMP_SGE:
8247     if (!getSignedRangeMin(RHS).isMinSignedValue()) {
8248       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
8249                        SCEV::FlagNSW);
8250       Pred = ICmpInst::ICMP_SGT;
8251       Changed = true;
8252     } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) {
8253       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
8254                        SCEV::FlagNSW);
8255       Pred = ICmpInst::ICMP_SGT;
8256       Changed = true;
8257     }
8258     break;
8259   case ICmpInst::ICMP_ULE:
8260     if (!getUnsignedRangeMax(RHS).isMaxValue()) {
8261       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
8262                        SCEV::FlagNUW);
8263       Pred = ICmpInst::ICMP_ULT;
8264       Changed = true;
8265     } else if (!getUnsignedRangeMin(LHS).isMinValue()) {
8266       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
8267       Pred = ICmpInst::ICMP_ULT;
8268       Changed = true;
8269     }
8270     break;
8271   case ICmpInst::ICMP_UGE:
8272     if (!getUnsignedRangeMin(RHS).isMinValue()) {
8273       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
8274       Pred = ICmpInst::ICMP_UGT;
8275       Changed = true;
8276     } else if (!getUnsignedRangeMax(LHS).isMaxValue()) {
8277       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
8278                        SCEV::FlagNUW);
8279       Pred = ICmpInst::ICMP_UGT;
8280       Changed = true;
8281     }
8282     break;
8283   default:
8284     break;
8285   }
8286 
8287   // TODO: More simplifications are possible here.
8288 
8289   // Recursively simplify until we either hit a recursion limit or nothing
8290   // changes.
8291   if (Changed)
8292     return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
8293 
8294   return Changed;
8295 
8296 trivially_true:
8297   // Return 0 == 0.
8298   LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
8299   Pred = ICmpInst::ICMP_EQ;
8300   return true;
8301 
8302 trivially_false:
8303   // Return 0 != 0.
8304   LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
8305   Pred = ICmpInst::ICMP_NE;
8306   return true;
8307 }
8308 
8309 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
8310   return getSignedRangeMax(S).isNegative();
8311 }
8312 
8313 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
8314   return getSignedRangeMin(S).isStrictlyPositive();
8315 }
8316 
8317 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
8318   return !getSignedRangeMin(S).isNegative();
8319 }
8320 
8321 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
8322   return !getSignedRangeMax(S).isStrictlyPositive();
8323 }
8324 
8325 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
8326   return isKnownNegative(S) || isKnownPositive(S);
8327 }
8328 
8329 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
8330                                        const SCEV *LHS, const SCEV *RHS) {
8331   // Canonicalize the inputs first.
8332   (void)SimplifyICmpOperands(Pred, LHS, RHS);
8333 
8334   // If LHS or RHS is an addrec, check to see if the condition is true in
8335   // every iteration of the loop.
8336   // If LHS and RHS are both addrec, both conditions must be true in
8337   // every iteration of the loop.
8338   const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
8339   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
8340   bool LeftGuarded = false;
8341   bool RightGuarded = false;
8342   if (LAR) {
8343     const Loop *L = LAR->getLoop();
8344     if (isLoopEntryGuardedByCond(L, Pred, LAR->getStart(), RHS) &&
8345         isLoopBackedgeGuardedByCond(L, Pred, LAR->getPostIncExpr(*this), RHS)) {
8346       if (!RAR) return true;
8347       LeftGuarded = true;
8348     }
8349   }
8350   if (RAR) {
8351     const Loop *L = RAR->getLoop();
8352     if (isLoopEntryGuardedByCond(L, Pred, LHS, RAR->getStart()) &&
8353         isLoopBackedgeGuardedByCond(L, Pred, LHS, RAR->getPostIncExpr(*this))) {
8354       if (!LAR) return true;
8355       RightGuarded = true;
8356     }
8357   }
8358   if (LeftGuarded && RightGuarded)
8359     return true;
8360 
8361   if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
8362     return true;
8363 
8364   // Otherwise see what can be done with known constant ranges.
8365   return isKnownPredicateViaConstantRanges(Pred, LHS, RHS);
8366 }
8367 
8368 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS,
8369                                            ICmpInst::Predicate Pred,
8370                                            bool &Increasing) {
8371   bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing);
8372 
8373 #ifndef NDEBUG
8374   // Verify an invariant: inverting the predicate should turn a monotonically
8375   // increasing change to a monotonically decreasing one, and vice versa.
8376   bool IncreasingSwapped;
8377   bool ResultSwapped = isMonotonicPredicateImpl(
8378       LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped);
8379 
8380   assert(Result == ResultSwapped && "should be able to analyze both!");
8381   if (ResultSwapped)
8382     assert(Increasing == !IncreasingSwapped &&
8383            "monotonicity should flip as we flip the predicate");
8384 #endif
8385 
8386   return Result;
8387 }
8388 
8389 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS,
8390                                                ICmpInst::Predicate Pred,
8391                                                bool &Increasing) {
8392 
8393   // A zero step value for LHS means the induction variable is essentially a
8394   // loop invariant value. We don't really depend on the predicate actually
8395   // flipping from false to true (for increasing predicates, and the other way
8396   // around for decreasing predicates), all we care about is that *if* the
8397   // predicate changes then it only changes from false to true.
8398   //
8399   // A zero step value in itself is not very useful, but there may be places
8400   // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
8401   // as general as possible.
8402 
8403   switch (Pred) {
8404   default:
8405     return false; // Conservative answer
8406 
8407   case ICmpInst::ICMP_UGT:
8408   case ICmpInst::ICMP_UGE:
8409   case ICmpInst::ICMP_ULT:
8410   case ICmpInst::ICMP_ULE:
8411     if (!LHS->hasNoUnsignedWrap())
8412       return false;
8413 
8414     Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE;
8415     return true;
8416 
8417   case ICmpInst::ICMP_SGT:
8418   case ICmpInst::ICMP_SGE:
8419   case ICmpInst::ICMP_SLT:
8420   case ICmpInst::ICMP_SLE: {
8421     if (!LHS->hasNoSignedWrap())
8422       return false;
8423 
8424     const SCEV *Step = LHS->getStepRecurrence(*this);
8425 
8426     if (isKnownNonNegative(Step)) {
8427       Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE;
8428       return true;
8429     }
8430 
8431     if (isKnownNonPositive(Step)) {
8432       Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE;
8433       return true;
8434     }
8435 
8436     return false;
8437   }
8438 
8439   }
8440 
8441   llvm_unreachable("switch has default clause!");
8442 }
8443 
8444 bool ScalarEvolution::isLoopInvariantPredicate(
8445     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
8446     ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS,
8447     const SCEV *&InvariantRHS) {
8448 
8449   // If there is a loop-invariant, force it into the RHS, otherwise bail out.
8450   if (!isLoopInvariant(RHS, L)) {
8451     if (!isLoopInvariant(LHS, L))
8452       return false;
8453 
8454     std::swap(LHS, RHS);
8455     Pred = ICmpInst::getSwappedPredicate(Pred);
8456   }
8457 
8458   const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
8459   if (!ArLHS || ArLHS->getLoop() != L)
8460     return false;
8461 
8462   bool Increasing;
8463   if (!isMonotonicPredicate(ArLHS, Pred, Increasing))
8464     return false;
8465 
8466   // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
8467   // true as the loop iterates, and the backedge is control dependent on
8468   // "ArLHS `Pred` RHS" == true then we can reason as follows:
8469   //
8470   //   * if the predicate was false in the first iteration then the predicate
8471   //     is never evaluated again, since the loop exits without taking the
8472   //     backedge.
8473   //   * if the predicate was true in the first iteration then it will
8474   //     continue to be true for all future iterations since it is
8475   //     monotonically increasing.
8476   //
8477   // For both the above possibilities, we can replace the loop varying
8478   // predicate with its value on the first iteration of the loop (which is
8479   // loop invariant).
8480   //
8481   // A similar reasoning applies for a monotonically decreasing predicate, by
8482   // replacing true with false and false with true in the above two bullets.
8483 
8484   auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
8485 
8486   if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
8487     return false;
8488 
8489   InvariantPred = Pred;
8490   InvariantLHS = ArLHS->getStart();
8491   InvariantRHS = RHS;
8492   return true;
8493 }
8494 
8495 bool ScalarEvolution::isKnownPredicateViaConstantRanges(
8496     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
8497   if (HasSameValue(LHS, RHS))
8498     return ICmpInst::isTrueWhenEqual(Pred);
8499 
8500   // This code is split out from isKnownPredicate because it is called from
8501   // within isLoopEntryGuardedByCond.
8502 
8503   auto CheckRanges =
8504       [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) {
8505     return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS)
8506         .contains(RangeLHS);
8507   };
8508 
8509   // The check at the top of the function catches the case where the values are
8510   // known to be equal.
8511   if (Pred == CmpInst::ICMP_EQ)
8512     return false;
8513 
8514   if (Pred == CmpInst::ICMP_NE)
8515     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) ||
8516            CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) ||
8517            isKnownNonZero(getMinusSCEV(LHS, RHS));
8518 
8519   if (CmpInst::isSigned(Pred))
8520     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS));
8521 
8522   return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS));
8523 }
8524 
8525 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
8526                                                     const SCEV *LHS,
8527                                                     const SCEV *RHS) {
8528 
8529   // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer.
8530   // Return Y via OutY.
8531   auto MatchBinaryAddToConst =
8532       [this](const SCEV *Result, const SCEV *X, APInt &OutY,
8533              SCEV::NoWrapFlags ExpectedFlags) {
8534     const SCEV *NonConstOp, *ConstOp;
8535     SCEV::NoWrapFlags FlagsPresent;
8536 
8537     if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) ||
8538         !isa<SCEVConstant>(ConstOp) || NonConstOp != X)
8539       return false;
8540 
8541     OutY = cast<SCEVConstant>(ConstOp)->getAPInt();
8542     return (FlagsPresent & ExpectedFlags) == ExpectedFlags;
8543   };
8544 
8545   APInt C;
8546 
8547   switch (Pred) {
8548   default:
8549     break;
8550 
8551   case ICmpInst::ICMP_SGE:
8552     std::swap(LHS, RHS);
8553     LLVM_FALLTHROUGH;
8554   case ICmpInst::ICMP_SLE:
8555     // X s<= (X + C)<nsw> if C >= 0
8556     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative())
8557       return true;
8558 
8559     // (X + C)<nsw> s<= X if C <= 0
8560     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) &&
8561         !C.isStrictlyPositive())
8562       return true;
8563     break;
8564 
8565   case ICmpInst::ICMP_SGT:
8566     std::swap(LHS, RHS);
8567     LLVM_FALLTHROUGH;
8568   case ICmpInst::ICMP_SLT:
8569     // X s< (X + C)<nsw> if C > 0
8570     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) &&
8571         C.isStrictlyPositive())
8572       return true;
8573 
8574     // (X + C)<nsw> s< X if C < 0
8575     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative())
8576       return true;
8577     break;
8578   }
8579 
8580   return false;
8581 }
8582 
8583 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
8584                                                    const SCEV *LHS,
8585                                                    const SCEV *RHS) {
8586   if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
8587     return false;
8588 
8589   // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
8590   // the stack can result in exponential time complexity.
8591   SaveAndRestore<bool> Restore(ProvingSplitPredicate, true);
8592 
8593   // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
8594   //
8595   // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
8596   // isKnownPredicate.  isKnownPredicate is more powerful, but also more
8597   // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
8598   // interesting cases seen in practice.  We can consider "upgrading" L >= 0 to
8599   // use isKnownPredicate later if needed.
8600   return isKnownNonNegative(RHS) &&
8601          isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
8602          isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
8603 }
8604 
8605 bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB,
8606                                         ICmpInst::Predicate Pred,
8607                                         const SCEV *LHS, const SCEV *RHS) {
8608   // No need to even try if we know the module has no guards.
8609   if (!HasGuards)
8610     return false;
8611 
8612   return any_of(*BB, [&](Instruction &I) {
8613     using namespace llvm::PatternMatch;
8614 
8615     Value *Condition;
8616     return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
8617                          m_Value(Condition))) &&
8618            isImpliedCond(Pred, LHS, RHS, Condition, false);
8619   });
8620 }
8621 
8622 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
8623 /// protected by a conditional between LHS and RHS.  This is used to
8624 /// to eliminate casts.
8625 bool
8626 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
8627                                              ICmpInst::Predicate Pred,
8628                                              const SCEV *LHS, const SCEV *RHS) {
8629   // Interpret a null as meaning no loop, where there is obviously no guard
8630   // (interprocedural conditions notwithstanding).
8631   if (!L) return true;
8632 
8633   if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS))
8634     return true;
8635 
8636   BasicBlock *Latch = L->getLoopLatch();
8637   if (!Latch)
8638     return false;
8639 
8640   BranchInst *LoopContinuePredicate =
8641     dyn_cast<BranchInst>(Latch->getTerminator());
8642   if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
8643       isImpliedCond(Pred, LHS, RHS,
8644                     LoopContinuePredicate->getCondition(),
8645                     LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
8646     return true;
8647 
8648   // We don't want more than one activation of the following loops on the stack
8649   // -- that can lead to O(n!) time complexity.
8650   if (WalkingBEDominatingConds)
8651     return false;
8652 
8653   SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true);
8654 
8655   // See if we can exploit a trip count to prove the predicate.
8656   const auto &BETakenInfo = getBackedgeTakenInfo(L);
8657   const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
8658   if (LatchBECount != getCouldNotCompute()) {
8659     // We know that Latch branches back to the loop header exactly
8660     // LatchBECount times.  This means the backdege condition at Latch is
8661     // equivalent to  "{0,+,1} u< LatchBECount".
8662     Type *Ty = LatchBECount->getType();
8663     auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
8664     const SCEV *LoopCounter =
8665       getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
8666     if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
8667                       LatchBECount))
8668       return true;
8669   }
8670 
8671   // Check conditions due to any @llvm.assume intrinsics.
8672   for (auto &AssumeVH : AC.assumptions()) {
8673     if (!AssumeVH)
8674       continue;
8675     auto *CI = cast<CallInst>(AssumeVH);
8676     if (!DT.dominates(CI, Latch->getTerminator()))
8677       continue;
8678 
8679     if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
8680       return true;
8681   }
8682 
8683   // If the loop is not reachable from the entry block, we risk running into an
8684   // infinite loop as we walk up into the dom tree.  These loops do not matter
8685   // anyway, so we just return a conservative answer when we see them.
8686   if (!DT.isReachableFromEntry(L->getHeader()))
8687     return false;
8688 
8689   if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
8690     return true;
8691 
8692   for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
8693        DTN != HeaderDTN; DTN = DTN->getIDom()) {
8694 
8695     assert(DTN && "should reach the loop header before reaching the root!");
8696 
8697     BasicBlock *BB = DTN->getBlock();
8698     if (isImpliedViaGuard(BB, Pred, LHS, RHS))
8699       return true;
8700 
8701     BasicBlock *PBB = BB->getSinglePredecessor();
8702     if (!PBB)
8703       continue;
8704 
8705     BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
8706     if (!ContinuePredicate || !ContinuePredicate->isConditional())
8707       continue;
8708 
8709     Value *Condition = ContinuePredicate->getCondition();
8710 
8711     // If we have an edge `E` within the loop body that dominates the only
8712     // latch, the condition guarding `E` also guards the backedge.  This
8713     // reasoning works only for loops with a single latch.
8714 
8715     BasicBlockEdge DominatingEdge(PBB, BB);
8716     if (DominatingEdge.isSingleEdge()) {
8717       // We're constructively (and conservatively) enumerating edges within the
8718       // loop body that dominate the latch.  The dominator tree better agree
8719       // with us on this:
8720       assert(DT.dominates(DominatingEdge, Latch) && "should be!");
8721 
8722       if (isImpliedCond(Pred, LHS, RHS, Condition,
8723                         BB != ContinuePredicate->getSuccessor(0)))
8724         return true;
8725     }
8726   }
8727 
8728   return false;
8729 }
8730 
8731 bool
8732 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
8733                                           ICmpInst::Predicate Pred,
8734                                           const SCEV *LHS, const SCEV *RHS) {
8735   // Interpret a null as meaning no loop, where there is obviously no guard
8736   // (interprocedural conditions notwithstanding).
8737   if (!L) return false;
8738 
8739   if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS))
8740     return true;
8741 
8742   // Starting at the loop predecessor, climb up the predecessor chain, as long
8743   // as there are predecessors that can be found that have unique successors
8744   // leading to the original header.
8745   for (std::pair<BasicBlock *, BasicBlock *>
8746          Pair(L->getLoopPredecessor(), L->getHeader());
8747        Pair.first;
8748        Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
8749 
8750     if (isImpliedViaGuard(Pair.first, Pred, LHS, RHS))
8751       return true;
8752 
8753     BranchInst *LoopEntryPredicate =
8754       dyn_cast<BranchInst>(Pair.first->getTerminator());
8755     if (!LoopEntryPredicate ||
8756         LoopEntryPredicate->isUnconditional())
8757       continue;
8758 
8759     if (isImpliedCond(Pred, LHS, RHS,
8760                       LoopEntryPredicate->getCondition(),
8761                       LoopEntryPredicate->getSuccessor(0) != Pair.second))
8762       return true;
8763   }
8764 
8765   // Check conditions due to any @llvm.assume intrinsics.
8766   for (auto &AssumeVH : AC.assumptions()) {
8767     if (!AssumeVH)
8768       continue;
8769     auto *CI = cast<CallInst>(AssumeVH);
8770     if (!DT.dominates(CI, L->getHeader()))
8771       continue;
8772 
8773     if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
8774       return true;
8775   }
8776 
8777   return false;
8778 }
8779 
8780 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
8781                                     const SCEV *LHS, const SCEV *RHS,
8782                                     Value *FoundCondValue,
8783                                     bool Inverse) {
8784   if (!PendingLoopPredicates.insert(FoundCondValue).second)
8785     return false;
8786 
8787   auto ClearOnExit =
8788       make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
8789 
8790   // Recursively handle And and Or conditions.
8791   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
8792     if (BO->getOpcode() == Instruction::And) {
8793       if (!Inverse)
8794         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
8795                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
8796     } else if (BO->getOpcode() == Instruction::Or) {
8797       if (Inverse)
8798         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
8799                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
8800     }
8801   }
8802 
8803   ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
8804   if (!ICI) return false;
8805 
8806   // Now that we found a conditional branch that dominates the loop or controls
8807   // the loop latch. Check to see if it is the comparison we are looking for.
8808   ICmpInst::Predicate FoundPred;
8809   if (Inverse)
8810     FoundPred = ICI->getInversePredicate();
8811   else
8812     FoundPred = ICI->getPredicate();
8813 
8814   const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
8815   const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
8816 
8817   return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS);
8818 }
8819 
8820 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
8821                                     const SCEV *RHS,
8822                                     ICmpInst::Predicate FoundPred,
8823                                     const SCEV *FoundLHS,
8824                                     const SCEV *FoundRHS) {
8825   // Balance the types.
8826   if (getTypeSizeInBits(LHS->getType()) <
8827       getTypeSizeInBits(FoundLHS->getType())) {
8828     if (CmpInst::isSigned(Pred)) {
8829       LHS = getSignExtendExpr(LHS, FoundLHS->getType());
8830       RHS = getSignExtendExpr(RHS, FoundLHS->getType());
8831     } else {
8832       LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
8833       RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
8834     }
8835   } else if (getTypeSizeInBits(LHS->getType()) >
8836       getTypeSizeInBits(FoundLHS->getType())) {
8837     if (CmpInst::isSigned(FoundPred)) {
8838       FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
8839       FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
8840     } else {
8841       FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
8842       FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
8843     }
8844   }
8845 
8846   // Canonicalize the query to match the way instcombine will have
8847   // canonicalized the comparison.
8848   if (SimplifyICmpOperands(Pred, LHS, RHS))
8849     if (LHS == RHS)
8850       return CmpInst::isTrueWhenEqual(Pred);
8851   if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
8852     if (FoundLHS == FoundRHS)
8853       return CmpInst::isFalseWhenEqual(FoundPred);
8854 
8855   // Check to see if we can make the LHS or RHS match.
8856   if (LHS == FoundRHS || RHS == FoundLHS) {
8857     if (isa<SCEVConstant>(RHS)) {
8858       std::swap(FoundLHS, FoundRHS);
8859       FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
8860     } else {
8861       std::swap(LHS, RHS);
8862       Pred = ICmpInst::getSwappedPredicate(Pred);
8863     }
8864   }
8865 
8866   // Check whether the found predicate is the same as the desired predicate.
8867   if (FoundPred == Pred)
8868     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
8869 
8870   // Check whether swapping the found predicate makes it the same as the
8871   // desired predicate.
8872   if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
8873     if (isa<SCEVConstant>(RHS))
8874       return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
8875     else
8876       return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
8877                                    RHS, LHS, FoundLHS, FoundRHS);
8878   }
8879 
8880   // Unsigned comparison is the same as signed comparison when both the operands
8881   // are non-negative.
8882   if (CmpInst::isUnsigned(FoundPred) &&
8883       CmpInst::getSignedPredicate(FoundPred) == Pred &&
8884       isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS))
8885     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
8886 
8887   // Check if we can make progress by sharpening ranges.
8888   if (FoundPred == ICmpInst::ICMP_NE &&
8889       (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
8890 
8891     const SCEVConstant *C = nullptr;
8892     const SCEV *V = nullptr;
8893 
8894     if (isa<SCEVConstant>(FoundLHS)) {
8895       C = cast<SCEVConstant>(FoundLHS);
8896       V = FoundRHS;
8897     } else {
8898       C = cast<SCEVConstant>(FoundRHS);
8899       V = FoundLHS;
8900     }
8901 
8902     // The guarding predicate tells us that C != V. If the known range
8903     // of V is [C, t), we can sharpen the range to [C + 1, t).  The
8904     // range we consider has to correspond to same signedness as the
8905     // predicate we're interested in folding.
8906 
8907     APInt Min = ICmpInst::isSigned(Pred) ?
8908         getSignedRangeMin(V) : getUnsignedRangeMin(V);
8909 
8910     if (Min == C->getAPInt()) {
8911       // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
8912       // This is true even if (Min + 1) wraps around -- in case of
8913       // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
8914 
8915       APInt SharperMin = Min + 1;
8916 
8917       switch (Pred) {
8918         case ICmpInst::ICMP_SGE:
8919         case ICmpInst::ICMP_UGE:
8920           // We know V `Pred` SharperMin.  If this implies LHS `Pred`
8921           // RHS, we're done.
8922           if (isImpliedCondOperands(Pred, LHS, RHS, V,
8923                                     getConstant(SharperMin)))
8924             return true;
8925           LLVM_FALLTHROUGH;
8926 
8927         case ICmpInst::ICMP_SGT:
8928         case ICmpInst::ICMP_UGT:
8929           // We know from the range information that (V `Pred` Min ||
8930           // V == Min).  We know from the guarding condition that !(V
8931           // == Min).  This gives us
8932           //
8933           //       V `Pred` Min || V == Min && !(V == Min)
8934           //   =>  V `Pred` Min
8935           //
8936           // If V `Pred` Min implies LHS `Pred` RHS, we're done.
8937 
8938           if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min)))
8939             return true;
8940           LLVM_FALLTHROUGH;
8941 
8942         default:
8943           // No change
8944           break;
8945       }
8946     }
8947   }
8948 
8949   // Check whether the actual condition is beyond sufficient.
8950   if (FoundPred == ICmpInst::ICMP_EQ)
8951     if (ICmpInst::isTrueWhenEqual(Pred))
8952       if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
8953         return true;
8954   if (Pred == ICmpInst::ICMP_NE)
8955     if (!ICmpInst::isTrueWhenEqual(FoundPred))
8956       if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
8957         return true;
8958 
8959   // Otherwise assume the worst.
8960   return false;
8961 }
8962 
8963 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
8964                                      const SCEV *&L, const SCEV *&R,
8965                                      SCEV::NoWrapFlags &Flags) {
8966   const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
8967   if (!AE || AE->getNumOperands() != 2)
8968     return false;
8969 
8970   L = AE->getOperand(0);
8971   R = AE->getOperand(1);
8972   Flags = AE->getNoWrapFlags();
8973   return true;
8974 }
8975 
8976 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More,
8977                                                            const SCEV *Less) {
8978   // We avoid subtracting expressions here because this function is usually
8979   // fairly deep in the call stack (i.e. is called many times).
8980 
8981   if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
8982     const auto *LAR = cast<SCEVAddRecExpr>(Less);
8983     const auto *MAR = cast<SCEVAddRecExpr>(More);
8984 
8985     if (LAR->getLoop() != MAR->getLoop())
8986       return None;
8987 
8988     // We look at affine expressions only; not for correctness but to keep
8989     // getStepRecurrence cheap.
8990     if (!LAR->isAffine() || !MAR->isAffine())
8991       return None;
8992 
8993     if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
8994       return None;
8995 
8996     Less = LAR->getStart();
8997     More = MAR->getStart();
8998 
8999     // fall through
9000   }
9001 
9002   if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
9003     const auto &M = cast<SCEVConstant>(More)->getAPInt();
9004     const auto &L = cast<SCEVConstant>(Less)->getAPInt();
9005     return M - L;
9006   }
9007 
9008   const SCEV *L, *R;
9009   SCEV::NoWrapFlags Flags;
9010   if (splitBinaryAdd(Less, L, R, Flags))
9011     if (const auto *LC = dyn_cast<SCEVConstant>(L))
9012       if (R == More)
9013         return -(LC->getAPInt());
9014 
9015   if (splitBinaryAdd(More, L, R, Flags))
9016     if (const auto *LC = dyn_cast<SCEVConstant>(L))
9017       if (R == Less)
9018         return LC->getAPInt();
9019 
9020   return None;
9021 }
9022 
9023 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
9024     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
9025     const SCEV *FoundLHS, const SCEV *FoundRHS) {
9026   if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
9027     return false;
9028 
9029   const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
9030   if (!AddRecLHS)
9031     return false;
9032 
9033   const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
9034   if (!AddRecFoundLHS)
9035     return false;
9036 
9037   // We'd like to let SCEV reason about control dependencies, so we constrain
9038   // both the inequalities to be about add recurrences on the same loop.  This
9039   // way we can use isLoopEntryGuardedByCond later.
9040 
9041   const Loop *L = AddRecFoundLHS->getLoop();
9042   if (L != AddRecLHS->getLoop())
9043     return false;
9044 
9045   //  FoundLHS u< FoundRHS u< -C =>  (FoundLHS + C) u< (FoundRHS + C) ... (1)
9046   //
9047   //  FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
9048   //                                                                  ... (2)
9049   //
9050   // Informal proof for (2), assuming (1) [*]:
9051   //
9052   // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
9053   //
9054   // Then
9055   //
9056   //       FoundLHS s< FoundRHS s< INT_MIN - C
9057   // <=>  (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C   [ using (3) ]
9058   // <=>  (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
9059   // <=>  (FoundLHS + INT_MIN + C + INT_MIN) s<
9060   //                        (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
9061   // <=>  FoundLHS + C s< FoundRHS + C
9062   //
9063   // [*]: (1) can be proved by ruling out overflow.
9064   //
9065   // [**]: This can be proved by analyzing all the four possibilities:
9066   //    (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
9067   //    (A s>= 0, B s>= 0).
9068   //
9069   // Note:
9070   // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
9071   // will not sign underflow.  For instance, say FoundLHS = (i8 -128), FoundRHS
9072   // = (i8 -127) and C = (i8 -100).  Then INT_MIN - C = (i8 -28), and FoundRHS
9073   // s< (INT_MIN - C).  Lack of sign overflow / underflow in "FoundRHS + C" is
9074   // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
9075   // C)".
9076 
9077   Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
9078   Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
9079   if (!LDiff || !RDiff || *LDiff != *RDiff)
9080     return false;
9081 
9082   if (LDiff->isMinValue())
9083     return true;
9084 
9085   APInt FoundRHSLimit;
9086 
9087   if (Pred == CmpInst::ICMP_ULT) {
9088     FoundRHSLimit = -(*RDiff);
9089   } else {
9090     assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
9091     FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
9092   }
9093 
9094   // Try to prove (1) or (2), as needed.
9095   return isLoopEntryGuardedByCond(L, Pred, FoundRHS,
9096                                   getConstant(FoundRHSLimit));
9097 }
9098 
9099 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
9100                                             const SCEV *LHS, const SCEV *RHS,
9101                                             const SCEV *FoundLHS,
9102                                             const SCEV *FoundRHS) {
9103   if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
9104     return true;
9105 
9106   if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
9107     return true;
9108 
9109   return isImpliedCondOperandsHelper(Pred, LHS, RHS,
9110                                      FoundLHS, FoundRHS) ||
9111          // ~x < ~y --> x > y
9112          isImpliedCondOperandsHelper(Pred, LHS, RHS,
9113                                      getNotSCEV(FoundRHS),
9114                                      getNotSCEV(FoundLHS));
9115 }
9116 
9117 
9118 /// If Expr computes ~A, return A else return nullptr
9119 static const SCEV *MatchNotExpr(const SCEV *Expr) {
9120   const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
9121   if (!Add || Add->getNumOperands() != 2 ||
9122       !Add->getOperand(0)->isAllOnesValue())
9123     return nullptr;
9124 
9125   const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
9126   if (!AddRHS || AddRHS->getNumOperands() != 2 ||
9127       !AddRHS->getOperand(0)->isAllOnesValue())
9128     return nullptr;
9129 
9130   return AddRHS->getOperand(1);
9131 }
9132 
9133 
9134 /// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values?
9135 template<typename MaxExprType>
9136 static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr,
9137                               const SCEV *Candidate) {
9138   const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr);
9139   if (!MaxExpr) return false;
9140 
9141   return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end();
9142 }
9143 
9144 
9145 /// Is MaybeMinExpr an SMin or UMin of Candidate and some other values?
9146 template<typename MaxExprType>
9147 static bool IsMinConsistingOf(ScalarEvolution &SE,
9148                               const SCEV *MaybeMinExpr,
9149                               const SCEV *Candidate) {
9150   const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr);
9151   if (!MaybeMaxExpr)
9152     return false;
9153 
9154   return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate));
9155 }
9156 
9157 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
9158                                            ICmpInst::Predicate Pred,
9159                                            const SCEV *LHS, const SCEV *RHS) {
9160 
9161   // If both sides are affine addrecs for the same loop, with equal
9162   // steps, and we know the recurrences don't wrap, then we only
9163   // need to check the predicate on the starting values.
9164 
9165   if (!ICmpInst::isRelational(Pred))
9166     return false;
9167 
9168   const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
9169   if (!LAR)
9170     return false;
9171   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
9172   if (!RAR)
9173     return false;
9174   if (LAR->getLoop() != RAR->getLoop())
9175     return false;
9176   if (!LAR->isAffine() || !RAR->isAffine())
9177     return false;
9178 
9179   if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
9180     return false;
9181 
9182   SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
9183                          SCEV::FlagNSW : SCEV::FlagNUW;
9184   if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
9185     return false;
9186 
9187   return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
9188 }
9189 
9190 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
9191 /// expression?
9192 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
9193                                         ICmpInst::Predicate Pred,
9194                                         const SCEV *LHS, const SCEV *RHS) {
9195   switch (Pred) {
9196   default:
9197     return false;
9198 
9199   case ICmpInst::ICMP_SGE:
9200     std::swap(LHS, RHS);
9201     LLVM_FALLTHROUGH;
9202   case ICmpInst::ICMP_SLE:
9203     return
9204       // min(A, ...) <= A
9205       IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) ||
9206       // A <= max(A, ...)
9207       IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
9208 
9209   case ICmpInst::ICMP_UGE:
9210     std::swap(LHS, RHS);
9211     LLVM_FALLTHROUGH;
9212   case ICmpInst::ICMP_ULE:
9213     return
9214       // min(A, ...) <= A
9215       IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) ||
9216       // A <= max(A, ...)
9217       IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
9218   }
9219 
9220   llvm_unreachable("covered switch fell through?!");
9221 }
9222 
9223 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred,
9224                                              const SCEV *LHS, const SCEV *RHS,
9225                                              const SCEV *FoundLHS,
9226                                              const SCEV *FoundRHS,
9227                                              unsigned Depth) {
9228   assert(getTypeSizeInBits(LHS->getType()) ==
9229              getTypeSizeInBits(RHS->getType()) &&
9230          "LHS and RHS have different sizes?");
9231   assert(getTypeSizeInBits(FoundLHS->getType()) ==
9232              getTypeSizeInBits(FoundRHS->getType()) &&
9233          "FoundLHS and FoundRHS have different sizes?");
9234   // We want to avoid hurting the compile time with analysis of too big trees.
9235   if (Depth > MaxSCEVOperationsImplicationDepth)
9236     return false;
9237   // We only want to work with ICMP_SGT comparison so far.
9238   // TODO: Extend to ICMP_UGT?
9239   if (Pred == ICmpInst::ICMP_SLT) {
9240     Pred = ICmpInst::ICMP_SGT;
9241     std::swap(LHS, RHS);
9242     std::swap(FoundLHS, FoundRHS);
9243   }
9244   if (Pred != ICmpInst::ICMP_SGT)
9245     return false;
9246 
9247   auto GetOpFromSExt = [&](const SCEV *S) {
9248     if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
9249       return Ext->getOperand();
9250     // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
9251     // the constant in some cases.
9252     return S;
9253   };
9254 
9255   // Acquire values from extensions.
9256   auto *OrigFoundLHS = FoundLHS;
9257   LHS = GetOpFromSExt(LHS);
9258   FoundLHS = GetOpFromSExt(FoundLHS);
9259 
9260   // Is the SGT predicate can be proved trivially or using the found context.
9261   auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
9262     return isKnownViaSimpleReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
9263            isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
9264                                   FoundRHS, Depth + 1);
9265   };
9266 
9267   if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
9268     // We want to avoid creation of any new non-constant SCEV. Since we are
9269     // going to compare the operands to RHS, we should be certain that we don't
9270     // need any size extensions for this. So let's decline all cases when the
9271     // sizes of types of LHS and RHS do not match.
9272     // TODO: Maybe try to get RHS from sext to catch more cases?
9273     if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType()))
9274       return false;
9275 
9276     // Should not overflow.
9277     if (!LHSAddExpr->hasNoSignedWrap())
9278       return false;
9279 
9280     auto *LL = LHSAddExpr->getOperand(0);
9281     auto *LR = LHSAddExpr->getOperand(1);
9282     auto *MinusOne = getNegativeSCEV(getOne(RHS->getType()));
9283 
9284     // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
9285     auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
9286       return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
9287     };
9288     // Try to prove the following rule:
9289     // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
9290     // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
9291     if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
9292       return true;
9293   } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
9294     Value *LL, *LR;
9295     // FIXME: Once we have SDiv implemented, we can get rid of this matching.
9296     using namespace llvm::PatternMatch;
9297     if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
9298       // Rules for division.
9299       // We are going to perform some comparisons with Denominator and its
9300       // derivative expressions. In general case, creating a SCEV for it may
9301       // lead to a complex analysis of the entire graph, and in particular it
9302       // can request trip count recalculation for the same loop. This would
9303       // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
9304       // this, we only want to create SCEVs that are constants in this section.
9305       // So we bail if Denominator is not a constant.
9306       if (!isa<ConstantInt>(LR))
9307         return false;
9308 
9309       auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
9310 
9311       // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
9312       // then a SCEV for the numerator already exists and matches with FoundLHS.
9313       auto *Numerator = getExistingSCEV(LL);
9314       if (!Numerator || Numerator->getType() != FoundLHS->getType())
9315         return false;
9316 
9317       // Make sure that the numerator matches with FoundLHS and the denominator
9318       // is positive.
9319       if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
9320         return false;
9321 
9322       auto *DTy = Denominator->getType();
9323       auto *FRHSTy = FoundRHS->getType();
9324       if (DTy->isPointerTy() != FRHSTy->isPointerTy())
9325         // One of types is a pointer and another one is not. We cannot extend
9326         // them properly to a wider type, so let us just reject this case.
9327         // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
9328         // to avoid this check.
9329         return false;
9330 
9331       // Given that:
9332       // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
9333       auto *WTy = getWiderType(DTy, FRHSTy);
9334       auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
9335       auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
9336 
9337       // Try to prove the following rule:
9338       // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
9339       // For example, given that FoundLHS > 2. It means that FoundLHS is at
9340       // least 3. If we divide it by Denominator < 4, we will have at least 1.
9341       auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
9342       if (isKnownNonPositive(RHS) &&
9343           IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
9344         return true;
9345 
9346       // Try to prove the following rule:
9347       // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
9348       // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
9349       // If we divide it by Denominator > 2, then:
9350       // 1. If FoundLHS is negative, then the result is 0.
9351       // 2. If FoundLHS is non-negative, then the result is non-negative.
9352       // Anyways, the result is non-negative.
9353       auto *MinusOne = getNegativeSCEV(getOne(WTy));
9354       auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
9355       if (isKnownNegative(RHS) &&
9356           IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
9357         return true;
9358     }
9359   }
9360 
9361   return false;
9362 }
9363 
9364 bool
9365 ScalarEvolution::isKnownViaSimpleReasoning(ICmpInst::Predicate Pred,
9366                                            const SCEV *LHS, const SCEV *RHS) {
9367   return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
9368          IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
9369          IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
9370          isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
9371 }
9372 
9373 bool
9374 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
9375                                              const SCEV *LHS, const SCEV *RHS,
9376                                              const SCEV *FoundLHS,
9377                                              const SCEV *FoundRHS) {
9378   switch (Pred) {
9379   default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
9380   case ICmpInst::ICMP_EQ:
9381   case ICmpInst::ICMP_NE:
9382     if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
9383       return true;
9384     break;
9385   case ICmpInst::ICMP_SLT:
9386   case ICmpInst::ICMP_SLE:
9387     if (isKnownViaSimpleReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
9388         isKnownViaSimpleReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS))
9389       return true;
9390     break;
9391   case ICmpInst::ICMP_SGT:
9392   case ICmpInst::ICMP_SGE:
9393     if (isKnownViaSimpleReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
9394         isKnownViaSimpleReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS))
9395       return true;
9396     break;
9397   case ICmpInst::ICMP_ULT:
9398   case ICmpInst::ICMP_ULE:
9399     if (isKnownViaSimpleReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
9400         isKnownViaSimpleReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS))
9401       return true;
9402     break;
9403   case ICmpInst::ICMP_UGT:
9404   case ICmpInst::ICMP_UGE:
9405     if (isKnownViaSimpleReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
9406         isKnownViaSimpleReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS))
9407       return true;
9408     break;
9409   }
9410 
9411   // Maybe it can be proved via operations?
9412   if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
9413     return true;
9414 
9415   return false;
9416 }
9417 
9418 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
9419                                                      const SCEV *LHS,
9420                                                      const SCEV *RHS,
9421                                                      const SCEV *FoundLHS,
9422                                                      const SCEV *FoundRHS) {
9423   if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
9424     // The restriction on `FoundRHS` be lifted easily -- it exists only to
9425     // reduce the compile time impact of this optimization.
9426     return false;
9427 
9428   Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
9429   if (!Addend)
9430     return false;
9431 
9432   const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
9433 
9434   // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
9435   // antecedent "`FoundLHS` `Pred` `FoundRHS`".
9436   ConstantRange FoundLHSRange =
9437       ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS);
9438 
9439   // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
9440   ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
9441 
9442   // We can also compute the range of values for `LHS` that satisfy the
9443   // consequent, "`LHS` `Pred` `RHS`":
9444   const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
9445   ConstantRange SatisfyingLHSRange =
9446       ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS);
9447 
9448   // The antecedent implies the consequent if every value of `LHS` that
9449   // satisfies the antecedent also satisfies the consequent.
9450   return SatisfyingLHSRange.contains(LHSRange);
9451 }
9452 
9453 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
9454                                          bool IsSigned, bool NoWrap) {
9455   assert(isKnownPositive(Stride) && "Positive stride expected!");
9456 
9457   if (NoWrap) return false;
9458 
9459   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
9460   const SCEV *One = getOne(Stride->getType());
9461 
9462   if (IsSigned) {
9463     APInt MaxRHS = getSignedRangeMax(RHS);
9464     APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
9465     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
9466 
9467     // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
9468     return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS);
9469   }
9470 
9471   APInt MaxRHS = getUnsignedRangeMax(RHS);
9472   APInt MaxValue = APInt::getMaxValue(BitWidth);
9473   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
9474 
9475   // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
9476   return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS);
9477 }
9478 
9479 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
9480                                          bool IsSigned, bool NoWrap) {
9481   if (NoWrap) return false;
9482 
9483   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
9484   const SCEV *One = getOne(Stride->getType());
9485 
9486   if (IsSigned) {
9487     APInt MinRHS = getSignedRangeMin(RHS);
9488     APInt MinValue = APInt::getSignedMinValue(BitWidth);
9489     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
9490 
9491     // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
9492     return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS);
9493   }
9494 
9495   APInt MinRHS = getUnsignedRangeMin(RHS);
9496   APInt MinValue = APInt::getMinValue(BitWidth);
9497   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
9498 
9499   // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
9500   return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS);
9501 }
9502 
9503 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step,
9504                                             bool Equality) {
9505   const SCEV *One = getOne(Step->getType());
9506   Delta = Equality ? getAddExpr(Delta, Step)
9507                    : getAddExpr(Delta, getMinusSCEV(Step, One));
9508   return getUDivExpr(Delta, Step);
9509 }
9510 
9511 ScalarEvolution::ExitLimit
9512 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
9513                                   const Loop *L, bool IsSigned,
9514                                   bool ControlsExit, bool AllowPredicates) {
9515   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
9516   // We handle only IV < Invariant
9517   if (!isLoopInvariant(RHS, L))
9518     return getCouldNotCompute();
9519 
9520   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
9521   bool PredicatedIV = false;
9522 
9523   if (!IV && AllowPredicates) {
9524     // Try to make this an AddRec using runtime tests, in the first X
9525     // iterations of this loop, where X is the SCEV expression found by the
9526     // algorithm below.
9527     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
9528     PredicatedIV = true;
9529   }
9530 
9531   // Avoid weird loops
9532   if (!IV || IV->getLoop() != L || !IV->isAffine())
9533     return getCouldNotCompute();
9534 
9535   bool NoWrap = ControlsExit &&
9536                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
9537 
9538   const SCEV *Stride = IV->getStepRecurrence(*this);
9539 
9540   bool PositiveStride = isKnownPositive(Stride);
9541 
9542   // Avoid negative or zero stride values.
9543   if (!PositiveStride) {
9544     // We can compute the correct backedge taken count for loops with unknown
9545     // strides if we can prove that the loop is not an infinite loop with side
9546     // effects. Here's the loop structure we are trying to handle -
9547     //
9548     // i = start
9549     // do {
9550     //   A[i] = i;
9551     //   i += s;
9552     // } while (i < end);
9553     //
9554     // The backedge taken count for such loops is evaluated as -
9555     // (max(end, start + stride) - start - 1) /u stride
9556     //
9557     // The additional preconditions that we need to check to prove correctness
9558     // of the above formula is as follows -
9559     //
9560     // a) IV is either nuw or nsw depending upon signedness (indicated by the
9561     //    NoWrap flag).
9562     // b) loop is single exit with no side effects.
9563     //
9564     //
9565     // Precondition a) implies that if the stride is negative, this is a single
9566     // trip loop. The backedge taken count formula reduces to zero in this case.
9567     //
9568     // Precondition b) implies that the unknown stride cannot be zero otherwise
9569     // we have UB.
9570     //
9571     // The positive stride case is the same as isKnownPositive(Stride) returning
9572     // true (original behavior of the function).
9573     //
9574     // We want to make sure that the stride is truly unknown as there are edge
9575     // cases where ScalarEvolution propagates no wrap flags to the
9576     // post-increment/decrement IV even though the increment/decrement operation
9577     // itself is wrapping. The computed backedge taken count may be wrong in
9578     // such cases. This is prevented by checking that the stride is not known to
9579     // be either positive or non-positive. For example, no wrap flags are
9580     // propagated to the post-increment IV of this loop with a trip count of 2 -
9581     //
9582     // unsigned char i;
9583     // for(i=127; i<128; i+=129)
9584     //   A[i] = i;
9585     //
9586     if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) ||
9587         !loopHasNoSideEffects(L))
9588       return getCouldNotCompute();
9589 
9590   } else if (!Stride->isOne() &&
9591              doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap))
9592     // Avoid proven overflow cases: this will ensure that the backedge taken
9593     // count will not generate any unsigned overflow. Relaxed no-overflow
9594     // conditions exploit NoWrapFlags, allowing to optimize in presence of
9595     // undefined behaviors like the case of C language.
9596     return getCouldNotCompute();
9597 
9598   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT
9599                                       : ICmpInst::ICMP_ULT;
9600   const SCEV *Start = IV->getStart();
9601   const SCEV *End = RHS;
9602   // If the backedge is taken at least once, then it will be taken
9603   // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start
9604   // is the LHS value of the less-than comparison the first time it is evaluated
9605   // and End is the RHS.
9606   const SCEV *BECountIfBackedgeTaken =
9607     computeBECount(getMinusSCEV(End, Start), Stride, false);
9608   // If the loop entry is guarded by the result of the backedge test of the
9609   // first loop iteration, then we know the backedge will be taken at least
9610   // once and so the backedge taken count is as above. If not then we use the
9611   // expression (max(End,Start)-Start)/Stride to describe the backedge count,
9612   // as if the backedge is taken at least once max(End,Start) is End and so the
9613   // result is as above, and if not max(End,Start) is Start so we get a backedge
9614   // count of zero.
9615   const SCEV *BECount;
9616   if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS))
9617     BECount = BECountIfBackedgeTaken;
9618   else {
9619     End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
9620     BECount = computeBECount(getMinusSCEV(End, Start), Stride, false);
9621   }
9622 
9623   const SCEV *MaxBECount;
9624   bool MaxOrZero = false;
9625   if (isa<SCEVConstant>(BECount))
9626     MaxBECount = BECount;
9627   else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) {
9628     // If we know exactly how many times the backedge will be taken if it's
9629     // taken at least once, then the backedge count will either be that or
9630     // zero.
9631     MaxBECount = BECountIfBackedgeTaken;
9632     MaxOrZero = true;
9633   } else {
9634     // Calculate the maximum backedge count based on the range of values
9635     // permitted by Start, End, and Stride.
9636     APInt MinStart = IsSigned ? getSignedRangeMin(Start)
9637                               : getUnsignedRangeMin(Start);
9638 
9639     unsigned BitWidth = getTypeSizeInBits(LHS->getType());
9640 
9641     APInt StrideForMaxBECount;
9642 
9643     if (PositiveStride)
9644       StrideForMaxBECount =
9645         IsSigned ? getSignedRangeMin(Stride)
9646                  : getUnsignedRangeMin(Stride);
9647     else
9648       // Using a stride of 1 is safe when computing max backedge taken count for
9649       // a loop with unknown stride.
9650       StrideForMaxBECount = APInt(BitWidth, 1, IsSigned);
9651 
9652     APInt Limit =
9653       IsSigned ? APInt::getSignedMaxValue(BitWidth) - (StrideForMaxBECount - 1)
9654                : APInt::getMaxValue(BitWidth) - (StrideForMaxBECount - 1);
9655 
9656     // Although End can be a MAX expression we estimate MaxEnd considering only
9657     // the case End = RHS. This is safe because in the other case (End - Start)
9658     // is zero, leading to a zero maximum backedge taken count.
9659     APInt MaxEnd =
9660       IsSigned ? APIntOps::smin(getSignedRangeMax(RHS), Limit)
9661                : APIntOps::umin(getUnsignedRangeMax(RHS), Limit);
9662 
9663     MaxBECount = computeBECount(getConstant(MaxEnd - MinStart),
9664                                 getConstant(StrideForMaxBECount), false);
9665   }
9666 
9667   if (isa<SCEVCouldNotCompute>(MaxBECount) &&
9668       !isa<SCEVCouldNotCompute>(BECount))
9669     MaxBECount = getConstant(getUnsignedRangeMax(BECount));
9670 
9671   return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates);
9672 }
9673 
9674 ScalarEvolution::ExitLimit
9675 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
9676                                      const Loop *L, bool IsSigned,
9677                                      bool ControlsExit, bool AllowPredicates) {
9678   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
9679   // We handle only IV > Invariant
9680   if (!isLoopInvariant(RHS, L))
9681     return getCouldNotCompute();
9682 
9683   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
9684   if (!IV && AllowPredicates)
9685     // Try to make this an AddRec using runtime tests, in the first X
9686     // iterations of this loop, where X is the SCEV expression found by the
9687     // algorithm below.
9688     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
9689 
9690   // Avoid weird loops
9691   if (!IV || IV->getLoop() != L || !IV->isAffine())
9692     return getCouldNotCompute();
9693 
9694   bool NoWrap = ControlsExit &&
9695                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
9696 
9697   const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
9698 
9699   // Avoid negative or zero stride values
9700   if (!isKnownPositive(Stride))
9701     return getCouldNotCompute();
9702 
9703   // Avoid proven overflow cases: this will ensure that the backedge taken count
9704   // will not generate any unsigned overflow. Relaxed no-overflow conditions
9705   // exploit NoWrapFlags, allowing to optimize in presence of undefined
9706   // behaviors like the case of C language.
9707   if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap))
9708     return getCouldNotCompute();
9709 
9710   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT
9711                                       : ICmpInst::ICMP_UGT;
9712 
9713   const SCEV *Start = IV->getStart();
9714   const SCEV *End = RHS;
9715   if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS))
9716     End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
9717 
9718   const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false);
9719 
9720   APInt MaxStart = IsSigned ? getSignedRangeMax(Start)
9721                             : getUnsignedRangeMax(Start);
9722 
9723   APInt MinStride = IsSigned ? getSignedRangeMin(Stride)
9724                              : getUnsignedRangeMin(Stride);
9725 
9726   unsigned BitWidth = getTypeSizeInBits(LHS->getType());
9727   APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
9728                          : APInt::getMinValue(BitWidth) + (MinStride - 1);
9729 
9730   // Although End can be a MIN expression we estimate MinEnd considering only
9731   // the case End = RHS. This is safe because in the other case (Start - End)
9732   // is zero, leading to a zero maximum backedge taken count.
9733   APInt MinEnd =
9734     IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit)
9735              : APIntOps::umax(getUnsignedRangeMin(RHS), Limit);
9736 
9737 
9738   const SCEV *MaxBECount = getCouldNotCompute();
9739   if (isa<SCEVConstant>(BECount))
9740     MaxBECount = BECount;
9741   else
9742     MaxBECount = computeBECount(getConstant(MaxStart - MinEnd),
9743                                 getConstant(MinStride), false);
9744 
9745   if (isa<SCEVCouldNotCompute>(MaxBECount))
9746     MaxBECount = BECount;
9747 
9748   return ExitLimit(BECount, MaxBECount, false, Predicates);
9749 }
9750 
9751 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range,
9752                                                     ScalarEvolution &SE) const {
9753   if (Range.isFullSet())  // Infinite loop.
9754     return SE.getCouldNotCompute();
9755 
9756   // If the start is a non-zero constant, shift the range to simplify things.
9757   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
9758     if (!SC->getValue()->isZero()) {
9759       SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
9760       Operands[0] = SE.getZero(SC->getType());
9761       const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
9762                                              getNoWrapFlags(FlagNW));
9763       if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
9764         return ShiftedAddRec->getNumIterationsInRange(
9765             Range.subtract(SC->getAPInt()), SE);
9766       // This is strange and shouldn't happen.
9767       return SE.getCouldNotCompute();
9768     }
9769 
9770   // The only time we can solve this is when we have all constant indices.
9771   // Otherwise, we cannot determine the overflow conditions.
9772   if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
9773     return SE.getCouldNotCompute();
9774 
9775   // Okay at this point we know that all elements of the chrec are constants and
9776   // that the start element is zero.
9777 
9778   // First check to see if the range contains zero.  If not, the first
9779   // iteration exits.
9780   unsigned BitWidth = SE.getTypeSizeInBits(getType());
9781   if (!Range.contains(APInt(BitWidth, 0)))
9782     return SE.getZero(getType());
9783 
9784   if (isAffine()) {
9785     // If this is an affine expression then we have this situation:
9786     //   Solve {0,+,A} in Range  ===  Ax in Range
9787 
9788     // We know that zero is in the range.  If A is positive then we know that
9789     // the upper value of the range must be the first possible exit value.
9790     // If A is negative then the lower of the range is the last possible loop
9791     // value.  Also note that we already checked for a full range.
9792     APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
9793     APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower();
9794 
9795     // The exit value should be (End+A)/A.
9796     APInt ExitVal = (End + A).udiv(A);
9797     ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
9798 
9799     // Evaluate at the exit value.  If we really did fall out of the valid
9800     // range, then we computed our trip count, otherwise wrap around or other
9801     // things must have happened.
9802     ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
9803     if (Range.contains(Val->getValue()))
9804       return SE.getCouldNotCompute();  // Something strange happened
9805 
9806     // Ensure that the previous value is in the range.  This is a sanity check.
9807     assert(Range.contains(
9808            EvaluateConstantChrecAtConstant(this,
9809            ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&
9810            "Linear scev computation is off in a bad way!");
9811     return SE.getConstant(ExitValue);
9812   } else if (isQuadratic()) {
9813     // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
9814     // quadratic equation to solve it.  To do this, we must frame our problem in
9815     // terms of figuring out when zero is crossed, instead of when
9816     // Range.getUpper() is crossed.
9817     SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
9818     NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
9819     const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(), FlagAnyWrap);
9820 
9821     // Next, solve the constructed addrec
9822     if (auto Roots =
9823             SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE)) {
9824       const SCEVConstant *R1 = Roots->first;
9825       const SCEVConstant *R2 = Roots->second;
9826       // Pick the smallest positive root value.
9827       if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
9828               ICmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
9829         if (!CB->getZExtValue())
9830           std::swap(R1, R2); // R1 is the minimum root now.
9831 
9832         // Make sure the root is not off by one.  The returned iteration should
9833         // not be in the range, but the previous one should be.  When solving
9834         // for "X*X < 5", for example, we should not return a root of 2.
9835         ConstantInt *R1Val =
9836             EvaluateConstantChrecAtConstant(this, R1->getValue(), SE);
9837         if (Range.contains(R1Val->getValue())) {
9838           // The next iteration must be out of the range...
9839           ConstantInt *NextVal =
9840               ConstantInt::get(SE.getContext(), R1->getAPInt() + 1);
9841 
9842           R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
9843           if (!Range.contains(R1Val->getValue()))
9844             return SE.getConstant(NextVal);
9845           return SE.getCouldNotCompute(); // Something strange happened
9846         }
9847 
9848         // If R1 was not in the range, then it is a good return value.  Make
9849         // sure that R1-1 WAS in the range though, just in case.
9850         ConstantInt *NextVal =
9851             ConstantInt::get(SE.getContext(), R1->getAPInt() - 1);
9852         R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
9853         if (Range.contains(R1Val->getValue()))
9854           return R1;
9855         return SE.getCouldNotCompute(); // Something strange happened
9856       }
9857     }
9858   }
9859 
9860   return SE.getCouldNotCompute();
9861 }
9862 
9863 // Return true when S contains at least an undef value.
9864 static inline bool containsUndefs(const SCEV *S) {
9865   return SCEVExprContains(S, [](const SCEV *S) {
9866     if (const auto *SU = dyn_cast<SCEVUnknown>(S))
9867       return isa<UndefValue>(SU->getValue());
9868     else if (const auto *SC = dyn_cast<SCEVConstant>(S))
9869       return isa<UndefValue>(SC->getValue());
9870     return false;
9871   });
9872 }
9873 
9874 namespace {
9875 // Collect all steps of SCEV expressions.
9876 struct SCEVCollectStrides {
9877   ScalarEvolution &SE;
9878   SmallVectorImpl<const SCEV *> &Strides;
9879 
9880   SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S)
9881       : SE(SE), Strides(S) {}
9882 
9883   bool follow(const SCEV *S) {
9884     if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
9885       Strides.push_back(AR->getStepRecurrence(SE));
9886     return true;
9887   }
9888   bool isDone() const { return false; }
9889 };
9890 
9891 // Collect all SCEVUnknown and SCEVMulExpr expressions.
9892 struct SCEVCollectTerms {
9893   SmallVectorImpl<const SCEV *> &Terms;
9894 
9895   SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T)
9896       : Terms(T) {}
9897 
9898   bool follow(const SCEV *S) {
9899     if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) ||
9900         isa<SCEVSignExtendExpr>(S)) {
9901       if (!containsUndefs(S))
9902         Terms.push_back(S);
9903 
9904       // Stop recursion: once we collected a term, do not walk its operands.
9905       return false;
9906     }
9907 
9908     // Keep looking.
9909     return true;
9910   }
9911   bool isDone() const { return false; }
9912 };
9913 
9914 // Check if a SCEV contains an AddRecExpr.
9915 struct SCEVHasAddRec {
9916   bool &ContainsAddRec;
9917 
9918   SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) {
9919    ContainsAddRec = false;
9920   }
9921 
9922   bool follow(const SCEV *S) {
9923     if (isa<SCEVAddRecExpr>(S)) {
9924       ContainsAddRec = true;
9925 
9926       // Stop recursion: once we collected a term, do not walk its operands.
9927       return false;
9928     }
9929 
9930     // Keep looking.
9931     return true;
9932   }
9933   bool isDone() const { return false; }
9934 };
9935 
9936 // Find factors that are multiplied with an expression that (possibly as a
9937 // subexpression) contains an AddRecExpr. In the expression:
9938 //
9939 //  8 * (100 +  %p * %q * (%a + {0, +, 1}_loop))
9940 //
9941 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)"
9942 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size
9943 // parameters as they form a product with an induction variable.
9944 //
9945 // This collector expects all array size parameters to be in the same MulExpr.
9946 // It might be necessary to later add support for collecting parameters that are
9947 // spread over different nested MulExpr.
9948 struct SCEVCollectAddRecMultiplies {
9949   SmallVectorImpl<const SCEV *> &Terms;
9950   ScalarEvolution &SE;
9951 
9952   SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE)
9953       : Terms(T), SE(SE) {}
9954 
9955   bool follow(const SCEV *S) {
9956     if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) {
9957       bool HasAddRec = false;
9958       SmallVector<const SCEV *, 0> Operands;
9959       for (auto Op : Mul->operands()) {
9960         const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op);
9961         if (Unknown && !isa<CallInst>(Unknown->getValue())) {
9962           Operands.push_back(Op);
9963         } else if (Unknown) {
9964           HasAddRec = true;
9965         } else {
9966           bool ContainsAddRec;
9967           SCEVHasAddRec ContiansAddRec(ContainsAddRec);
9968           visitAll(Op, ContiansAddRec);
9969           HasAddRec |= ContainsAddRec;
9970         }
9971       }
9972       if (Operands.size() == 0)
9973         return true;
9974 
9975       if (!HasAddRec)
9976         return false;
9977 
9978       Terms.push_back(SE.getMulExpr(Operands));
9979       // Stop recursion: once we collected a term, do not walk its operands.
9980       return false;
9981     }
9982 
9983     // Keep looking.
9984     return true;
9985   }
9986   bool isDone() const { return false; }
9987 };
9988 }
9989 
9990 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in
9991 /// two places:
9992 ///   1) The strides of AddRec expressions.
9993 ///   2) Unknowns that are multiplied with AddRec expressions.
9994 void ScalarEvolution::collectParametricTerms(const SCEV *Expr,
9995     SmallVectorImpl<const SCEV *> &Terms) {
9996   SmallVector<const SCEV *, 4> Strides;
9997   SCEVCollectStrides StrideCollector(*this, Strides);
9998   visitAll(Expr, StrideCollector);
9999 
10000   DEBUG({
10001       dbgs() << "Strides:\n";
10002       for (const SCEV *S : Strides)
10003         dbgs() << *S << "\n";
10004     });
10005 
10006   for (const SCEV *S : Strides) {
10007     SCEVCollectTerms TermCollector(Terms);
10008     visitAll(S, TermCollector);
10009   }
10010 
10011   DEBUG({
10012       dbgs() << "Terms:\n";
10013       for (const SCEV *T : Terms)
10014         dbgs() << *T << "\n";
10015     });
10016 
10017   SCEVCollectAddRecMultiplies MulCollector(Terms, *this);
10018   visitAll(Expr, MulCollector);
10019 }
10020 
10021 static bool findArrayDimensionsRec(ScalarEvolution &SE,
10022                                    SmallVectorImpl<const SCEV *> &Terms,
10023                                    SmallVectorImpl<const SCEV *> &Sizes) {
10024   int Last = Terms.size() - 1;
10025   const SCEV *Step = Terms[Last];
10026 
10027   // End of recursion.
10028   if (Last == 0) {
10029     if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) {
10030       SmallVector<const SCEV *, 2> Qs;
10031       for (const SCEV *Op : M->operands())
10032         if (!isa<SCEVConstant>(Op))
10033           Qs.push_back(Op);
10034 
10035       Step = SE.getMulExpr(Qs);
10036     }
10037 
10038     Sizes.push_back(Step);
10039     return true;
10040   }
10041 
10042   for (const SCEV *&Term : Terms) {
10043     // Normalize the terms before the next call to findArrayDimensionsRec.
10044     const SCEV *Q, *R;
10045     SCEVDivision::divide(SE, Term, Step, &Q, &R);
10046 
10047     // Bail out when GCD does not evenly divide one of the terms.
10048     if (!R->isZero())
10049       return false;
10050 
10051     Term = Q;
10052   }
10053 
10054   // Remove all SCEVConstants.
10055   Terms.erase(
10056       remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }),
10057       Terms.end());
10058 
10059   if (Terms.size() > 0)
10060     if (!findArrayDimensionsRec(SE, Terms, Sizes))
10061       return false;
10062 
10063   Sizes.push_back(Step);
10064   return true;
10065 }
10066 
10067 
10068 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter.
10069 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) {
10070   for (const SCEV *T : Terms)
10071     if (SCEVExprContains(T, isa<SCEVUnknown, const SCEV *>))
10072       return true;
10073   return false;
10074 }
10075 
10076 // Return the number of product terms in S.
10077 static inline int numberOfTerms(const SCEV *S) {
10078   if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S))
10079     return Expr->getNumOperands();
10080   return 1;
10081 }
10082 
10083 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) {
10084   if (isa<SCEVConstant>(T))
10085     return nullptr;
10086 
10087   if (isa<SCEVUnknown>(T))
10088     return T;
10089 
10090   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) {
10091     SmallVector<const SCEV *, 2> Factors;
10092     for (const SCEV *Op : M->operands())
10093       if (!isa<SCEVConstant>(Op))
10094         Factors.push_back(Op);
10095 
10096     return SE.getMulExpr(Factors);
10097   }
10098 
10099   return T;
10100 }
10101 
10102 /// Return the size of an element read or written by Inst.
10103 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
10104   Type *Ty;
10105   if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
10106     Ty = Store->getValueOperand()->getType();
10107   else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
10108     Ty = Load->getType();
10109   else
10110     return nullptr;
10111 
10112   Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
10113   return getSizeOfExpr(ETy, Ty);
10114 }
10115 
10116 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
10117                                           SmallVectorImpl<const SCEV *> &Sizes,
10118                                           const SCEV *ElementSize) {
10119   if (Terms.size() < 1 || !ElementSize)
10120     return;
10121 
10122   // Early return when Terms do not contain parameters: we do not delinearize
10123   // non parametric SCEVs.
10124   if (!containsParameters(Terms))
10125     return;
10126 
10127   DEBUG({
10128       dbgs() << "Terms:\n";
10129       for (const SCEV *T : Terms)
10130         dbgs() << *T << "\n";
10131     });
10132 
10133   // Remove duplicates.
10134   array_pod_sort(Terms.begin(), Terms.end());
10135   Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end());
10136 
10137   // Put larger terms first.
10138   std::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) {
10139     return numberOfTerms(LHS) > numberOfTerms(RHS);
10140   });
10141 
10142   // Try to divide all terms by the element size. If term is not divisible by
10143   // element size, proceed with the original term.
10144   for (const SCEV *&Term : Terms) {
10145     const SCEV *Q, *R;
10146     SCEVDivision::divide(*this, Term, ElementSize, &Q, &R);
10147     if (!Q->isZero())
10148       Term = Q;
10149   }
10150 
10151   SmallVector<const SCEV *, 4> NewTerms;
10152 
10153   // Remove constant factors.
10154   for (const SCEV *T : Terms)
10155     if (const SCEV *NewT = removeConstantFactors(*this, T))
10156       NewTerms.push_back(NewT);
10157 
10158   DEBUG({
10159       dbgs() << "Terms after sorting:\n";
10160       for (const SCEV *T : NewTerms)
10161         dbgs() << *T << "\n";
10162     });
10163 
10164   if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) {
10165     Sizes.clear();
10166     return;
10167   }
10168 
10169   // The last element to be pushed into Sizes is the size of an element.
10170   Sizes.push_back(ElementSize);
10171 
10172   DEBUG({
10173       dbgs() << "Sizes:\n";
10174       for (const SCEV *S : Sizes)
10175         dbgs() << *S << "\n";
10176     });
10177 }
10178 
10179 void ScalarEvolution::computeAccessFunctions(
10180     const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts,
10181     SmallVectorImpl<const SCEV *> &Sizes) {
10182 
10183   // Early exit in case this SCEV is not an affine multivariate function.
10184   if (Sizes.empty())
10185     return;
10186 
10187   if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr))
10188     if (!AR->isAffine())
10189       return;
10190 
10191   const SCEV *Res = Expr;
10192   int Last = Sizes.size() - 1;
10193   for (int i = Last; i >= 0; i--) {
10194     const SCEV *Q, *R;
10195     SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R);
10196 
10197     DEBUG({
10198         dbgs() << "Res: " << *Res << "\n";
10199         dbgs() << "Sizes[i]: " << *Sizes[i] << "\n";
10200         dbgs() << "Res divided by Sizes[i]:\n";
10201         dbgs() << "Quotient: " << *Q << "\n";
10202         dbgs() << "Remainder: " << *R << "\n";
10203       });
10204 
10205     Res = Q;
10206 
10207     // Do not record the last subscript corresponding to the size of elements in
10208     // the array.
10209     if (i == Last) {
10210 
10211       // Bail out if the remainder is too complex.
10212       if (isa<SCEVAddRecExpr>(R)) {
10213         Subscripts.clear();
10214         Sizes.clear();
10215         return;
10216       }
10217 
10218       continue;
10219     }
10220 
10221     // Record the access function for the current subscript.
10222     Subscripts.push_back(R);
10223   }
10224 
10225   // Also push in last position the remainder of the last division: it will be
10226   // the access function of the innermost dimension.
10227   Subscripts.push_back(Res);
10228 
10229   std::reverse(Subscripts.begin(), Subscripts.end());
10230 
10231   DEBUG({
10232       dbgs() << "Subscripts:\n";
10233       for (const SCEV *S : Subscripts)
10234         dbgs() << *S << "\n";
10235     });
10236 }
10237 
10238 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and
10239 /// sizes of an array access. Returns the remainder of the delinearization that
10240 /// is the offset start of the array.  The SCEV->delinearize algorithm computes
10241 /// the multiples of SCEV coefficients: that is a pattern matching of sub
10242 /// expressions in the stride and base of a SCEV corresponding to the
10243 /// computation of a GCD (greatest common divisor) of base and stride.  When
10244 /// SCEV->delinearize fails, it returns the SCEV unchanged.
10245 ///
10246 /// For example: when analyzing the memory access A[i][j][k] in this loop nest
10247 ///
10248 ///  void foo(long n, long m, long o, double A[n][m][o]) {
10249 ///
10250 ///    for (long i = 0; i < n; i++)
10251 ///      for (long j = 0; j < m; j++)
10252 ///        for (long k = 0; k < o; k++)
10253 ///          A[i][j][k] = 1.0;
10254 ///  }
10255 ///
10256 /// the delinearization input is the following AddRec SCEV:
10257 ///
10258 ///  AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k>
10259 ///
10260 /// From this SCEV, we are able to say that the base offset of the access is %A
10261 /// because it appears as an offset that does not divide any of the strides in
10262 /// the loops:
10263 ///
10264 ///  CHECK: Base offset: %A
10265 ///
10266 /// and then SCEV->delinearize determines the size of some of the dimensions of
10267 /// the array as these are the multiples by which the strides are happening:
10268 ///
10269 ///  CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes.
10270 ///
10271 /// Note that the outermost dimension remains of UnknownSize because there are
10272 /// no strides that would help identifying the size of the last dimension: when
10273 /// the array has been statically allocated, one could compute the size of that
10274 /// dimension by dividing the overall size of the array by the size of the known
10275 /// dimensions: %m * %o * 8.
10276 ///
10277 /// Finally delinearize provides the access functions for the array reference
10278 /// that does correspond to A[i][j][k] of the above C testcase:
10279 ///
10280 ///  CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>]
10281 ///
10282 /// The testcases are checking the output of a function pass:
10283 /// DelinearizationPass that walks through all loads and stores of a function
10284 /// asking for the SCEV of the memory access with respect to all enclosing
10285 /// loops, calling SCEV->delinearize on that and printing the results.
10286 
10287 void ScalarEvolution::delinearize(const SCEV *Expr,
10288                                  SmallVectorImpl<const SCEV *> &Subscripts,
10289                                  SmallVectorImpl<const SCEV *> &Sizes,
10290                                  const SCEV *ElementSize) {
10291   // First step: collect parametric terms.
10292   SmallVector<const SCEV *, 4> Terms;
10293   collectParametricTerms(Expr, Terms);
10294 
10295   if (Terms.empty())
10296     return;
10297 
10298   // Second step: find subscript sizes.
10299   findArrayDimensions(Terms, Sizes, ElementSize);
10300 
10301   if (Sizes.empty())
10302     return;
10303 
10304   // Third step: compute the access functions for each subscript.
10305   computeAccessFunctions(Expr, Subscripts, Sizes);
10306 
10307   if (Subscripts.empty())
10308     return;
10309 
10310   DEBUG({
10311       dbgs() << "succeeded to delinearize " << *Expr << "\n";
10312       dbgs() << "ArrayDecl[UnknownSize]";
10313       for (const SCEV *S : Sizes)
10314         dbgs() << "[" << *S << "]";
10315 
10316       dbgs() << "\nArrayRef";
10317       for (const SCEV *S : Subscripts)
10318         dbgs() << "[" << *S << "]";
10319       dbgs() << "\n";
10320     });
10321 }
10322 
10323 //===----------------------------------------------------------------------===//
10324 //                   SCEVCallbackVH Class Implementation
10325 //===----------------------------------------------------------------------===//
10326 
10327 void ScalarEvolution::SCEVCallbackVH::deleted() {
10328   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
10329   if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
10330     SE->ConstantEvolutionLoopExitValue.erase(PN);
10331   SE->eraseValueFromMap(getValPtr());
10332   // this now dangles!
10333 }
10334 
10335 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
10336   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
10337 
10338   // Forget all the expressions associated with users of the old value,
10339   // so that future queries will recompute the expressions using the new
10340   // value.
10341   Value *Old = getValPtr();
10342   SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end());
10343   SmallPtrSet<User *, 8> Visited;
10344   while (!Worklist.empty()) {
10345     User *U = Worklist.pop_back_val();
10346     // Deleting the Old value will cause this to dangle. Postpone
10347     // that until everything else is done.
10348     if (U == Old)
10349       continue;
10350     if (!Visited.insert(U).second)
10351       continue;
10352     if (PHINode *PN = dyn_cast<PHINode>(U))
10353       SE->ConstantEvolutionLoopExitValue.erase(PN);
10354     SE->eraseValueFromMap(U);
10355     Worklist.insert(Worklist.end(), U->user_begin(), U->user_end());
10356   }
10357   // Delete the Old value.
10358   if (PHINode *PN = dyn_cast<PHINode>(Old))
10359     SE->ConstantEvolutionLoopExitValue.erase(PN);
10360   SE->eraseValueFromMap(Old);
10361   // this now dangles!
10362 }
10363 
10364 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
10365   : CallbackVH(V), SE(se) {}
10366 
10367 //===----------------------------------------------------------------------===//
10368 //                   ScalarEvolution Class Implementation
10369 //===----------------------------------------------------------------------===//
10370 
10371 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
10372                                  AssumptionCache &AC, DominatorTree &DT,
10373                                  LoopInfo &LI)
10374     : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
10375       CouldNotCompute(new SCEVCouldNotCompute()),
10376       WalkingBEDominatingConds(false), ProvingSplitPredicate(false),
10377       ValuesAtScopes(64), LoopDispositions(64), BlockDispositions(64),
10378       FirstUnknown(nullptr) {
10379 
10380   // To use guards for proving predicates, we need to scan every instruction in
10381   // relevant basic blocks, and not just terminators.  Doing this is a waste of
10382   // time if the IR does not actually contain any calls to
10383   // @llvm.experimental.guard, so do a quick check and remember this beforehand.
10384   //
10385   // This pessimizes the case where a pass that preserves ScalarEvolution wants
10386   // to _add_ guards to the module when there weren't any before, and wants
10387   // ScalarEvolution to optimize based on those guards.  For now we prefer to be
10388   // efficient in lieu of being smart in that rather obscure case.
10389 
10390   auto *GuardDecl = F.getParent()->getFunction(
10391       Intrinsic::getName(Intrinsic::experimental_guard));
10392   HasGuards = GuardDecl && !GuardDecl->use_empty();
10393 }
10394 
10395 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
10396     : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT),
10397       LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
10398       ValueExprMap(std::move(Arg.ValueExprMap)),
10399       PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
10400       WalkingBEDominatingConds(false), ProvingSplitPredicate(false),
10401       MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)),
10402       BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
10403       PredicatedBackedgeTakenCounts(
10404           std::move(Arg.PredicatedBackedgeTakenCounts)),
10405       ExitLimits(std::move(Arg.ExitLimits)),
10406       ConstantEvolutionLoopExitValue(
10407           std::move(Arg.ConstantEvolutionLoopExitValue)),
10408       ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
10409       LoopDispositions(std::move(Arg.LoopDispositions)),
10410       LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
10411       BlockDispositions(std::move(Arg.BlockDispositions)),
10412       UnsignedRanges(std::move(Arg.UnsignedRanges)),
10413       SignedRanges(std::move(Arg.SignedRanges)),
10414       UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
10415       UniquePreds(std::move(Arg.UniquePreds)),
10416       SCEVAllocator(std::move(Arg.SCEVAllocator)),
10417       PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)),
10418       FirstUnknown(Arg.FirstUnknown) {
10419   Arg.FirstUnknown = nullptr;
10420 }
10421 
10422 ScalarEvolution::~ScalarEvolution() {
10423   // Iterate through all the SCEVUnknown instances and call their
10424   // destructors, so that they release their references to their values.
10425   for (SCEVUnknown *U = FirstUnknown; U;) {
10426     SCEVUnknown *Tmp = U;
10427     U = U->Next;
10428     Tmp->~SCEVUnknown();
10429   }
10430   FirstUnknown = nullptr;
10431 
10432   ExprValueMap.clear();
10433   ValueExprMap.clear();
10434   HasRecMap.clear();
10435 
10436   // Free any extra memory created for ExitNotTakenInfo in the unlikely event
10437   // that a loop had multiple computable exits.
10438   for (auto &BTCI : BackedgeTakenCounts)
10439     BTCI.second.clear();
10440   for (auto &BTCI : PredicatedBackedgeTakenCounts)
10441     BTCI.second.clear();
10442 
10443   assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
10444   assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
10445   assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
10446 }
10447 
10448 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
10449   return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
10450 }
10451 
10452 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
10453                           const Loop *L) {
10454   // Print all inner loops first
10455   for (Loop *I : *L)
10456     PrintLoopInfo(OS, SE, I);
10457 
10458   OS << "Loop ";
10459   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
10460   OS << ": ";
10461 
10462   SmallVector<BasicBlock *, 8> ExitBlocks;
10463   L->getExitBlocks(ExitBlocks);
10464   if (ExitBlocks.size() != 1)
10465     OS << "<multiple exits> ";
10466 
10467   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
10468     OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
10469   } else {
10470     OS << "Unpredictable backedge-taken count. ";
10471   }
10472 
10473   OS << "\n"
10474         "Loop ";
10475   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
10476   OS << ": ";
10477 
10478   if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
10479     OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
10480     if (SE->isBackedgeTakenCountMaxOrZero(L))
10481       OS << ", actual taken count either this or zero.";
10482   } else {
10483     OS << "Unpredictable max backedge-taken count. ";
10484   }
10485 
10486   OS << "\n"
10487         "Loop ";
10488   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
10489   OS << ": ";
10490 
10491   SCEVUnionPredicate Pred;
10492   auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred);
10493   if (!isa<SCEVCouldNotCompute>(PBT)) {
10494     OS << "Predicated backedge-taken count is " << *PBT << "\n";
10495     OS << " Predicates:\n";
10496     Pred.print(OS, 4);
10497   } else {
10498     OS << "Unpredictable predicated backedge-taken count. ";
10499   }
10500   OS << "\n";
10501 
10502   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
10503     OS << "Loop ";
10504     L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
10505     OS << ": ";
10506     OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
10507   }
10508 }
10509 
10510 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) {
10511   switch (LD) {
10512   case ScalarEvolution::LoopVariant:
10513     return "Variant";
10514   case ScalarEvolution::LoopInvariant:
10515     return "Invariant";
10516   case ScalarEvolution::LoopComputable:
10517     return "Computable";
10518   }
10519   llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!");
10520 }
10521 
10522 void ScalarEvolution::print(raw_ostream &OS) const {
10523   // ScalarEvolution's implementation of the print method is to print
10524   // out SCEV values of all instructions that are interesting. Doing
10525   // this potentially causes it to create new SCEV objects though,
10526   // which technically conflicts with the const qualifier. This isn't
10527   // observable from outside the class though, so casting away the
10528   // const isn't dangerous.
10529   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
10530 
10531   OS << "Classifying expressions for: ";
10532   F.printAsOperand(OS, /*PrintType=*/false);
10533   OS << "\n";
10534   for (Instruction &I : instructions(F))
10535     if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
10536       OS << I << '\n';
10537       OS << "  -->  ";
10538       const SCEV *SV = SE.getSCEV(&I);
10539       SV->print(OS);
10540       if (!isa<SCEVCouldNotCompute>(SV)) {
10541         OS << " U: ";
10542         SE.getUnsignedRange(SV).print(OS);
10543         OS << " S: ";
10544         SE.getSignedRange(SV).print(OS);
10545       }
10546 
10547       const Loop *L = LI.getLoopFor(I.getParent());
10548 
10549       const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
10550       if (AtUse != SV) {
10551         OS << "  -->  ";
10552         AtUse->print(OS);
10553         if (!isa<SCEVCouldNotCompute>(AtUse)) {
10554           OS << " U: ";
10555           SE.getUnsignedRange(AtUse).print(OS);
10556           OS << " S: ";
10557           SE.getSignedRange(AtUse).print(OS);
10558         }
10559       }
10560 
10561       if (L) {
10562         OS << "\t\t" "Exits: ";
10563         const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
10564         if (!SE.isLoopInvariant(ExitValue, L)) {
10565           OS << "<<Unknown>>";
10566         } else {
10567           OS << *ExitValue;
10568         }
10569 
10570         bool First = true;
10571         for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
10572           if (First) {
10573             OS << "\t\t" "LoopDispositions: { ";
10574             First = false;
10575           } else {
10576             OS << ", ";
10577           }
10578 
10579           Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
10580           OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter));
10581         }
10582 
10583         for (auto *InnerL : depth_first(L)) {
10584           if (InnerL == L)
10585             continue;
10586           if (First) {
10587             OS << "\t\t" "LoopDispositions: { ";
10588             First = false;
10589           } else {
10590             OS << ", ";
10591           }
10592 
10593           InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
10594           OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL));
10595         }
10596 
10597         OS << " }";
10598       }
10599 
10600       OS << "\n";
10601     }
10602 
10603   OS << "Determining loop execution counts for: ";
10604   F.printAsOperand(OS, /*PrintType=*/false);
10605   OS << "\n";
10606   for (Loop *I : LI)
10607     PrintLoopInfo(OS, &SE, I);
10608 }
10609 
10610 ScalarEvolution::LoopDisposition
10611 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
10612   auto &Values = LoopDispositions[S];
10613   for (auto &V : Values) {
10614     if (V.getPointer() == L)
10615       return V.getInt();
10616   }
10617   Values.emplace_back(L, LoopVariant);
10618   LoopDisposition D = computeLoopDisposition(S, L);
10619   auto &Values2 = LoopDispositions[S];
10620   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
10621     if (V.getPointer() == L) {
10622       V.setInt(D);
10623       break;
10624     }
10625   }
10626   return D;
10627 }
10628 
10629 ScalarEvolution::LoopDisposition
10630 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
10631   switch (static_cast<SCEVTypes>(S->getSCEVType())) {
10632   case scConstant:
10633     return LoopInvariant;
10634   case scTruncate:
10635   case scZeroExtend:
10636   case scSignExtend:
10637     return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
10638   case scAddRecExpr: {
10639     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
10640 
10641     // If L is the addrec's loop, it's computable.
10642     if (AR->getLoop() == L)
10643       return LoopComputable;
10644 
10645     // Add recurrences are never invariant in the function-body (null loop).
10646     if (!L)
10647       return LoopVariant;
10648 
10649     // This recurrence is variant w.r.t. L if L contains AR's loop.
10650     if (L->contains(AR->getLoop()))
10651       return LoopVariant;
10652 
10653     // This recurrence is invariant w.r.t. L if AR's loop contains L.
10654     if (AR->getLoop()->contains(L))
10655       return LoopInvariant;
10656 
10657     // This recurrence is variant w.r.t. L if any of its operands
10658     // are variant.
10659     for (auto *Op : AR->operands())
10660       if (!isLoopInvariant(Op, L))
10661         return LoopVariant;
10662 
10663     // Otherwise it's loop-invariant.
10664     return LoopInvariant;
10665   }
10666   case scAddExpr:
10667   case scMulExpr:
10668   case scUMaxExpr:
10669   case scSMaxExpr: {
10670     bool HasVarying = false;
10671     for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) {
10672       LoopDisposition D = getLoopDisposition(Op, L);
10673       if (D == LoopVariant)
10674         return LoopVariant;
10675       if (D == LoopComputable)
10676         HasVarying = true;
10677     }
10678     return HasVarying ? LoopComputable : LoopInvariant;
10679   }
10680   case scUDivExpr: {
10681     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
10682     LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
10683     if (LD == LoopVariant)
10684       return LoopVariant;
10685     LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
10686     if (RD == LoopVariant)
10687       return LoopVariant;
10688     return (LD == LoopInvariant && RD == LoopInvariant) ?
10689            LoopInvariant : LoopComputable;
10690   }
10691   case scUnknown:
10692     // All non-instruction values are loop invariant.  All instructions are loop
10693     // invariant if they are not contained in the specified loop.
10694     // Instructions are never considered invariant in the function body
10695     // (null loop) because they are defined within the "loop".
10696     if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
10697       return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
10698     return LoopInvariant;
10699   case scCouldNotCompute:
10700     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
10701   }
10702   llvm_unreachable("Unknown SCEV kind!");
10703 }
10704 
10705 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
10706   return getLoopDisposition(S, L) == LoopInvariant;
10707 }
10708 
10709 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
10710   return getLoopDisposition(S, L) == LoopComputable;
10711 }
10712 
10713 ScalarEvolution::BlockDisposition
10714 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
10715   auto &Values = BlockDispositions[S];
10716   for (auto &V : Values) {
10717     if (V.getPointer() == BB)
10718       return V.getInt();
10719   }
10720   Values.emplace_back(BB, DoesNotDominateBlock);
10721   BlockDisposition D = computeBlockDisposition(S, BB);
10722   auto &Values2 = BlockDispositions[S];
10723   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
10724     if (V.getPointer() == BB) {
10725       V.setInt(D);
10726       break;
10727     }
10728   }
10729   return D;
10730 }
10731 
10732 ScalarEvolution::BlockDisposition
10733 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
10734   switch (static_cast<SCEVTypes>(S->getSCEVType())) {
10735   case scConstant:
10736     return ProperlyDominatesBlock;
10737   case scTruncate:
10738   case scZeroExtend:
10739   case scSignExtend:
10740     return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
10741   case scAddRecExpr: {
10742     // This uses a "dominates" query instead of "properly dominates" query
10743     // to test for proper dominance too, because the instruction which
10744     // produces the addrec's value is a PHI, and a PHI effectively properly
10745     // dominates its entire containing block.
10746     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
10747     if (!DT.dominates(AR->getLoop()->getHeader(), BB))
10748       return DoesNotDominateBlock;
10749 
10750     // Fall through into SCEVNAryExpr handling.
10751     LLVM_FALLTHROUGH;
10752   }
10753   case scAddExpr:
10754   case scMulExpr:
10755   case scUMaxExpr:
10756   case scSMaxExpr: {
10757     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
10758     bool Proper = true;
10759     for (const SCEV *NAryOp : NAry->operands()) {
10760       BlockDisposition D = getBlockDisposition(NAryOp, BB);
10761       if (D == DoesNotDominateBlock)
10762         return DoesNotDominateBlock;
10763       if (D == DominatesBlock)
10764         Proper = false;
10765     }
10766     return Proper ? ProperlyDominatesBlock : DominatesBlock;
10767   }
10768   case scUDivExpr: {
10769     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
10770     const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
10771     BlockDisposition LD = getBlockDisposition(LHS, BB);
10772     if (LD == DoesNotDominateBlock)
10773       return DoesNotDominateBlock;
10774     BlockDisposition RD = getBlockDisposition(RHS, BB);
10775     if (RD == DoesNotDominateBlock)
10776       return DoesNotDominateBlock;
10777     return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
10778       ProperlyDominatesBlock : DominatesBlock;
10779   }
10780   case scUnknown:
10781     if (Instruction *I =
10782           dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
10783       if (I->getParent() == BB)
10784         return DominatesBlock;
10785       if (DT.properlyDominates(I->getParent(), BB))
10786         return ProperlyDominatesBlock;
10787       return DoesNotDominateBlock;
10788     }
10789     return ProperlyDominatesBlock;
10790   case scCouldNotCompute:
10791     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
10792   }
10793   llvm_unreachable("Unknown SCEV kind!");
10794 }
10795 
10796 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
10797   return getBlockDisposition(S, BB) >= DominatesBlock;
10798 }
10799 
10800 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
10801   return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
10802 }
10803 
10804 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
10805   return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; });
10806 }
10807 
10808 void ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
10809   ValuesAtScopes.erase(S);
10810   LoopDispositions.erase(S);
10811   BlockDispositions.erase(S);
10812   UnsignedRanges.erase(S);
10813   SignedRanges.erase(S);
10814   ExprValueMap.erase(S);
10815   HasRecMap.erase(S);
10816   MinTrailingZerosCache.erase(S);
10817 
10818   for (auto I = PredicatedSCEVRewrites.begin();
10819        I != PredicatedSCEVRewrites.end();) {
10820     std::pair<const SCEV *, const Loop *> Entry = I->first;
10821     if (Entry.first == S)
10822       PredicatedSCEVRewrites.erase(I++);
10823     else
10824       ++I;
10825   }
10826 
10827   auto RemoveSCEVFromBackedgeMap =
10828       [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
10829         for (auto I = Map.begin(), E = Map.end(); I != E;) {
10830           BackedgeTakenInfo &BEInfo = I->second;
10831           if (BEInfo.hasOperand(S, this)) {
10832             BEInfo.clear();
10833             Map.erase(I++);
10834           } else
10835             ++I;
10836         }
10837       };
10838 
10839   RemoveSCEVFromBackedgeMap(BackedgeTakenCounts);
10840   RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts);
10841 }
10842 
10843 void ScalarEvolution::verify() const {
10844   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
10845   ScalarEvolution SE2(F, TLI, AC, DT, LI);
10846 
10847   SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end());
10848 
10849   // Map's SCEV expressions from one ScalarEvolution "universe" to another.
10850   struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> {
10851     const SCEV *visitConstant(const SCEVConstant *Constant) {
10852       return SE.getConstant(Constant->getAPInt());
10853     }
10854     const SCEV *visitUnknown(const SCEVUnknown *Expr) {
10855       return SE.getUnknown(Expr->getValue());
10856     }
10857 
10858     const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
10859       return SE.getCouldNotCompute();
10860     }
10861     SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {}
10862   };
10863 
10864   SCEVMapper SCM(SE2);
10865 
10866   while (!LoopStack.empty()) {
10867     auto *L = LoopStack.pop_back_val();
10868     LoopStack.insert(LoopStack.end(), L->begin(), L->end());
10869 
10870     auto *CurBECount = SCM.visit(
10871         const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L));
10872     auto *NewBECount = SE2.getBackedgeTakenCount(L);
10873 
10874     if (CurBECount == SE2.getCouldNotCompute() ||
10875         NewBECount == SE2.getCouldNotCompute()) {
10876       // NB! This situation is legal, but is very suspicious -- whatever pass
10877       // change the loop to make a trip count go from could not compute to
10878       // computable or vice-versa *should have* invalidated SCEV.  However, we
10879       // choose not to assert here (for now) since we don't want false
10880       // positives.
10881       continue;
10882     }
10883 
10884     if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) {
10885       // SCEV treats "undef" as an unknown but consistent value (i.e. it does
10886       // not propagate undef aggressively).  This means we can (and do) fail
10887       // verification in cases where a transform makes the trip count of a loop
10888       // go from "undef" to "undef+1" (say).  The transform is fine, since in
10889       // both cases the loop iterates "undef" times, but SCEV thinks we
10890       // increased the trip count of the loop by 1 incorrectly.
10891       continue;
10892     }
10893 
10894     if (SE.getTypeSizeInBits(CurBECount->getType()) >
10895         SE.getTypeSizeInBits(NewBECount->getType()))
10896       NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType());
10897     else if (SE.getTypeSizeInBits(CurBECount->getType()) <
10898              SE.getTypeSizeInBits(NewBECount->getType()))
10899       CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType());
10900 
10901     auto *ConstantDelta =
10902         dyn_cast<SCEVConstant>(SE2.getMinusSCEV(CurBECount, NewBECount));
10903 
10904     if (ConstantDelta && ConstantDelta->getAPInt() != 0) {
10905       dbgs() << "Trip Count Changed!\n";
10906       dbgs() << "Old: " << *CurBECount << "\n";
10907       dbgs() << "New: " << *NewBECount << "\n";
10908       dbgs() << "Delta: " << *ConstantDelta << "\n";
10909       std::abort();
10910     }
10911   }
10912 }
10913 
10914 bool ScalarEvolution::invalidate(
10915     Function &F, const PreservedAnalyses &PA,
10916     FunctionAnalysisManager::Invalidator &Inv) {
10917   // Invalidate the ScalarEvolution object whenever it isn't preserved or one
10918   // of its dependencies is invalidated.
10919   auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
10920   return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
10921          Inv.invalidate<AssumptionAnalysis>(F, PA) ||
10922          Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
10923          Inv.invalidate<LoopAnalysis>(F, PA);
10924 }
10925 
10926 AnalysisKey ScalarEvolutionAnalysis::Key;
10927 
10928 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
10929                                              FunctionAnalysisManager &AM) {
10930   return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F),
10931                          AM.getResult<AssumptionAnalysis>(F),
10932                          AM.getResult<DominatorTreeAnalysis>(F),
10933                          AM.getResult<LoopAnalysis>(F));
10934 }
10935 
10936 PreservedAnalyses
10937 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
10938   AM.getResult<ScalarEvolutionAnalysis>(F).print(OS);
10939   return PreservedAnalyses::all();
10940 }
10941 
10942 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
10943                       "Scalar Evolution Analysis", false, true)
10944 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
10945 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
10946 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
10947 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
10948 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
10949                     "Scalar Evolution Analysis", false, true)
10950 char ScalarEvolutionWrapperPass::ID = 0;
10951 
10952 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
10953   initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
10954 }
10955 
10956 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
10957   SE.reset(new ScalarEvolution(
10958       F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
10959       getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
10960       getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
10961       getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
10962   return false;
10963 }
10964 
10965 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
10966 
10967 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
10968   SE->print(OS);
10969 }
10970 
10971 void ScalarEvolutionWrapperPass::verifyAnalysis() const {
10972   if (!VerifySCEV)
10973     return;
10974 
10975   SE->verify();
10976 }
10977 
10978 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
10979   AU.setPreservesAll();
10980   AU.addRequiredTransitive<AssumptionCacheTracker>();
10981   AU.addRequiredTransitive<LoopInfoWrapperPass>();
10982   AU.addRequiredTransitive<DominatorTreeWrapperPass>();
10983   AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
10984 }
10985 
10986 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS,
10987                                                         const SCEV *RHS) {
10988   FoldingSetNodeID ID;
10989   assert(LHS->getType() == RHS->getType() &&
10990          "Type mismatch between LHS and RHS");
10991   // Unique this node based on the arguments
10992   ID.AddInteger(SCEVPredicate::P_Equal);
10993   ID.AddPointer(LHS);
10994   ID.AddPointer(RHS);
10995   void *IP = nullptr;
10996   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
10997     return S;
10998   SCEVEqualPredicate *Eq = new (SCEVAllocator)
10999       SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS);
11000   UniquePreds.InsertNode(Eq, IP);
11001   return Eq;
11002 }
11003 
11004 const SCEVPredicate *ScalarEvolution::getWrapPredicate(
11005     const SCEVAddRecExpr *AR,
11006     SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
11007   FoldingSetNodeID ID;
11008   // Unique this node based on the arguments
11009   ID.AddInteger(SCEVPredicate::P_Wrap);
11010   ID.AddPointer(AR);
11011   ID.AddInteger(AddedFlags);
11012   void *IP = nullptr;
11013   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
11014     return S;
11015   auto *OF = new (SCEVAllocator)
11016       SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
11017   UniquePreds.InsertNode(OF, IP);
11018   return OF;
11019 }
11020 
11021 namespace {
11022 
11023 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
11024 public:
11025   /// Rewrites \p S in the context of a loop L and the SCEV predication
11026   /// infrastructure.
11027   ///
11028   /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
11029   /// equivalences present in \p Pred.
11030   ///
11031   /// If \p NewPreds is non-null, rewrite is free to add further predicates to
11032   /// \p NewPreds such that the result will be an AddRecExpr.
11033   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
11034                              SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
11035                              SCEVUnionPredicate *Pred) {
11036     SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
11037     return Rewriter.visit(S);
11038   }
11039 
11040   SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE,
11041                         SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
11042                         SCEVUnionPredicate *Pred)
11043       : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
11044 
11045   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
11046     if (Pred) {
11047       auto ExprPreds = Pred->getPredicatesForExpr(Expr);
11048       for (auto *Pred : ExprPreds)
11049         if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred))
11050           if (IPred->getLHS() == Expr)
11051             return IPred->getRHS();
11052     }
11053     return convertToAddRecWithPreds(Expr);
11054   }
11055 
11056   const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
11057     const SCEV *Operand = visit(Expr->getOperand());
11058     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
11059     if (AR && AR->getLoop() == L && AR->isAffine()) {
11060       // This couldn't be folded because the operand didn't have the nuw
11061       // flag. Add the nusw flag as an assumption that we could make.
11062       const SCEV *Step = AR->getStepRecurrence(SE);
11063       Type *Ty = Expr->getType();
11064       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
11065         return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
11066                                 SE.getSignExtendExpr(Step, Ty), L,
11067                                 AR->getNoWrapFlags());
11068     }
11069     return SE.getZeroExtendExpr(Operand, Expr->getType());
11070   }
11071 
11072   const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
11073     const SCEV *Operand = visit(Expr->getOperand());
11074     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
11075     if (AR && AR->getLoop() == L && AR->isAffine()) {
11076       // This couldn't be folded because the operand didn't have the nsw
11077       // flag. Add the nssw flag as an assumption that we could make.
11078       const SCEV *Step = AR->getStepRecurrence(SE);
11079       Type *Ty = Expr->getType();
11080       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
11081         return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
11082                                 SE.getSignExtendExpr(Step, Ty), L,
11083                                 AR->getNoWrapFlags());
11084     }
11085     return SE.getSignExtendExpr(Operand, Expr->getType());
11086   }
11087 
11088 private:
11089   bool addOverflowAssumption(const SCEVPredicate *P) {
11090     if (!NewPreds) {
11091       // Check if we've already made this assumption.
11092       return Pred && Pred->implies(P);
11093     }
11094     NewPreds->insert(P);
11095     return true;
11096   }
11097 
11098   bool addOverflowAssumption(const SCEVAddRecExpr *AR,
11099                              SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
11100     auto *A = SE.getWrapPredicate(AR, AddedFlags);
11101     return addOverflowAssumption(A);
11102   }
11103 
11104   // If \p Expr represents a PHINode, we try to see if it can be represented
11105   // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible
11106   // to add this predicate as a runtime overflow check, we return the AddRec.
11107   // If \p Expr does not meet these conditions (is not a PHI node, or we
11108   // couldn't create an AddRec for it, or couldn't add the predicate), we just
11109   // return \p Expr.
11110   const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) {
11111     if (!isa<PHINode>(Expr->getValue()))
11112       return Expr;
11113     Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
11114     PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr);
11115     if (!PredicatedRewrite)
11116       return Expr;
11117     for (auto *P : PredicatedRewrite->second){
11118       if (!addOverflowAssumption(P))
11119         return Expr;
11120     }
11121     return PredicatedRewrite->first;
11122   }
11123 
11124   SmallPtrSetImpl<const SCEVPredicate *> *NewPreds;
11125   SCEVUnionPredicate *Pred;
11126   const Loop *L;
11127 };
11128 } // end anonymous namespace
11129 
11130 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
11131                                                    SCEVUnionPredicate &Preds) {
11132   return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
11133 }
11134 
11135 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates(
11136     const SCEV *S, const Loop *L,
11137     SmallPtrSetImpl<const SCEVPredicate *> &Preds) {
11138 
11139   SmallPtrSet<const SCEVPredicate *, 4> TransformPreds;
11140   S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
11141   auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
11142 
11143   if (!AddRec)
11144     return nullptr;
11145 
11146   // Since the transformation was successful, we can now transfer the SCEV
11147   // predicates.
11148   for (auto *P : TransformPreds)
11149     Preds.insert(P);
11150 
11151   return AddRec;
11152 }
11153 
11154 /// SCEV predicates
11155 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
11156                              SCEVPredicateKind Kind)
11157     : FastID(ID), Kind(Kind) {}
11158 
11159 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID,
11160                                        const SCEV *LHS, const SCEV *RHS)
11161     : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {
11162   assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match");
11163   assert(LHS != RHS && "LHS and RHS are the same SCEV");
11164 }
11165 
11166 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const {
11167   const auto *Op = dyn_cast<SCEVEqualPredicate>(N);
11168 
11169   if (!Op)
11170     return false;
11171 
11172   return Op->LHS == LHS && Op->RHS == RHS;
11173 }
11174 
11175 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; }
11176 
11177 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; }
11178 
11179 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const {
11180   OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
11181 }
11182 
11183 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
11184                                      const SCEVAddRecExpr *AR,
11185                                      IncrementWrapFlags Flags)
11186     : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
11187 
11188 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; }
11189 
11190 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const {
11191   const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
11192 
11193   return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags;
11194 }
11195 
11196 bool SCEVWrapPredicate::isAlwaysTrue() const {
11197   SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
11198   IncrementWrapFlags IFlags = Flags;
11199 
11200   if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
11201     IFlags = clearFlags(IFlags, IncrementNSSW);
11202 
11203   return IFlags == IncrementAnyWrap;
11204 }
11205 
11206 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
11207   OS.indent(Depth) << *getExpr() << " Added Flags: ";
11208   if (SCEVWrapPredicate::IncrementNUSW & getFlags())
11209     OS << "<nusw>";
11210   if (SCEVWrapPredicate::IncrementNSSW & getFlags())
11211     OS << "<nssw>";
11212   OS << "\n";
11213 }
11214 
11215 SCEVWrapPredicate::IncrementWrapFlags
11216 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR,
11217                                    ScalarEvolution &SE) {
11218   IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
11219   SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
11220 
11221   // We can safely transfer the NSW flag as NSSW.
11222   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
11223     ImpliedFlags = IncrementNSSW;
11224 
11225   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
11226     // If the increment is positive, the SCEV NUW flag will also imply the
11227     // WrapPredicate NUSW flag.
11228     if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
11229       if (Step->getValue()->getValue().isNonNegative())
11230         ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
11231   }
11232 
11233   return ImpliedFlags;
11234 }
11235 
11236 /// Union predicates don't get cached so create a dummy set ID for it.
11237 SCEVUnionPredicate::SCEVUnionPredicate()
11238     : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {}
11239 
11240 bool SCEVUnionPredicate::isAlwaysTrue() const {
11241   return all_of(Preds,
11242                 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
11243 }
11244 
11245 ArrayRef<const SCEVPredicate *>
11246 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) {
11247   auto I = SCEVToPreds.find(Expr);
11248   if (I == SCEVToPreds.end())
11249     return ArrayRef<const SCEVPredicate *>();
11250   return I->second;
11251 }
11252 
11253 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
11254   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
11255     return all_of(Set->Preds,
11256                   [this](const SCEVPredicate *I) { return this->implies(I); });
11257 
11258   auto ScevPredsIt = SCEVToPreds.find(N->getExpr());
11259   if (ScevPredsIt == SCEVToPreds.end())
11260     return false;
11261   auto &SCEVPreds = ScevPredsIt->second;
11262 
11263   return any_of(SCEVPreds,
11264                 [N](const SCEVPredicate *I) { return I->implies(N); });
11265 }
11266 
11267 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; }
11268 
11269 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
11270   for (auto Pred : Preds)
11271     Pred->print(OS, Depth);
11272 }
11273 
11274 void SCEVUnionPredicate::add(const SCEVPredicate *N) {
11275   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
11276     for (auto Pred : Set->Preds)
11277       add(Pred);
11278     return;
11279   }
11280 
11281   if (implies(N))
11282     return;
11283 
11284   const SCEV *Key = N->getExpr();
11285   assert(Key && "Only SCEVUnionPredicate doesn't have an "
11286                 " associated expression!");
11287 
11288   SCEVToPreds[Key].push_back(N);
11289   Preds.push_back(N);
11290 }
11291 
11292 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
11293                                                      Loop &L)
11294     : SE(SE), L(L), Generation(0), BackedgeCount(nullptr) {}
11295 
11296 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
11297   const SCEV *Expr = SE.getSCEV(V);
11298   RewriteEntry &Entry = RewriteMap[Expr];
11299 
11300   // If we already have an entry and the version matches, return it.
11301   if (Entry.second && Generation == Entry.first)
11302     return Entry.second;
11303 
11304   // We found an entry but it's stale. Rewrite the stale entry
11305   // according to the current predicate.
11306   if (Entry.second)
11307     Expr = Entry.second;
11308 
11309   const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds);
11310   Entry = {Generation, NewSCEV};
11311 
11312   return NewSCEV;
11313 }
11314 
11315 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() {
11316   if (!BackedgeCount) {
11317     SCEVUnionPredicate BackedgePred;
11318     BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred);
11319     addPredicate(BackedgePred);
11320   }
11321   return BackedgeCount;
11322 }
11323 
11324 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
11325   if (Preds.implies(&Pred))
11326     return;
11327   Preds.add(&Pred);
11328   updateGeneration();
11329 }
11330 
11331 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const {
11332   return Preds;
11333 }
11334 
11335 void PredicatedScalarEvolution::updateGeneration() {
11336   // If the generation number wrapped recompute everything.
11337   if (++Generation == 0) {
11338     for (auto &II : RewriteMap) {
11339       const SCEV *Rewritten = II.second.second;
11340       II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)};
11341     }
11342   }
11343 }
11344 
11345 void PredicatedScalarEvolution::setNoOverflow(
11346     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
11347   const SCEV *Expr = getSCEV(V);
11348   const auto *AR = cast<SCEVAddRecExpr>(Expr);
11349 
11350   auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE);
11351 
11352   // Clear the statically implied flags.
11353   Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags);
11354   addPredicate(*SE.getWrapPredicate(AR, Flags));
11355 
11356   auto II = FlagsMap.insert({V, Flags});
11357   if (!II.second)
11358     II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second);
11359 }
11360 
11361 bool PredicatedScalarEvolution::hasNoOverflow(
11362     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
11363   const SCEV *Expr = getSCEV(V);
11364   const auto *AR = cast<SCEVAddRecExpr>(Expr);
11365 
11366   Flags = SCEVWrapPredicate::clearFlags(
11367       Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
11368 
11369   auto II = FlagsMap.find(V);
11370 
11371   if (II != FlagsMap.end())
11372     Flags = SCEVWrapPredicate::clearFlags(Flags, II->second);
11373 
11374   return Flags == SCEVWrapPredicate::IncrementAnyWrap;
11375 }
11376 
11377 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) {
11378   const SCEV *Expr = this->getSCEV(V);
11379   SmallPtrSet<const SCEVPredicate *, 4> NewPreds;
11380   auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
11381 
11382   if (!New)
11383     return nullptr;
11384 
11385   for (auto *P : NewPreds)
11386     Preds.add(P);
11387 
11388   updateGeneration();
11389   RewriteMap[SE.getSCEV(V)] = {Generation, New};
11390   return New;
11391 }
11392 
11393 PredicatedScalarEvolution::PredicatedScalarEvolution(
11394     const PredicatedScalarEvolution &Init)
11395     : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds),
11396       Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
11397   for (const auto &I : Init.FlagsMap)
11398     FlagsMap.insert(I);
11399 }
11400 
11401 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const {
11402   // For each block.
11403   for (auto *BB : L.getBlocks())
11404     for (auto &I : *BB) {
11405       if (!SE.isSCEVable(I.getType()))
11406         continue;
11407 
11408       auto *Expr = SE.getSCEV(&I);
11409       auto II = RewriteMap.find(Expr);
11410 
11411       if (II == RewriteMap.end())
11412         continue;
11413 
11414       // Don't print things that are not interesting.
11415       if (II->second.second == Expr)
11416         continue;
11417 
11418       OS.indent(Depth) << "[PSE]" << I << ":\n";
11419       OS.indent(Depth + 2) << *Expr << "\n";
11420       OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
11421     }
11422 }
11423