1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains the implementation of the scalar evolution analysis
11 // engine, which is used primarily to analyze expressions involving induction
12 // variables in loops.
13 //
14 // There are several aspects to this library.  First is the representation of
15 // scalar expressions, which are represented as subclasses of the SCEV class.
16 // These classes are used to represent certain types of subexpressions that we
17 // can handle. We only create one SCEV of a particular shape, so
18 // pointer-comparisons for equality are legal.
19 //
20 // One important aspect of the SCEV objects is that they are never cyclic, even
21 // if there is a cycle in the dataflow for an expression (ie, a PHI node).  If
22 // the PHI node is one of the idioms that we can represent (e.g., a polynomial
23 // recurrence) then we represent it directly as a recurrence node, otherwise we
24 // represent it as a SCEVUnknown node.
25 //
26 // In addition to being able to represent expressions of various types, we also
27 // have folders that are used to build the *canonical* representation for a
28 // particular expression.  These folders are capable of using a variety of
29 // rewrite rules to simplify the expressions.
30 //
31 // Once the folders are defined, we can implement the more interesting
32 // higher-level code, such as the code that recognizes PHI nodes of various
33 // types, computes the execution count of a loop, etc.
34 //
35 // TODO: We should use these routines and value representations to implement
36 // dependence analysis!
37 //
38 //===----------------------------------------------------------------------===//
39 //
40 // There are several good references for the techniques used in this analysis.
41 //
42 //  Chains of recurrences -- a method to expedite the evaluation
43 //  of closed-form functions
44 //  Olaf Bachmann, Paul S. Wang, Eugene V. Zima
45 //
46 //  On computational properties of chains of recurrences
47 //  Eugene V. Zima
48 //
49 //  Symbolic Evaluation of Chains of Recurrences for Loop Optimization
50 //  Robert A. van Engelen
51 //
52 //  Efficient Symbolic Analysis for Optimizing Compilers
53 //  Robert A. van Engelen
54 //
55 //  Using the chains of recurrences algebra for data dependence testing and
56 //  induction variable substitution
57 //  MS Thesis, Johnie Birch
58 //
59 //===----------------------------------------------------------------------===//
60 
61 #include "llvm/Analysis/ScalarEvolution.h"
62 #include "llvm/ADT/APInt.h"
63 #include "llvm/ADT/ArrayRef.h"
64 #include "llvm/ADT/DenseMap.h"
65 #include "llvm/ADT/DepthFirstIterator.h"
66 #include "llvm/ADT/FoldingSet.h"
67 #include "llvm/ADT/None.h"
68 #include "llvm/ADT/Optional.h"
69 #include "llvm/ADT/STLExtras.h"
70 #include "llvm/ADT/ScopeExit.h"
71 #include "llvm/ADT/Sequence.h"
72 #include "llvm/ADT/SetVector.h"
73 #include "llvm/ADT/SmallPtrSet.h"
74 #include "llvm/ADT/SmallSet.h"
75 #include "llvm/ADT/SmallVector.h"
76 #include "llvm/ADT/Statistic.h"
77 #include "llvm/ADT/StringRef.h"
78 #include "llvm/Analysis/AssumptionCache.h"
79 #include "llvm/Analysis/ConstantFolding.h"
80 #include "llvm/Analysis/InstructionSimplify.h"
81 #include "llvm/Analysis/LoopInfo.h"
82 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
83 #include "llvm/Analysis/TargetLibraryInfo.h"
84 #include "llvm/Analysis/ValueTracking.h"
85 #include "llvm/IR/Argument.h"
86 #include "llvm/IR/BasicBlock.h"
87 #include "llvm/IR/CFG.h"
88 #include "llvm/IR/CallSite.h"
89 #include "llvm/IR/Constant.h"
90 #include "llvm/IR/ConstantRange.h"
91 #include "llvm/IR/Constants.h"
92 #include "llvm/IR/DataLayout.h"
93 #include "llvm/IR/DerivedTypes.h"
94 #include "llvm/IR/Dominators.h"
95 #include "llvm/IR/Function.h"
96 #include "llvm/IR/GlobalAlias.h"
97 #include "llvm/IR/GlobalValue.h"
98 #include "llvm/IR/GlobalVariable.h"
99 #include "llvm/IR/InstIterator.h"
100 #include "llvm/IR/InstrTypes.h"
101 #include "llvm/IR/Instruction.h"
102 #include "llvm/IR/Instructions.h"
103 #include "llvm/IR/IntrinsicInst.h"
104 #include "llvm/IR/Intrinsics.h"
105 #include "llvm/IR/LLVMContext.h"
106 #include "llvm/IR/Metadata.h"
107 #include "llvm/IR/Operator.h"
108 #include "llvm/IR/PatternMatch.h"
109 #include "llvm/IR/Type.h"
110 #include "llvm/IR/Use.h"
111 #include "llvm/IR/User.h"
112 #include "llvm/IR/Value.h"
113 #include "llvm/Pass.h"
114 #include "llvm/Support/Casting.h"
115 #include "llvm/Support/CommandLine.h"
116 #include "llvm/Support/Compiler.h"
117 #include "llvm/Support/Debug.h"
118 #include "llvm/Support/ErrorHandling.h"
119 #include "llvm/Support/KnownBits.h"
120 #include "llvm/Support/SaveAndRestore.h"
121 #include "llvm/Support/raw_ostream.h"
122 #include <algorithm>
123 #include <cassert>
124 #include <climits>
125 #include <cstddef>
126 #include <cstdint>
127 #include <cstdlib>
128 #include <map>
129 #include <memory>
130 #include <tuple>
131 #include <utility>
132 #include <vector>
133 
134 using namespace llvm;
135 
136 #define DEBUG_TYPE "scalar-evolution"
137 
138 STATISTIC(NumArrayLenItCounts,
139           "Number of trip counts computed with array length");
140 STATISTIC(NumTripCountsComputed,
141           "Number of loops with predictable loop counts");
142 STATISTIC(NumTripCountsNotComputed,
143           "Number of loops without predictable loop counts");
144 STATISTIC(NumBruteForceTripCountsComputed,
145           "Number of loops with trip counts computed by force");
146 
147 static cl::opt<unsigned>
148 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
149                         cl::desc("Maximum number of iterations SCEV will "
150                                  "symbolically execute a constant "
151                                  "derived loop"),
152                         cl::init(100));
153 
154 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean.
155 static cl::opt<bool>
156 VerifySCEV("verify-scev",
157            cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
158 static cl::opt<bool>
159     VerifySCEVMap("verify-scev-maps",
160                   cl::desc("Verify no dangling value in ScalarEvolution's "
161                            "ExprValueMap (slow)"));
162 
163 static cl::opt<unsigned> MulOpsInlineThreshold(
164     "scev-mulops-inline-threshold", cl::Hidden,
165     cl::desc("Threshold for inlining multiplication operands into a SCEV"),
166     cl::init(32));
167 
168 static cl::opt<unsigned> AddOpsInlineThreshold(
169     "scev-addops-inline-threshold", cl::Hidden,
170     cl::desc("Threshold for inlining addition operands into a SCEV"),
171     cl::init(500));
172 
173 static cl::opt<unsigned> MaxSCEVCompareDepth(
174     "scalar-evolution-max-scev-compare-depth", cl::Hidden,
175     cl::desc("Maximum depth of recursive SCEV complexity comparisons"),
176     cl::init(32));
177 
178 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth(
179     "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden,
180     cl::desc("Maximum depth of recursive SCEV operations implication analysis"),
181     cl::init(2));
182 
183 static cl::opt<unsigned> MaxValueCompareDepth(
184     "scalar-evolution-max-value-compare-depth", cl::Hidden,
185     cl::desc("Maximum depth of recursive value complexity comparisons"),
186     cl::init(2));
187 
188 static cl::opt<unsigned>
189     MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden,
190                   cl::desc("Maximum depth of recursive arithmetics"),
191                   cl::init(32));
192 
193 static cl::opt<unsigned> MaxConstantEvolvingDepth(
194     "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
195     cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
196 
197 static cl::opt<unsigned>
198     MaxExtDepth("scalar-evolution-max-ext-depth", cl::Hidden,
199                 cl::desc("Maximum depth of recursive SExt/ZExt"),
200                 cl::init(8));
201 
202 static cl::opt<unsigned>
203     MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden,
204                   cl::desc("Max coefficients in AddRec during evolving"),
205                   cl::init(16));
206 
207 //===----------------------------------------------------------------------===//
208 //                           SCEV class definitions
209 //===----------------------------------------------------------------------===//
210 
211 //===----------------------------------------------------------------------===//
212 // Implementation of the SCEV class.
213 //
214 
215 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
216 LLVM_DUMP_METHOD void SCEV::dump() const {
217   print(dbgs());
218   dbgs() << '\n';
219 }
220 #endif
221 
222 void SCEV::print(raw_ostream &OS) const {
223   switch (static_cast<SCEVTypes>(getSCEVType())) {
224   case scConstant:
225     cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
226     return;
227   case scTruncate: {
228     const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
229     const SCEV *Op = Trunc->getOperand();
230     OS << "(trunc " << *Op->getType() << " " << *Op << " to "
231        << *Trunc->getType() << ")";
232     return;
233   }
234   case scZeroExtend: {
235     const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
236     const SCEV *Op = ZExt->getOperand();
237     OS << "(zext " << *Op->getType() << " " << *Op << " to "
238        << *ZExt->getType() << ")";
239     return;
240   }
241   case scSignExtend: {
242     const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
243     const SCEV *Op = SExt->getOperand();
244     OS << "(sext " << *Op->getType() << " " << *Op << " to "
245        << *SExt->getType() << ")";
246     return;
247   }
248   case scAddRecExpr: {
249     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
250     OS << "{" << *AR->getOperand(0);
251     for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
252       OS << ",+," << *AR->getOperand(i);
253     OS << "}<";
254     if (AR->hasNoUnsignedWrap())
255       OS << "nuw><";
256     if (AR->hasNoSignedWrap())
257       OS << "nsw><";
258     if (AR->hasNoSelfWrap() &&
259         !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
260       OS << "nw><";
261     AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
262     OS << ">";
263     return;
264   }
265   case scAddExpr:
266   case scMulExpr:
267   case scUMaxExpr:
268   case scSMaxExpr: {
269     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
270     const char *OpStr = nullptr;
271     switch (NAry->getSCEVType()) {
272     case scAddExpr: OpStr = " + "; break;
273     case scMulExpr: OpStr = " * "; break;
274     case scUMaxExpr: OpStr = " umax "; break;
275     case scSMaxExpr: OpStr = " smax "; break;
276     }
277     OS << "(";
278     for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
279          I != E; ++I) {
280       OS << **I;
281       if (std::next(I) != E)
282         OS << OpStr;
283     }
284     OS << ")";
285     switch (NAry->getSCEVType()) {
286     case scAddExpr:
287     case scMulExpr:
288       if (NAry->hasNoUnsignedWrap())
289         OS << "<nuw>";
290       if (NAry->hasNoSignedWrap())
291         OS << "<nsw>";
292     }
293     return;
294   }
295   case scUDivExpr: {
296     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
297     OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
298     return;
299   }
300   case scUnknown: {
301     const SCEVUnknown *U = cast<SCEVUnknown>(this);
302     Type *AllocTy;
303     if (U->isSizeOf(AllocTy)) {
304       OS << "sizeof(" << *AllocTy << ")";
305       return;
306     }
307     if (U->isAlignOf(AllocTy)) {
308       OS << "alignof(" << *AllocTy << ")";
309       return;
310     }
311 
312     Type *CTy;
313     Constant *FieldNo;
314     if (U->isOffsetOf(CTy, FieldNo)) {
315       OS << "offsetof(" << *CTy << ", ";
316       FieldNo->printAsOperand(OS, false);
317       OS << ")";
318       return;
319     }
320 
321     // Otherwise just print it normally.
322     U->getValue()->printAsOperand(OS, false);
323     return;
324   }
325   case scCouldNotCompute:
326     OS << "***COULDNOTCOMPUTE***";
327     return;
328   }
329   llvm_unreachable("Unknown SCEV kind!");
330 }
331 
332 Type *SCEV::getType() const {
333   switch (static_cast<SCEVTypes>(getSCEVType())) {
334   case scConstant:
335     return cast<SCEVConstant>(this)->getType();
336   case scTruncate:
337   case scZeroExtend:
338   case scSignExtend:
339     return cast<SCEVCastExpr>(this)->getType();
340   case scAddRecExpr:
341   case scMulExpr:
342   case scUMaxExpr:
343   case scSMaxExpr:
344     return cast<SCEVNAryExpr>(this)->getType();
345   case scAddExpr:
346     return cast<SCEVAddExpr>(this)->getType();
347   case scUDivExpr:
348     return cast<SCEVUDivExpr>(this)->getType();
349   case scUnknown:
350     return cast<SCEVUnknown>(this)->getType();
351   case scCouldNotCompute:
352     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
353   }
354   llvm_unreachable("Unknown SCEV kind!");
355 }
356 
357 bool SCEV::isZero() const {
358   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
359     return SC->getValue()->isZero();
360   return false;
361 }
362 
363 bool SCEV::isOne() const {
364   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
365     return SC->getValue()->isOne();
366   return false;
367 }
368 
369 bool SCEV::isAllOnesValue() const {
370   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
371     return SC->getValue()->isMinusOne();
372   return false;
373 }
374 
375 bool SCEV::isNonConstantNegative() const {
376   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
377   if (!Mul) return false;
378 
379   // If there is a constant factor, it will be first.
380   const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
381   if (!SC) return false;
382 
383   // Return true if the value is negative, this matches things like (-42 * V).
384   return SC->getAPInt().isNegative();
385 }
386 
387 SCEVCouldNotCompute::SCEVCouldNotCompute() :
388   SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {}
389 
390 bool SCEVCouldNotCompute::classof(const SCEV *S) {
391   return S->getSCEVType() == scCouldNotCompute;
392 }
393 
394 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
395   FoldingSetNodeID ID;
396   ID.AddInteger(scConstant);
397   ID.AddPointer(V);
398   void *IP = nullptr;
399   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
400   SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
401   UniqueSCEVs.InsertNode(S, IP);
402   return S;
403 }
404 
405 const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
406   return getConstant(ConstantInt::get(getContext(), Val));
407 }
408 
409 const SCEV *
410 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
411   IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
412   return getConstant(ConstantInt::get(ITy, V, isSigned));
413 }
414 
415 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
416                            unsigned SCEVTy, const SCEV *op, Type *ty)
417   : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
418 
419 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
420                                    const SCEV *op, Type *ty)
421   : SCEVCastExpr(ID, scTruncate, op, ty) {
422   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
423          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
424          "Cannot truncate non-integer value!");
425 }
426 
427 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
428                                        const SCEV *op, Type *ty)
429   : SCEVCastExpr(ID, scZeroExtend, op, ty) {
430   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
431          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
432          "Cannot zero extend non-integer value!");
433 }
434 
435 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
436                                        const SCEV *op, Type *ty)
437   : SCEVCastExpr(ID, scSignExtend, op, ty) {
438   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
439          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
440          "Cannot sign extend non-integer value!");
441 }
442 
443 void SCEVUnknown::deleted() {
444   // Clear this SCEVUnknown from various maps.
445   SE->forgetMemoizedResults(this);
446 
447   // Remove this SCEVUnknown from the uniquing map.
448   SE->UniqueSCEVs.RemoveNode(this);
449 
450   // Release the value.
451   setValPtr(nullptr);
452 }
453 
454 void SCEVUnknown::allUsesReplacedWith(Value *New) {
455   // Remove this SCEVUnknown from the uniquing map.
456   SE->UniqueSCEVs.RemoveNode(this);
457 
458   // Update this SCEVUnknown to point to the new value. This is needed
459   // because there may still be outstanding SCEVs which still point to
460   // this SCEVUnknown.
461   setValPtr(New);
462 }
463 
464 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
465   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
466     if (VCE->getOpcode() == Instruction::PtrToInt)
467       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
468         if (CE->getOpcode() == Instruction::GetElementPtr &&
469             CE->getOperand(0)->isNullValue() &&
470             CE->getNumOperands() == 2)
471           if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
472             if (CI->isOne()) {
473               AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
474                                  ->getElementType();
475               return true;
476             }
477 
478   return false;
479 }
480 
481 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
482   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
483     if (VCE->getOpcode() == Instruction::PtrToInt)
484       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
485         if (CE->getOpcode() == Instruction::GetElementPtr &&
486             CE->getOperand(0)->isNullValue()) {
487           Type *Ty =
488             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
489           if (StructType *STy = dyn_cast<StructType>(Ty))
490             if (!STy->isPacked() &&
491                 CE->getNumOperands() == 3 &&
492                 CE->getOperand(1)->isNullValue()) {
493               if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
494                 if (CI->isOne() &&
495                     STy->getNumElements() == 2 &&
496                     STy->getElementType(0)->isIntegerTy(1)) {
497                   AllocTy = STy->getElementType(1);
498                   return true;
499                 }
500             }
501         }
502 
503   return false;
504 }
505 
506 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
507   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
508     if (VCE->getOpcode() == Instruction::PtrToInt)
509       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
510         if (CE->getOpcode() == Instruction::GetElementPtr &&
511             CE->getNumOperands() == 3 &&
512             CE->getOperand(0)->isNullValue() &&
513             CE->getOperand(1)->isNullValue()) {
514           Type *Ty =
515             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
516           // Ignore vector types here so that ScalarEvolutionExpander doesn't
517           // emit getelementptrs that index into vectors.
518           if (Ty->isStructTy() || Ty->isArrayTy()) {
519             CTy = Ty;
520             FieldNo = CE->getOperand(2);
521             return true;
522           }
523         }
524 
525   return false;
526 }
527 
528 //===----------------------------------------------------------------------===//
529 //                               SCEV Utilities
530 //===----------------------------------------------------------------------===//
531 
532 /// Compare the two values \p LV and \p RV in terms of their "complexity" where
533 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order
534 /// operands in SCEV expressions.  \p EqCache is a set of pairs of values that
535 /// have been previously deemed to be "equally complex" by this routine.  It is
536 /// intended to avoid exponential time complexity in cases like:
537 ///
538 ///   %a = f(%x, %y)
539 ///   %b = f(%a, %a)
540 ///   %c = f(%b, %b)
541 ///
542 ///   %d = f(%x, %y)
543 ///   %e = f(%d, %d)
544 ///   %f = f(%e, %e)
545 ///
546 ///   CompareValueComplexity(%f, %c)
547 ///
548 /// Since we do not continue running this routine on expression trees once we
549 /// have seen unequal values, there is no need to track them in the cache.
550 static int
551 CompareValueComplexity(SmallSet<std::pair<Value *, Value *>, 8> &EqCache,
552                        const LoopInfo *const LI, Value *LV, Value *RV,
553                        unsigned Depth) {
554   if (Depth > MaxValueCompareDepth || EqCache.count({LV, RV}))
555     return 0;
556 
557   // Order pointer values after integer values. This helps SCEVExpander form
558   // GEPs.
559   bool LIsPointer = LV->getType()->isPointerTy(),
560        RIsPointer = RV->getType()->isPointerTy();
561   if (LIsPointer != RIsPointer)
562     return (int)LIsPointer - (int)RIsPointer;
563 
564   // Compare getValueID values.
565   unsigned LID = LV->getValueID(), RID = RV->getValueID();
566   if (LID != RID)
567     return (int)LID - (int)RID;
568 
569   // Sort arguments by their position.
570   if (const auto *LA = dyn_cast<Argument>(LV)) {
571     const auto *RA = cast<Argument>(RV);
572     unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
573     return (int)LArgNo - (int)RArgNo;
574   }
575 
576   if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
577     const auto *RGV = cast<GlobalValue>(RV);
578 
579     const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
580       auto LT = GV->getLinkage();
581       return !(GlobalValue::isPrivateLinkage(LT) ||
582                GlobalValue::isInternalLinkage(LT));
583     };
584 
585     // Use the names to distinguish the two values, but only if the
586     // names are semantically important.
587     if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
588       return LGV->getName().compare(RGV->getName());
589   }
590 
591   // For instructions, compare their loop depth, and their operand count.  This
592   // is pretty loose.
593   if (const auto *LInst = dyn_cast<Instruction>(LV)) {
594     const auto *RInst = cast<Instruction>(RV);
595 
596     // Compare loop depths.
597     const BasicBlock *LParent = LInst->getParent(),
598                      *RParent = RInst->getParent();
599     if (LParent != RParent) {
600       unsigned LDepth = LI->getLoopDepth(LParent),
601                RDepth = LI->getLoopDepth(RParent);
602       if (LDepth != RDepth)
603         return (int)LDepth - (int)RDepth;
604     }
605 
606     // Compare the number of operands.
607     unsigned LNumOps = LInst->getNumOperands(),
608              RNumOps = RInst->getNumOperands();
609     if (LNumOps != RNumOps)
610       return (int)LNumOps - (int)RNumOps;
611 
612     for (unsigned Idx : seq(0u, LNumOps)) {
613       int Result =
614           CompareValueComplexity(EqCache, LI, LInst->getOperand(Idx),
615                                  RInst->getOperand(Idx), Depth + 1);
616       if (Result != 0)
617         return Result;
618     }
619   }
620 
621   EqCache.insert({LV, RV});
622   return 0;
623 }
624 
625 // Return negative, zero, or positive, if LHS is less than, equal to, or greater
626 // than RHS, respectively. A three-way result allows recursive comparisons to be
627 // more efficient.
628 static int CompareSCEVComplexity(
629     SmallSet<std::pair<const SCEV *, const SCEV *>, 8> &EqCacheSCEV,
630     const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS,
631     DominatorTree &DT, unsigned Depth = 0) {
632   // Fast-path: SCEVs are uniqued so we can do a quick equality check.
633   if (LHS == RHS)
634     return 0;
635 
636   // Primarily, sort the SCEVs by their getSCEVType().
637   unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
638   if (LType != RType)
639     return (int)LType - (int)RType;
640 
641   if (Depth > MaxSCEVCompareDepth || EqCacheSCEV.count({LHS, RHS}))
642     return 0;
643   // Aside from the getSCEVType() ordering, the particular ordering
644   // isn't very important except that it's beneficial to be consistent,
645   // so that (a + b) and (b + a) don't end up as different expressions.
646   switch (static_cast<SCEVTypes>(LType)) {
647   case scUnknown: {
648     const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
649     const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
650 
651     SmallSet<std::pair<Value *, Value *>, 8> EqCache;
652     int X = CompareValueComplexity(EqCache, LI, LU->getValue(), RU->getValue(),
653                                    Depth + 1);
654     if (X == 0)
655       EqCacheSCEV.insert({LHS, RHS});
656     return X;
657   }
658 
659   case scConstant: {
660     const SCEVConstant *LC = cast<SCEVConstant>(LHS);
661     const SCEVConstant *RC = cast<SCEVConstant>(RHS);
662 
663     // Compare constant values.
664     const APInt &LA = LC->getAPInt();
665     const APInt &RA = RC->getAPInt();
666     unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
667     if (LBitWidth != RBitWidth)
668       return (int)LBitWidth - (int)RBitWidth;
669     return LA.ult(RA) ? -1 : 1;
670   }
671 
672   case scAddRecExpr: {
673     const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
674     const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
675 
676     // There is always a dominance between two recs that are used by one SCEV,
677     // so we can safely sort recs by loop header dominance. We require such
678     // order in getAddExpr.
679     const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
680     if (LLoop != RLoop) {
681       const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
682       assert(LHead != RHead && "Two loops share the same header?");
683       if (DT.dominates(LHead, RHead))
684         return 1;
685       else
686         assert(DT.dominates(RHead, LHead) &&
687                "No dominance between recurrences used by one SCEV?");
688       return -1;
689     }
690 
691     // Addrec complexity grows with operand count.
692     unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
693     if (LNumOps != RNumOps)
694       return (int)LNumOps - (int)RNumOps;
695 
696     // Lexicographically compare.
697     for (unsigned i = 0; i != LNumOps; ++i) {
698       int X = CompareSCEVComplexity(EqCacheSCEV, LI, LA->getOperand(i),
699                                     RA->getOperand(i), DT,  Depth + 1);
700       if (X != 0)
701         return X;
702     }
703     EqCacheSCEV.insert({LHS, RHS});
704     return 0;
705   }
706 
707   case scAddExpr:
708   case scMulExpr:
709   case scSMaxExpr:
710   case scUMaxExpr: {
711     const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
712     const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
713 
714     // Lexicographically compare n-ary expressions.
715     unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
716     if (LNumOps != RNumOps)
717       return (int)LNumOps - (int)RNumOps;
718 
719     for (unsigned i = 0; i != LNumOps; ++i) {
720       if (i >= RNumOps)
721         return 1;
722       int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getOperand(i),
723                                     RC->getOperand(i), DT, Depth + 1);
724       if (X != 0)
725         return X;
726     }
727     EqCacheSCEV.insert({LHS, RHS});
728     return 0;
729   }
730 
731   case scUDivExpr: {
732     const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
733     const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
734 
735     // Lexicographically compare udiv expressions.
736     int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getLHS(), RC->getLHS(),
737                                   DT, Depth + 1);
738     if (X != 0)
739       return X;
740     X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getRHS(), RC->getRHS(), DT,
741                               Depth + 1);
742     if (X == 0)
743       EqCacheSCEV.insert({LHS, RHS});
744     return X;
745   }
746 
747   case scTruncate:
748   case scZeroExtend:
749   case scSignExtend: {
750     const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
751     const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
752 
753     // Compare cast expressions by operand.
754     int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getOperand(),
755                                   RC->getOperand(), DT, Depth + 1);
756     if (X == 0)
757       EqCacheSCEV.insert({LHS, RHS});
758     return X;
759   }
760 
761   case scCouldNotCompute:
762     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
763   }
764   llvm_unreachable("Unknown SCEV kind!");
765 }
766 
767 /// Given a list of SCEV objects, order them by their complexity, and group
768 /// objects of the same complexity together by value.  When this routine is
769 /// finished, we know that any duplicates in the vector are consecutive and that
770 /// complexity is monotonically increasing.
771 ///
772 /// Note that we go take special precautions to ensure that we get deterministic
773 /// results from this routine.  In other words, we don't want the results of
774 /// this to depend on where the addresses of various SCEV objects happened to
775 /// land in memory.
776 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
777                               LoopInfo *LI, DominatorTree &DT) {
778   if (Ops.size() < 2) return;  // Noop
779 
780   SmallSet<std::pair<const SCEV *, const SCEV *>, 8> EqCache;
781   if (Ops.size() == 2) {
782     // This is the common case, which also happens to be trivially simple.
783     // Special case it.
784     const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
785     if (CompareSCEVComplexity(EqCache, LI, RHS, LHS, DT) < 0)
786       std::swap(LHS, RHS);
787     return;
788   }
789 
790   // Do the rough sort by complexity.
791   std::stable_sort(Ops.begin(), Ops.end(),
792                    [&EqCache, LI, &DT](const SCEV *LHS, const SCEV *RHS) {
793                      return
794                          CompareSCEVComplexity(EqCache, LI, LHS, RHS, DT) < 0;
795                    });
796 
797   // Now that we are sorted by complexity, group elements of the same
798   // complexity.  Note that this is, at worst, N^2, but the vector is likely to
799   // be extremely short in practice.  Note that we take this approach because we
800   // do not want to depend on the addresses of the objects we are grouping.
801   for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
802     const SCEV *S = Ops[i];
803     unsigned Complexity = S->getSCEVType();
804 
805     // If there are any objects of the same complexity and same value as this
806     // one, group them.
807     for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
808       if (Ops[j] == S) { // Found a duplicate.
809         // Move it to immediately after i'th element.
810         std::swap(Ops[i+1], Ops[j]);
811         ++i;   // no need to rescan it.
812         if (i == e-2) return;  // Done!
813       }
814     }
815   }
816 }
817 
818 // Returns the size of the SCEV S.
819 static inline int sizeOfSCEV(const SCEV *S) {
820   struct FindSCEVSize {
821     int Size = 0;
822 
823     FindSCEVSize() = default;
824 
825     bool follow(const SCEV *S) {
826       ++Size;
827       // Keep looking at all operands of S.
828       return true;
829     }
830 
831     bool isDone() const {
832       return false;
833     }
834   };
835 
836   FindSCEVSize F;
837   SCEVTraversal<FindSCEVSize> ST(F);
838   ST.visitAll(S);
839   return F.Size;
840 }
841 
842 namespace {
843 
844 struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> {
845 public:
846   // Computes the Quotient and Remainder of the division of Numerator by
847   // Denominator.
848   static void divide(ScalarEvolution &SE, const SCEV *Numerator,
849                      const SCEV *Denominator, const SCEV **Quotient,
850                      const SCEV **Remainder) {
851     assert(Numerator && Denominator && "Uninitialized SCEV");
852 
853     SCEVDivision D(SE, Numerator, Denominator);
854 
855     // Check for the trivial case here to avoid having to check for it in the
856     // rest of the code.
857     if (Numerator == Denominator) {
858       *Quotient = D.One;
859       *Remainder = D.Zero;
860       return;
861     }
862 
863     if (Numerator->isZero()) {
864       *Quotient = D.Zero;
865       *Remainder = D.Zero;
866       return;
867     }
868 
869     // A simple case when N/1. The quotient is N.
870     if (Denominator->isOne()) {
871       *Quotient = Numerator;
872       *Remainder = D.Zero;
873       return;
874     }
875 
876     // Split the Denominator when it is a product.
877     if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) {
878       const SCEV *Q, *R;
879       *Quotient = Numerator;
880       for (const SCEV *Op : T->operands()) {
881         divide(SE, *Quotient, Op, &Q, &R);
882         *Quotient = Q;
883 
884         // Bail out when the Numerator is not divisible by one of the terms of
885         // the Denominator.
886         if (!R->isZero()) {
887           *Quotient = D.Zero;
888           *Remainder = Numerator;
889           return;
890         }
891       }
892       *Remainder = D.Zero;
893       return;
894     }
895 
896     D.visit(Numerator);
897     *Quotient = D.Quotient;
898     *Remainder = D.Remainder;
899   }
900 
901   // Except in the trivial case described above, we do not know how to divide
902   // Expr by Denominator for the following functions with empty implementation.
903   void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {}
904   void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {}
905   void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {}
906   void visitUDivExpr(const SCEVUDivExpr *Numerator) {}
907   void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {}
908   void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {}
909   void visitUnknown(const SCEVUnknown *Numerator) {}
910   void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {}
911 
912   void visitConstant(const SCEVConstant *Numerator) {
913     if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) {
914       APInt NumeratorVal = Numerator->getAPInt();
915       APInt DenominatorVal = D->getAPInt();
916       uint32_t NumeratorBW = NumeratorVal.getBitWidth();
917       uint32_t DenominatorBW = DenominatorVal.getBitWidth();
918 
919       if (NumeratorBW > DenominatorBW)
920         DenominatorVal = DenominatorVal.sext(NumeratorBW);
921       else if (NumeratorBW < DenominatorBW)
922         NumeratorVal = NumeratorVal.sext(DenominatorBW);
923 
924       APInt QuotientVal(NumeratorVal.getBitWidth(), 0);
925       APInt RemainderVal(NumeratorVal.getBitWidth(), 0);
926       APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal);
927       Quotient = SE.getConstant(QuotientVal);
928       Remainder = SE.getConstant(RemainderVal);
929       return;
930     }
931   }
932 
933   void visitAddRecExpr(const SCEVAddRecExpr *Numerator) {
934     const SCEV *StartQ, *StartR, *StepQ, *StepR;
935     if (!Numerator->isAffine())
936       return cannotDivide(Numerator);
937     divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR);
938     divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR);
939     // Bail out if the types do not match.
940     Type *Ty = Denominator->getType();
941     if (Ty != StartQ->getType() || Ty != StartR->getType() ||
942         Ty != StepQ->getType() || Ty != StepR->getType())
943       return cannotDivide(Numerator);
944     Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(),
945                                 Numerator->getNoWrapFlags());
946     Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(),
947                                  Numerator->getNoWrapFlags());
948   }
949 
950   void visitAddExpr(const SCEVAddExpr *Numerator) {
951     SmallVector<const SCEV *, 2> Qs, Rs;
952     Type *Ty = Denominator->getType();
953 
954     for (const SCEV *Op : Numerator->operands()) {
955       const SCEV *Q, *R;
956       divide(SE, Op, Denominator, &Q, &R);
957 
958       // Bail out if types do not match.
959       if (Ty != Q->getType() || Ty != R->getType())
960         return cannotDivide(Numerator);
961 
962       Qs.push_back(Q);
963       Rs.push_back(R);
964     }
965 
966     if (Qs.size() == 1) {
967       Quotient = Qs[0];
968       Remainder = Rs[0];
969       return;
970     }
971 
972     Quotient = SE.getAddExpr(Qs);
973     Remainder = SE.getAddExpr(Rs);
974   }
975 
976   void visitMulExpr(const SCEVMulExpr *Numerator) {
977     SmallVector<const SCEV *, 2> Qs;
978     Type *Ty = Denominator->getType();
979 
980     bool FoundDenominatorTerm = false;
981     for (const SCEV *Op : Numerator->operands()) {
982       // Bail out if types do not match.
983       if (Ty != Op->getType())
984         return cannotDivide(Numerator);
985 
986       if (FoundDenominatorTerm) {
987         Qs.push_back(Op);
988         continue;
989       }
990 
991       // Check whether Denominator divides one of the product operands.
992       const SCEV *Q, *R;
993       divide(SE, Op, Denominator, &Q, &R);
994       if (!R->isZero()) {
995         Qs.push_back(Op);
996         continue;
997       }
998 
999       // Bail out if types do not match.
1000       if (Ty != Q->getType())
1001         return cannotDivide(Numerator);
1002 
1003       FoundDenominatorTerm = true;
1004       Qs.push_back(Q);
1005     }
1006 
1007     if (FoundDenominatorTerm) {
1008       Remainder = Zero;
1009       if (Qs.size() == 1)
1010         Quotient = Qs[0];
1011       else
1012         Quotient = SE.getMulExpr(Qs);
1013       return;
1014     }
1015 
1016     if (!isa<SCEVUnknown>(Denominator))
1017       return cannotDivide(Numerator);
1018 
1019     // The Remainder is obtained by replacing Denominator by 0 in Numerator.
1020     ValueToValueMap RewriteMap;
1021     RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
1022         cast<SCEVConstant>(Zero)->getValue();
1023     Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
1024 
1025     if (Remainder->isZero()) {
1026       // The Quotient is obtained by replacing Denominator by 1 in Numerator.
1027       RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
1028           cast<SCEVConstant>(One)->getValue();
1029       Quotient =
1030           SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
1031       return;
1032     }
1033 
1034     // Quotient is (Numerator - Remainder) divided by Denominator.
1035     const SCEV *Q, *R;
1036     const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder);
1037     // This SCEV does not seem to simplify: fail the division here.
1038     if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator))
1039       return cannotDivide(Numerator);
1040     divide(SE, Diff, Denominator, &Q, &R);
1041     if (R != Zero)
1042       return cannotDivide(Numerator);
1043     Quotient = Q;
1044   }
1045 
1046 private:
1047   SCEVDivision(ScalarEvolution &S, const SCEV *Numerator,
1048                const SCEV *Denominator)
1049       : SE(S), Denominator(Denominator) {
1050     Zero = SE.getZero(Denominator->getType());
1051     One = SE.getOne(Denominator->getType());
1052 
1053     // We generally do not know how to divide Expr by Denominator. We
1054     // initialize the division to a "cannot divide" state to simplify the rest
1055     // of the code.
1056     cannotDivide(Numerator);
1057   }
1058 
1059   // Convenience function for giving up on the division. We set the quotient to
1060   // be equal to zero and the remainder to be equal to the numerator.
1061   void cannotDivide(const SCEV *Numerator) {
1062     Quotient = Zero;
1063     Remainder = Numerator;
1064   }
1065 
1066   ScalarEvolution &SE;
1067   const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One;
1068 };
1069 
1070 } // end anonymous namespace
1071 
1072 //===----------------------------------------------------------------------===//
1073 //                      Simple SCEV method implementations
1074 //===----------------------------------------------------------------------===//
1075 
1076 /// Compute BC(It, K).  The result has width W.  Assume, K > 0.
1077 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
1078                                        ScalarEvolution &SE,
1079                                        Type *ResultTy) {
1080   // Handle the simplest case efficiently.
1081   if (K == 1)
1082     return SE.getTruncateOrZeroExtend(It, ResultTy);
1083 
1084   // We are using the following formula for BC(It, K):
1085   //
1086   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
1087   //
1088   // Suppose, W is the bitwidth of the return value.  We must be prepared for
1089   // overflow.  Hence, we must assure that the result of our computation is
1090   // equal to the accurate one modulo 2^W.  Unfortunately, division isn't
1091   // safe in modular arithmetic.
1092   //
1093   // However, this code doesn't use exactly that formula; the formula it uses
1094   // is something like the following, where T is the number of factors of 2 in
1095   // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
1096   // exponentiation:
1097   //
1098   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
1099   //
1100   // This formula is trivially equivalent to the previous formula.  However,
1101   // this formula can be implemented much more efficiently.  The trick is that
1102   // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
1103   // arithmetic.  To do exact division in modular arithmetic, all we have
1104   // to do is multiply by the inverse.  Therefore, this step can be done at
1105   // width W.
1106   //
1107   // The next issue is how to safely do the division by 2^T.  The way this
1108   // is done is by doing the multiplication step at a width of at least W + T
1109   // bits.  This way, the bottom W+T bits of the product are accurate. Then,
1110   // when we perform the division by 2^T (which is equivalent to a right shift
1111   // by T), the bottom W bits are accurate.  Extra bits are okay; they'll get
1112   // truncated out after the division by 2^T.
1113   //
1114   // In comparison to just directly using the first formula, this technique
1115   // is much more efficient; using the first formula requires W * K bits,
1116   // but this formula less than W + K bits. Also, the first formula requires
1117   // a division step, whereas this formula only requires multiplies and shifts.
1118   //
1119   // It doesn't matter whether the subtraction step is done in the calculation
1120   // width or the input iteration count's width; if the subtraction overflows,
1121   // the result must be zero anyway.  We prefer here to do it in the width of
1122   // the induction variable because it helps a lot for certain cases; CodeGen
1123   // isn't smart enough to ignore the overflow, which leads to much less
1124   // efficient code if the width of the subtraction is wider than the native
1125   // register width.
1126   //
1127   // (It's possible to not widen at all by pulling out factors of 2 before
1128   // the multiplication; for example, K=2 can be calculated as
1129   // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
1130   // extra arithmetic, so it's not an obvious win, and it gets
1131   // much more complicated for K > 3.)
1132 
1133   // Protection from insane SCEVs; this bound is conservative,
1134   // but it probably doesn't matter.
1135   if (K > 1000)
1136     return SE.getCouldNotCompute();
1137 
1138   unsigned W = SE.getTypeSizeInBits(ResultTy);
1139 
1140   // Calculate K! / 2^T and T; we divide out the factors of two before
1141   // multiplying for calculating K! / 2^T to avoid overflow.
1142   // Other overflow doesn't matter because we only care about the bottom
1143   // W bits of the result.
1144   APInt OddFactorial(W, 1);
1145   unsigned T = 1;
1146   for (unsigned i = 3; i <= K; ++i) {
1147     APInt Mult(W, i);
1148     unsigned TwoFactors = Mult.countTrailingZeros();
1149     T += TwoFactors;
1150     Mult.lshrInPlace(TwoFactors);
1151     OddFactorial *= Mult;
1152   }
1153 
1154   // We need at least W + T bits for the multiplication step
1155   unsigned CalculationBits = W + T;
1156 
1157   // Calculate 2^T, at width T+W.
1158   APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
1159 
1160   // Calculate the multiplicative inverse of K! / 2^T;
1161   // this multiplication factor will perform the exact division by
1162   // K! / 2^T.
1163   APInt Mod = APInt::getSignedMinValue(W+1);
1164   APInt MultiplyFactor = OddFactorial.zext(W+1);
1165   MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
1166   MultiplyFactor = MultiplyFactor.trunc(W);
1167 
1168   // Calculate the product, at width T+W
1169   IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
1170                                                       CalculationBits);
1171   const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
1172   for (unsigned i = 1; i != K; ++i) {
1173     const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
1174     Dividend = SE.getMulExpr(Dividend,
1175                              SE.getTruncateOrZeroExtend(S, CalculationTy));
1176   }
1177 
1178   // Divide by 2^T
1179   const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
1180 
1181   // Truncate the result, and divide by K! / 2^T.
1182 
1183   return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1184                        SE.getTruncateOrZeroExtend(DivResult, ResultTy));
1185 }
1186 
1187 /// Return the value of this chain of recurrences at the specified iteration
1188 /// number.  We can evaluate this recurrence by multiplying each element in the
1189 /// chain by the binomial coefficient corresponding to it.  In other words, we
1190 /// can evaluate {A,+,B,+,C,+,D} as:
1191 ///
1192 ///   A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
1193 ///
1194 /// where BC(It, k) stands for binomial coefficient.
1195 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
1196                                                 ScalarEvolution &SE) const {
1197   const SCEV *Result = getStart();
1198   for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1199     // The computation is correct in the face of overflow provided that the
1200     // multiplication is performed _after_ the evaluation of the binomial
1201     // coefficient.
1202     const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
1203     if (isa<SCEVCouldNotCompute>(Coeff))
1204       return Coeff;
1205 
1206     Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
1207   }
1208   return Result;
1209 }
1210 
1211 //===----------------------------------------------------------------------===//
1212 //                    SCEV Expression folder implementations
1213 //===----------------------------------------------------------------------===//
1214 
1215 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
1216                                              Type *Ty) {
1217   assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1218          "This is not a truncating conversion!");
1219   assert(isSCEVable(Ty) &&
1220          "This is not a conversion to a SCEVable type!");
1221   Ty = getEffectiveSCEVType(Ty);
1222 
1223   FoldingSetNodeID ID;
1224   ID.AddInteger(scTruncate);
1225   ID.AddPointer(Op);
1226   ID.AddPointer(Ty);
1227   void *IP = nullptr;
1228   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1229 
1230   // Fold if the operand is constant.
1231   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1232     return getConstant(
1233       cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1234 
1235   // trunc(trunc(x)) --> trunc(x)
1236   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
1237     return getTruncateExpr(ST->getOperand(), Ty);
1238 
1239   // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1240   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1241     return getTruncateOrSignExtend(SS->getOperand(), Ty);
1242 
1243   // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1244   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1245     return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
1246 
1247   // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can
1248   // eliminate all the truncates, or we replace other casts with truncates.
1249   if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) {
1250     SmallVector<const SCEV *, 4> Operands;
1251     bool hasTrunc = false;
1252     for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) {
1253       const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty);
1254       if (!isa<SCEVCastExpr>(SA->getOperand(i)))
1255         hasTrunc = isa<SCEVTruncateExpr>(S);
1256       Operands.push_back(S);
1257     }
1258     if (!hasTrunc)
1259       return getAddExpr(Operands);
1260     UniqueSCEVs.FindNodeOrInsertPos(ID, IP);  // Mutates IP, returns NULL.
1261   }
1262 
1263   // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can
1264   // eliminate all the truncates, or we replace other casts with truncates.
1265   if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) {
1266     SmallVector<const SCEV *, 4> Operands;
1267     bool hasTrunc = false;
1268     for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) {
1269       const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty);
1270       if (!isa<SCEVCastExpr>(SM->getOperand(i)))
1271         hasTrunc = isa<SCEVTruncateExpr>(S);
1272       Operands.push_back(S);
1273     }
1274     if (!hasTrunc)
1275       return getMulExpr(Operands);
1276     UniqueSCEVs.FindNodeOrInsertPos(ID, IP);  // Mutates IP, returns NULL.
1277   }
1278 
1279   // If the input value is a chrec scev, truncate the chrec's operands.
1280   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1281     SmallVector<const SCEV *, 4> Operands;
1282     for (const SCEV *Op : AddRec->operands())
1283       Operands.push_back(getTruncateExpr(Op, Ty));
1284     return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1285   }
1286 
1287   // The cast wasn't folded; create an explicit cast node. We can reuse
1288   // the existing insert position since if we get here, we won't have
1289   // made any changes which would invalidate it.
1290   SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1291                                                  Op, Ty);
1292   UniqueSCEVs.InsertNode(S, IP);
1293   return S;
1294 }
1295 
1296 // Get the limit of a recurrence such that incrementing by Step cannot cause
1297 // signed overflow as long as the value of the recurrence within the
1298 // loop does not exceed this limit before incrementing.
1299 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1300                                                  ICmpInst::Predicate *Pred,
1301                                                  ScalarEvolution *SE) {
1302   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1303   if (SE->isKnownPositive(Step)) {
1304     *Pred = ICmpInst::ICMP_SLT;
1305     return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1306                            SE->getSignedRangeMax(Step));
1307   }
1308   if (SE->isKnownNegative(Step)) {
1309     *Pred = ICmpInst::ICMP_SGT;
1310     return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1311                            SE->getSignedRangeMin(Step));
1312   }
1313   return nullptr;
1314 }
1315 
1316 // Get the limit of a recurrence such that incrementing by Step cannot cause
1317 // unsigned overflow as long as the value of the recurrence within the loop does
1318 // not exceed this limit before incrementing.
1319 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1320                                                    ICmpInst::Predicate *Pred,
1321                                                    ScalarEvolution *SE) {
1322   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1323   *Pred = ICmpInst::ICMP_ULT;
1324 
1325   return SE->getConstant(APInt::getMinValue(BitWidth) -
1326                          SE->getUnsignedRangeMax(Step));
1327 }
1328 
1329 namespace {
1330 
1331 struct ExtendOpTraitsBase {
1332   typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *,
1333                                                           unsigned);
1334 };
1335 
1336 // Used to make code generic over signed and unsigned overflow.
1337 template <typename ExtendOp> struct ExtendOpTraits {
1338   // Members present:
1339   //
1340   // static const SCEV::NoWrapFlags WrapType;
1341   //
1342   // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1343   //
1344   // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1345   //                                           ICmpInst::Predicate *Pred,
1346   //                                           ScalarEvolution *SE);
1347 };
1348 
1349 template <>
1350 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1351   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1352 
1353   static const GetExtendExprTy GetExtendExpr;
1354 
1355   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1356                                              ICmpInst::Predicate *Pred,
1357                                              ScalarEvolution *SE) {
1358     return getSignedOverflowLimitForStep(Step, Pred, SE);
1359   }
1360 };
1361 
1362 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1363     SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr;
1364 
1365 template <>
1366 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1367   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1368 
1369   static const GetExtendExprTy GetExtendExpr;
1370 
1371   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1372                                              ICmpInst::Predicate *Pred,
1373                                              ScalarEvolution *SE) {
1374     return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1375   }
1376 };
1377 
1378 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1379     SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr;
1380 
1381 } // end anonymous namespace
1382 
1383 // The recurrence AR has been shown to have no signed/unsigned wrap or something
1384 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1385 // easily prove NSW/NUW for its preincrement or postincrement sibling. This
1386 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1387 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1388 // expression "Step + sext/zext(PreIncAR)" is congruent with
1389 // "sext/zext(PostIncAR)"
1390 template <typename ExtendOpTy>
1391 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1392                                         ScalarEvolution *SE, unsigned Depth) {
1393   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1394   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1395 
1396   const Loop *L = AR->getLoop();
1397   const SCEV *Start = AR->getStart();
1398   const SCEV *Step = AR->getStepRecurrence(*SE);
1399 
1400   // Check for a simple looking step prior to loop entry.
1401   const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1402   if (!SA)
1403     return nullptr;
1404 
1405   // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1406   // subtraction is expensive. For this purpose, perform a quick and dirty
1407   // difference, by checking for Step in the operand list.
1408   SmallVector<const SCEV *, 4> DiffOps;
1409   for (const SCEV *Op : SA->operands())
1410     if (Op != Step)
1411       DiffOps.push_back(Op);
1412 
1413   if (DiffOps.size() == SA->getNumOperands())
1414     return nullptr;
1415 
1416   // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1417   // `Step`:
1418 
1419   // 1. NSW/NUW flags on the step increment.
1420   auto PreStartFlags =
1421     ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
1422   const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1423   const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1424       SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1425 
1426   // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1427   // "S+X does not sign/unsign-overflow".
1428   //
1429 
1430   const SCEV *BECount = SE->getBackedgeTakenCount(L);
1431   if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1432       !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1433     return PreStart;
1434 
1435   // 2. Direct overflow check on the step operation's expression.
1436   unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1437   Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1438   const SCEV *OperandExtendedStart =
1439       SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
1440                      (SE->*GetExtendExpr)(Step, WideTy, Depth));
1441   if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
1442     if (PreAR && AR->getNoWrapFlags(WrapType)) {
1443       // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1444       // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1445       // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`.  Cache this fact.
1446       const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType);
1447     }
1448     return PreStart;
1449   }
1450 
1451   // 3. Loop precondition.
1452   ICmpInst::Predicate Pred;
1453   const SCEV *OverflowLimit =
1454       ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1455 
1456   if (OverflowLimit &&
1457       SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1458     return PreStart;
1459 
1460   return nullptr;
1461 }
1462 
1463 // Get the normalized zero or sign extended expression for this AddRec's Start.
1464 template <typename ExtendOpTy>
1465 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1466                                         ScalarEvolution *SE,
1467                                         unsigned Depth) {
1468   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1469 
1470   const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth);
1471   if (!PreStart)
1472     return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth);
1473 
1474   return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty,
1475                                              Depth),
1476                         (SE->*GetExtendExpr)(PreStart, Ty, Depth));
1477 }
1478 
1479 // Try to prove away overflow by looking at "nearby" add recurrences.  A
1480 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1481 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1482 //
1483 // Formally:
1484 //
1485 //     {S,+,X} == {S-T,+,X} + T
1486 //  => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1487 //
1488 // If ({S-T,+,X} + T) does not overflow  ... (1)
1489 //
1490 //  RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1491 //
1492 // If {S-T,+,X} does not overflow  ... (2)
1493 //
1494 //  RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1495 //      == {Ext(S-T)+Ext(T),+,Ext(X)}
1496 //
1497 // If (S-T)+T does not overflow  ... (3)
1498 //
1499 //  RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1500 //      == {Ext(S),+,Ext(X)} == LHS
1501 //
1502 // Thus, if (1), (2) and (3) are true for some T, then
1503 //   Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1504 //
1505 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1506 // does not overflow" restricted to the 0th iteration.  Therefore we only need
1507 // to check for (1) and (2).
1508 //
1509 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1510 // is `Delta` (defined below).
1511 template <typename ExtendOpTy>
1512 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1513                                                 const SCEV *Step,
1514                                                 const Loop *L) {
1515   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1516 
1517   // We restrict `Start` to a constant to prevent SCEV from spending too much
1518   // time here.  It is correct (but more expensive) to continue with a
1519   // non-constant `Start` and do a general SCEV subtraction to compute
1520   // `PreStart` below.
1521   const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1522   if (!StartC)
1523     return false;
1524 
1525   APInt StartAI = StartC->getAPInt();
1526 
1527   for (unsigned Delta : {-2, -1, 1, 2}) {
1528     const SCEV *PreStart = getConstant(StartAI - Delta);
1529 
1530     FoldingSetNodeID ID;
1531     ID.AddInteger(scAddRecExpr);
1532     ID.AddPointer(PreStart);
1533     ID.AddPointer(Step);
1534     ID.AddPointer(L);
1535     void *IP = nullptr;
1536     const auto *PreAR =
1537       static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1538 
1539     // Give up if we don't already have the add recurrence we need because
1540     // actually constructing an add recurrence is relatively expensive.
1541     if (PreAR && PreAR->getNoWrapFlags(WrapType)) {  // proves (2)
1542       const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1543       ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1544       const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1545           DeltaS, &Pred, this);
1546       if (Limit && isKnownPredicate(Pred, PreAR, Limit))  // proves (1)
1547         return true;
1548     }
1549   }
1550 
1551   return false;
1552 }
1553 
1554 const SCEV *
1555 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1556   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1557          "This is not an extending conversion!");
1558   assert(isSCEVable(Ty) &&
1559          "This is not a conversion to a SCEVable type!");
1560   Ty = getEffectiveSCEVType(Ty);
1561 
1562   // Fold if the operand is constant.
1563   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1564     return getConstant(
1565       cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
1566 
1567   // zext(zext(x)) --> zext(x)
1568   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1569     return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1570 
1571   // Before doing any expensive analysis, check to see if we've already
1572   // computed a SCEV for this Op and Ty.
1573   FoldingSetNodeID ID;
1574   ID.AddInteger(scZeroExtend);
1575   ID.AddPointer(Op);
1576   ID.AddPointer(Ty);
1577   void *IP = nullptr;
1578   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1579   if (Depth > MaxExtDepth) {
1580     SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1581                                                      Op, Ty);
1582     UniqueSCEVs.InsertNode(S, IP);
1583     return S;
1584   }
1585 
1586   // zext(trunc(x)) --> zext(x) or x or trunc(x)
1587   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1588     // It's possible the bits taken off by the truncate were all zero bits. If
1589     // so, we should be able to simplify this further.
1590     const SCEV *X = ST->getOperand();
1591     ConstantRange CR = getUnsignedRange(X);
1592     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1593     unsigned NewBits = getTypeSizeInBits(Ty);
1594     if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1595             CR.zextOrTrunc(NewBits)))
1596       return getTruncateOrZeroExtend(X, Ty);
1597   }
1598 
1599   // If the input value is a chrec scev, and we can prove that the value
1600   // did not overflow the old, smaller, value, we can zero extend all of the
1601   // operands (often constants).  This allows analysis of something like
1602   // this:  for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1603   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1604     if (AR->isAffine()) {
1605       const SCEV *Start = AR->getStart();
1606       const SCEV *Step = AR->getStepRecurrence(*this);
1607       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1608       const Loop *L = AR->getLoop();
1609 
1610       if (!AR->hasNoUnsignedWrap()) {
1611         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1612         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1613       }
1614 
1615       // If we have special knowledge that this addrec won't overflow,
1616       // we don't need to do any further analysis.
1617       if (AR->hasNoUnsignedWrap())
1618         return getAddRecExpr(
1619             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1620             getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1621 
1622       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1623       // Note that this serves two purposes: It filters out loops that are
1624       // simply not analyzable, and it covers the case where this code is
1625       // being called from within backedge-taken count analysis, such that
1626       // attempting to ask for the backedge-taken count would likely result
1627       // in infinite recursion. In the later case, the analysis code will
1628       // cope with a conservative value, and it will take care to purge
1629       // that value once it has finished.
1630       const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1631       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1632         // Manually compute the final value for AR, checking for
1633         // overflow.
1634 
1635         // Check whether the backedge-taken count can be losslessly casted to
1636         // the addrec's type. The count is always unsigned.
1637         const SCEV *CastedMaxBECount =
1638           getTruncateOrZeroExtend(MaxBECount, Start->getType());
1639         const SCEV *RecastedMaxBECount =
1640           getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1641         if (MaxBECount == RecastedMaxBECount) {
1642           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1643           // Check whether Start+Step*MaxBECount has no unsigned overflow.
1644           const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step,
1645                                         SCEV::FlagAnyWrap, Depth + 1);
1646           const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul,
1647                                                           SCEV::FlagAnyWrap,
1648                                                           Depth + 1),
1649                                                WideTy, Depth + 1);
1650           const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
1651           const SCEV *WideMaxBECount =
1652             getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1653           const SCEV *OperandExtendedAdd =
1654             getAddExpr(WideStart,
1655                        getMulExpr(WideMaxBECount,
1656                                   getZeroExtendExpr(Step, WideTy, Depth + 1),
1657                                   SCEV::FlagAnyWrap, Depth + 1),
1658                        SCEV::FlagAnyWrap, Depth + 1);
1659           if (ZAdd == OperandExtendedAdd) {
1660             // Cache knowledge of AR NUW, which is propagated to this AddRec.
1661             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1662             // Return the expression with the addrec on the outside.
1663             return getAddRecExpr(
1664                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1665                                                          Depth + 1),
1666                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1667                 AR->getNoWrapFlags());
1668           }
1669           // Similar to above, only this time treat the step value as signed.
1670           // This covers loops that count down.
1671           OperandExtendedAdd =
1672             getAddExpr(WideStart,
1673                        getMulExpr(WideMaxBECount,
1674                                   getSignExtendExpr(Step, WideTy, Depth + 1),
1675                                   SCEV::FlagAnyWrap, Depth + 1),
1676                        SCEV::FlagAnyWrap, Depth + 1);
1677           if (ZAdd == OperandExtendedAdd) {
1678             // Cache knowledge of AR NW, which is propagated to this AddRec.
1679             // Negative step causes unsigned wrap, but it still can't self-wrap.
1680             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1681             // Return the expression with the addrec on the outside.
1682             return getAddRecExpr(
1683                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1684                                                          Depth + 1),
1685                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1686                 AR->getNoWrapFlags());
1687           }
1688         }
1689       }
1690 
1691       // Normally, in the cases we can prove no-overflow via a
1692       // backedge guarding condition, we can also compute a backedge
1693       // taken count for the loop.  The exceptions are assumptions and
1694       // guards present in the loop -- SCEV is not great at exploiting
1695       // these to compute max backedge taken counts, but can still use
1696       // these to prove lack of overflow.  Use this fact to avoid
1697       // doing extra work that may not pay off.
1698       if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1699           !AC.assumptions().empty()) {
1700         // If the backedge is guarded by a comparison with the pre-inc
1701         // value the addrec is safe. Also, if the entry is guarded by
1702         // a comparison with the start value and the backedge is
1703         // guarded by a comparison with the post-inc value, the addrec
1704         // is safe.
1705         if (isKnownPositive(Step)) {
1706           const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
1707                                       getUnsignedRangeMax(Step));
1708           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
1709               (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
1710                isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
1711                                            AR->getPostIncExpr(*this), N))) {
1712             // Cache knowledge of AR NUW, which is propagated to this
1713             // AddRec.
1714             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1715             // Return the expression with the addrec on the outside.
1716             return getAddRecExpr(
1717                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1718                                                          Depth + 1),
1719                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1720                 AR->getNoWrapFlags());
1721           }
1722         } else if (isKnownNegative(Step)) {
1723           const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1724                                       getSignedRangeMin(Step));
1725           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1726               (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) &&
1727                isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
1728                                            AR->getPostIncExpr(*this), N))) {
1729             // Cache knowledge of AR NW, which is propagated to this
1730             // AddRec.  Negative step causes unsigned wrap, but it
1731             // still can't self-wrap.
1732             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1733             // Return the expression with the addrec on the outside.
1734             return getAddRecExpr(
1735                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1736                                                          Depth + 1),
1737                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1738                 AR->getNoWrapFlags());
1739           }
1740         }
1741       }
1742 
1743       if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1744         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1745         return getAddRecExpr(
1746             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1747             getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1748       }
1749     }
1750 
1751   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1752     // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1753     if (SA->hasNoUnsignedWrap()) {
1754       // If the addition does not unsign overflow then we can, by definition,
1755       // commute the zero extension with the addition operation.
1756       SmallVector<const SCEV *, 4> Ops;
1757       for (const auto *Op : SA->operands())
1758         Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1759       return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1);
1760     }
1761   }
1762 
1763   // The cast wasn't folded; create an explicit cast node.
1764   // Recompute the insert position, as it may have been invalidated.
1765   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1766   SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1767                                                    Op, Ty);
1768   UniqueSCEVs.InsertNode(S, IP);
1769   return S;
1770 }
1771 
1772 const SCEV *
1773 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1774   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1775          "This is not an extending conversion!");
1776   assert(isSCEVable(Ty) &&
1777          "This is not a conversion to a SCEVable type!");
1778   Ty = getEffectiveSCEVType(Ty);
1779 
1780   // Fold if the operand is constant.
1781   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1782     return getConstant(
1783       cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
1784 
1785   // sext(sext(x)) --> sext(x)
1786   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1787     return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1);
1788 
1789   // sext(zext(x)) --> zext(x)
1790   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1791     return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1792 
1793   // Before doing any expensive analysis, check to see if we've already
1794   // computed a SCEV for this Op and Ty.
1795   FoldingSetNodeID ID;
1796   ID.AddInteger(scSignExtend);
1797   ID.AddPointer(Op);
1798   ID.AddPointer(Ty);
1799   void *IP = nullptr;
1800   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1801   // Limit recursion depth.
1802   if (Depth > MaxExtDepth) {
1803     SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1804                                                      Op, Ty);
1805     UniqueSCEVs.InsertNode(S, IP);
1806     return S;
1807   }
1808 
1809   // sext(trunc(x)) --> sext(x) or x or trunc(x)
1810   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1811     // It's possible the bits taken off by the truncate were all sign bits. If
1812     // so, we should be able to simplify this further.
1813     const SCEV *X = ST->getOperand();
1814     ConstantRange CR = getSignedRange(X);
1815     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1816     unsigned NewBits = getTypeSizeInBits(Ty);
1817     if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1818             CR.sextOrTrunc(NewBits)))
1819       return getTruncateOrSignExtend(X, Ty);
1820   }
1821 
1822   // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2
1823   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1824     if (SA->getNumOperands() == 2) {
1825       auto *SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0));
1826       auto *SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1));
1827       if (SMul && SC1) {
1828         if (auto *SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) {
1829           const APInt &C1 = SC1->getAPInt();
1830           const APInt &C2 = SC2->getAPInt();
1831           if (C1.isStrictlyPositive() && C2.isStrictlyPositive() &&
1832               C2.ugt(C1) && C2.isPowerOf2())
1833             return getAddExpr(getSignExtendExpr(SC1, Ty, Depth + 1),
1834                               getSignExtendExpr(SMul, Ty, Depth + 1),
1835                               SCEV::FlagAnyWrap, Depth + 1);
1836         }
1837       }
1838     }
1839 
1840     // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1841     if (SA->hasNoSignedWrap()) {
1842       // If the addition does not sign overflow then we can, by definition,
1843       // commute the sign extension with the addition operation.
1844       SmallVector<const SCEV *, 4> Ops;
1845       for (const auto *Op : SA->operands())
1846         Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1));
1847       return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1);
1848     }
1849   }
1850   // If the input value is a chrec scev, and we can prove that the value
1851   // did not overflow the old, smaller, value, we can sign extend all of the
1852   // operands (often constants).  This allows analysis of something like
1853   // this:  for (signed char X = 0; X < 100; ++X) { int Y = X; }
1854   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1855     if (AR->isAffine()) {
1856       const SCEV *Start = AR->getStart();
1857       const SCEV *Step = AR->getStepRecurrence(*this);
1858       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1859       const Loop *L = AR->getLoop();
1860 
1861       if (!AR->hasNoSignedWrap()) {
1862         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1863         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1864       }
1865 
1866       // If we have special knowledge that this addrec won't overflow,
1867       // we don't need to do any further analysis.
1868       if (AR->hasNoSignedWrap())
1869         return getAddRecExpr(
1870             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
1871             getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW);
1872 
1873       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1874       // Note that this serves two purposes: It filters out loops that are
1875       // simply not analyzable, and it covers the case where this code is
1876       // being called from within backedge-taken count analysis, such that
1877       // attempting to ask for the backedge-taken count would likely result
1878       // in infinite recursion. In the later case, the analysis code will
1879       // cope with a conservative value, and it will take care to purge
1880       // that value once it has finished.
1881       const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1882       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1883         // Manually compute the final value for AR, checking for
1884         // overflow.
1885 
1886         // Check whether the backedge-taken count can be losslessly casted to
1887         // the addrec's type. The count is always unsigned.
1888         const SCEV *CastedMaxBECount =
1889           getTruncateOrZeroExtend(MaxBECount, Start->getType());
1890         const SCEV *RecastedMaxBECount =
1891           getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1892         if (MaxBECount == RecastedMaxBECount) {
1893           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1894           // Check whether Start+Step*MaxBECount has no signed overflow.
1895           const SCEV *SMul = getMulExpr(CastedMaxBECount, Step,
1896                                         SCEV::FlagAnyWrap, Depth + 1);
1897           const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul,
1898                                                           SCEV::FlagAnyWrap,
1899                                                           Depth + 1),
1900                                                WideTy, Depth + 1);
1901           const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
1902           const SCEV *WideMaxBECount =
1903             getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1904           const SCEV *OperandExtendedAdd =
1905             getAddExpr(WideStart,
1906                        getMulExpr(WideMaxBECount,
1907                                   getSignExtendExpr(Step, WideTy, Depth + 1),
1908                                   SCEV::FlagAnyWrap, Depth + 1),
1909                        SCEV::FlagAnyWrap, Depth + 1);
1910           if (SAdd == OperandExtendedAdd) {
1911             // Cache knowledge of AR NSW, which is propagated to this AddRec.
1912             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1913             // Return the expression with the addrec on the outside.
1914             return getAddRecExpr(
1915                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
1916                                                          Depth + 1),
1917                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1918                 AR->getNoWrapFlags());
1919           }
1920           // Similar to above, only this time treat the step value as unsigned.
1921           // This covers loops that count up with an unsigned step.
1922           OperandExtendedAdd =
1923             getAddExpr(WideStart,
1924                        getMulExpr(WideMaxBECount,
1925                                   getZeroExtendExpr(Step, WideTy, Depth + 1),
1926                                   SCEV::FlagAnyWrap, Depth + 1),
1927                        SCEV::FlagAnyWrap, Depth + 1);
1928           if (SAdd == OperandExtendedAdd) {
1929             // If AR wraps around then
1930             //
1931             //    abs(Step) * MaxBECount > unsigned-max(AR->getType())
1932             // => SAdd != OperandExtendedAdd
1933             //
1934             // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
1935             // (SAdd == OperandExtendedAdd => AR is NW)
1936 
1937             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1938 
1939             // Return the expression with the addrec on the outside.
1940             return getAddRecExpr(
1941                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
1942                                                          Depth + 1),
1943                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1944                 AR->getNoWrapFlags());
1945           }
1946         }
1947       }
1948 
1949       // Normally, in the cases we can prove no-overflow via a
1950       // backedge guarding condition, we can also compute a backedge
1951       // taken count for the loop.  The exceptions are assumptions and
1952       // guards present in the loop -- SCEV is not great at exploiting
1953       // these to compute max backedge taken counts, but can still use
1954       // these to prove lack of overflow.  Use this fact to avoid
1955       // doing extra work that may not pay off.
1956 
1957       if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1958           !AC.assumptions().empty()) {
1959         // If the backedge is guarded by a comparison with the pre-inc
1960         // value the addrec is safe. Also, if the entry is guarded by
1961         // a comparison with the start value and the backedge is
1962         // guarded by a comparison with the post-inc value, the addrec
1963         // is safe.
1964         ICmpInst::Predicate Pred;
1965         const SCEV *OverflowLimit =
1966             getSignedOverflowLimitForStep(Step, &Pred, this);
1967         if (OverflowLimit &&
1968             (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
1969              (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) &&
1970               isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this),
1971                                           OverflowLimit)))) {
1972           // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec.
1973           const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1974           return getAddRecExpr(
1975               getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
1976               getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1977         }
1978       }
1979 
1980       // If Start and Step are constants, check if we can apply this
1981       // transformation:
1982       // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2
1983       auto *SC1 = dyn_cast<SCEVConstant>(Start);
1984       auto *SC2 = dyn_cast<SCEVConstant>(Step);
1985       if (SC1 && SC2) {
1986         const APInt &C1 = SC1->getAPInt();
1987         const APInt &C2 = SC2->getAPInt();
1988         if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) &&
1989             C2.isPowerOf2()) {
1990           Start = getSignExtendExpr(Start, Ty, Depth + 1);
1991           const SCEV *NewAR = getAddRecExpr(getZero(AR->getType()), Step, L,
1992                                             AR->getNoWrapFlags());
1993           return getAddExpr(Start, getSignExtendExpr(NewAR, Ty, Depth + 1),
1994                             SCEV::FlagAnyWrap, Depth + 1);
1995         }
1996       }
1997 
1998       if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
1999         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
2000         return getAddRecExpr(
2001             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2002             getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2003       }
2004     }
2005 
2006   // If the input value is provably positive and we could not simplify
2007   // away the sext build a zext instead.
2008   if (isKnownNonNegative(Op))
2009     return getZeroExtendExpr(Op, Ty, Depth + 1);
2010 
2011   // The cast wasn't folded; create an explicit cast node.
2012   // Recompute the insert position, as it may have been invalidated.
2013   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2014   SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
2015                                                    Op, Ty);
2016   UniqueSCEVs.InsertNode(S, IP);
2017   return S;
2018 }
2019 
2020 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
2021 /// unspecified bits out to the given type.
2022 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
2023                                               Type *Ty) {
2024   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
2025          "This is not an extending conversion!");
2026   assert(isSCEVable(Ty) &&
2027          "This is not a conversion to a SCEVable type!");
2028   Ty = getEffectiveSCEVType(Ty);
2029 
2030   // Sign-extend negative constants.
2031   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
2032     if (SC->getAPInt().isNegative())
2033       return getSignExtendExpr(Op, Ty);
2034 
2035   // Peel off a truncate cast.
2036   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
2037     const SCEV *NewOp = T->getOperand();
2038     if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
2039       return getAnyExtendExpr(NewOp, Ty);
2040     return getTruncateOrNoop(NewOp, Ty);
2041   }
2042 
2043   // Next try a zext cast. If the cast is folded, use it.
2044   const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2045   if (!isa<SCEVZeroExtendExpr>(ZExt))
2046     return ZExt;
2047 
2048   // Next try a sext cast. If the cast is folded, use it.
2049   const SCEV *SExt = getSignExtendExpr(Op, Ty);
2050   if (!isa<SCEVSignExtendExpr>(SExt))
2051     return SExt;
2052 
2053   // Force the cast to be folded into the operands of an addrec.
2054   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2055     SmallVector<const SCEV *, 4> Ops;
2056     for (const SCEV *Op : AR->operands())
2057       Ops.push_back(getAnyExtendExpr(Op, Ty));
2058     return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2059   }
2060 
2061   // If the expression is obviously signed, use the sext cast value.
2062   if (isa<SCEVSMaxExpr>(Op))
2063     return SExt;
2064 
2065   // Absent any other information, use the zext cast value.
2066   return ZExt;
2067 }
2068 
2069 /// Process the given Ops list, which is a list of operands to be added under
2070 /// the given scale, update the given map. This is a helper function for
2071 /// getAddRecExpr. As an example of what it does, given a sequence of operands
2072 /// that would form an add expression like this:
2073 ///
2074 ///    m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2075 ///
2076 /// where A and B are constants, update the map with these values:
2077 ///
2078 ///    (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2079 ///
2080 /// and add 13 + A*B*29 to AccumulatedConstant.
2081 /// This will allow getAddRecExpr to produce this:
2082 ///
2083 ///    13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2084 ///
2085 /// This form often exposes folding opportunities that are hidden in
2086 /// the original operand list.
2087 ///
2088 /// Return true iff it appears that any interesting folding opportunities
2089 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
2090 /// the common case where no interesting opportunities are present, and
2091 /// is also used as a check to avoid infinite recursion.
2092 static bool
2093 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
2094                              SmallVectorImpl<const SCEV *> &NewOps,
2095                              APInt &AccumulatedConstant,
2096                              const SCEV *const *Ops, size_t NumOperands,
2097                              const APInt &Scale,
2098                              ScalarEvolution &SE) {
2099   bool Interesting = false;
2100 
2101   // Iterate over the add operands. They are sorted, with constants first.
2102   unsigned i = 0;
2103   while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2104     ++i;
2105     // Pull a buried constant out to the outside.
2106     if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2107       Interesting = true;
2108     AccumulatedConstant += Scale * C->getAPInt();
2109   }
2110 
2111   // Next comes everything else. We're especially interested in multiplies
2112   // here, but they're in the middle, so just visit the rest with one loop.
2113   for (; i != NumOperands; ++i) {
2114     const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
2115     if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2116       APInt NewScale =
2117           Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2118       if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2119         // A multiplication of a constant with another add; recurse.
2120         const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2121         Interesting |=
2122           CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2123                                        Add->op_begin(), Add->getNumOperands(),
2124                                        NewScale, SE);
2125       } else {
2126         // A multiplication of a constant with some other value. Update
2127         // the map.
2128         SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
2129         const SCEV *Key = SE.getMulExpr(MulOps);
2130         auto Pair = M.insert({Key, NewScale});
2131         if (Pair.second) {
2132           NewOps.push_back(Pair.first->first);
2133         } else {
2134           Pair.first->second += NewScale;
2135           // The map already had an entry for this value, which may indicate
2136           // a folding opportunity.
2137           Interesting = true;
2138         }
2139       }
2140     } else {
2141       // An ordinary operand. Update the map.
2142       std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
2143           M.insert({Ops[i], Scale});
2144       if (Pair.second) {
2145         NewOps.push_back(Pair.first->first);
2146       } else {
2147         Pair.first->second += Scale;
2148         // The map already had an entry for this value, which may indicate
2149         // a folding opportunity.
2150         Interesting = true;
2151       }
2152     }
2153   }
2154 
2155   return Interesting;
2156 }
2157 
2158 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2159 // `OldFlags' as can't-wrap behavior.  Infer a more aggressive set of
2160 // can't-overflow flags for the operation if possible.
2161 static SCEV::NoWrapFlags
2162 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
2163                       const SmallVectorImpl<const SCEV *> &Ops,
2164                       SCEV::NoWrapFlags Flags) {
2165   using namespace std::placeholders;
2166 
2167   using OBO = OverflowingBinaryOperator;
2168 
2169   bool CanAnalyze =
2170       Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
2171   (void)CanAnalyze;
2172   assert(CanAnalyze && "don't call from other places!");
2173 
2174   int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2175   SCEV::NoWrapFlags SignOrUnsignWrap =
2176       ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2177 
2178   // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2179   auto IsKnownNonNegative = [&](const SCEV *S) {
2180     return SE->isKnownNonNegative(S);
2181   };
2182 
2183   if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2184     Flags =
2185         ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
2186 
2187   SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2188 
2189   if (SignOrUnsignWrap != SignOrUnsignMask && Type == scAddExpr &&
2190       Ops.size() == 2 && isa<SCEVConstant>(Ops[0])) {
2191 
2192     // (A + C) --> (A + C)<nsw> if the addition does not sign overflow
2193     // (A + C) --> (A + C)<nuw> if the addition does not unsign overflow
2194 
2195     const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2196     if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2197       auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2198           Instruction::Add, C, OBO::NoSignedWrap);
2199       if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2200         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2201     }
2202     if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2203       auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2204           Instruction::Add, C, OBO::NoUnsignedWrap);
2205       if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2206         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2207     }
2208   }
2209 
2210   return Flags;
2211 }
2212 
2213 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) {
2214   if (!isLoopInvariant(S, L))
2215     return false;
2216   // If a value depends on a SCEVUnknown which is defined after the loop, we
2217   // conservatively assume that we cannot calculate it at the loop's entry.
2218   struct FindDominatedSCEVUnknown {
2219     bool Found = false;
2220     const Loop *L;
2221     DominatorTree &DT;
2222     LoopInfo &LI;
2223 
2224     FindDominatedSCEVUnknown(const Loop *L, DominatorTree &DT, LoopInfo &LI)
2225         : L(L), DT(DT), LI(LI) {}
2226 
2227     bool checkSCEVUnknown(const SCEVUnknown *SU) {
2228       if (auto *I = dyn_cast<Instruction>(SU->getValue())) {
2229         if (DT.dominates(L->getHeader(), I->getParent()))
2230           Found = true;
2231         else
2232           assert(DT.dominates(I->getParent(), L->getHeader()) &&
2233                  "No dominance relationship between SCEV and loop?");
2234       }
2235       return false;
2236     }
2237 
2238     bool follow(const SCEV *S) {
2239       switch (static_cast<SCEVTypes>(S->getSCEVType())) {
2240       case scConstant:
2241         return false;
2242       case scAddRecExpr:
2243       case scTruncate:
2244       case scZeroExtend:
2245       case scSignExtend:
2246       case scAddExpr:
2247       case scMulExpr:
2248       case scUMaxExpr:
2249       case scSMaxExpr:
2250       case scUDivExpr:
2251         return true;
2252       case scUnknown:
2253         return checkSCEVUnknown(cast<SCEVUnknown>(S));
2254       case scCouldNotCompute:
2255         llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
2256       }
2257       return false;
2258     }
2259 
2260     bool isDone() { return Found; }
2261   };
2262 
2263   FindDominatedSCEVUnknown FSU(L, DT, LI);
2264   SCEVTraversal<FindDominatedSCEVUnknown> ST(FSU);
2265   ST.visitAll(S);
2266   return !FSU.Found;
2267 }
2268 
2269 /// Get a canonical add expression, or something simpler if possible.
2270 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2271                                         SCEV::NoWrapFlags Flags,
2272                                         unsigned Depth) {
2273   assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2274          "only nuw or nsw allowed");
2275   assert(!Ops.empty() && "Cannot get empty add!");
2276   if (Ops.size() == 1) return Ops[0];
2277 #ifndef NDEBUG
2278   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2279   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2280     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2281            "SCEVAddExpr operand types don't match!");
2282 #endif
2283 
2284   // Sort by complexity, this groups all similar expression types together.
2285   GroupByComplexity(Ops, &LI, DT);
2286 
2287   Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags);
2288 
2289   // If there are any constants, fold them together.
2290   unsigned Idx = 0;
2291   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2292     ++Idx;
2293     assert(Idx < Ops.size());
2294     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2295       // We found two constants, fold them together!
2296       Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
2297       if (Ops.size() == 2) return Ops[0];
2298       Ops.erase(Ops.begin()+1);  // Erase the folded element
2299       LHSC = cast<SCEVConstant>(Ops[0]);
2300     }
2301 
2302     // If we are left with a constant zero being added, strip it off.
2303     if (LHSC->getValue()->isZero()) {
2304       Ops.erase(Ops.begin());
2305       --Idx;
2306     }
2307 
2308     if (Ops.size() == 1) return Ops[0];
2309   }
2310 
2311   // Limit recursion calls depth.
2312   if (Depth > MaxArithDepth)
2313     return getOrCreateAddExpr(Ops, Flags);
2314 
2315   // Okay, check to see if the same value occurs in the operand list more than
2316   // once.  If so, merge them together into an multiply expression.  Since we
2317   // sorted the list, these values are required to be adjacent.
2318   Type *Ty = Ops[0]->getType();
2319   bool FoundMatch = false;
2320   for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2321     if (Ops[i] == Ops[i+1]) {      //  X + Y + Y  -->  X + Y*2
2322       // Scan ahead to count how many equal operands there are.
2323       unsigned Count = 2;
2324       while (i+Count != e && Ops[i+Count] == Ops[i])
2325         ++Count;
2326       // Merge the values into a multiply.
2327       const SCEV *Scale = getConstant(Ty, Count);
2328       const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1);
2329       if (Ops.size() == Count)
2330         return Mul;
2331       Ops[i] = Mul;
2332       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2333       --i; e -= Count - 1;
2334       FoundMatch = true;
2335     }
2336   if (FoundMatch)
2337     return getAddExpr(Ops, Flags);
2338 
2339   // Check for truncates. If all the operands are truncated from the same
2340   // type, see if factoring out the truncate would permit the result to be
2341   // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
2342   // if the contents of the resulting outer trunc fold to something simple.
2343   auto FindTruncSrcType = [&]() -> Type * {
2344     // We're ultimately looking to fold an addrec of truncs and muls of only
2345     // constants and truncs, so if we find any other types of SCEV
2346     // as operands of the addrec then we bail and return nullptr here.
2347     // Otherwise, we return the type of the operand of a trunc that we find.
2348     if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx]))
2349       return T->getOperand()->getType();
2350     if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2351       const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1);
2352       if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp))
2353         return T->getOperand()->getType();
2354     }
2355     return nullptr;
2356   };
2357   if (auto *SrcType = FindTruncSrcType()) {
2358     SmallVector<const SCEV *, 8> LargeOps;
2359     bool Ok = true;
2360     // Check all the operands to see if they can be represented in the
2361     // source type of the truncate.
2362     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2363       if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2364         if (T->getOperand()->getType() != SrcType) {
2365           Ok = false;
2366           break;
2367         }
2368         LargeOps.push_back(T->getOperand());
2369       } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2370         LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2371       } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
2372         SmallVector<const SCEV *, 8> LargeMulOps;
2373         for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2374           if (const SCEVTruncateExpr *T =
2375                 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2376             if (T->getOperand()->getType() != SrcType) {
2377               Ok = false;
2378               break;
2379             }
2380             LargeMulOps.push_back(T->getOperand());
2381           } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2382             LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2383           } else {
2384             Ok = false;
2385             break;
2386           }
2387         }
2388         if (Ok)
2389           LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1));
2390       } else {
2391         Ok = false;
2392         break;
2393       }
2394     }
2395     if (Ok) {
2396       // Evaluate the expression in the larger type.
2397       const SCEV *Fold = getAddExpr(LargeOps, Flags, Depth + 1);
2398       // If it folds to something simple, use it. Otherwise, don't.
2399       if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2400         return getTruncateExpr(Fold, Ty);
2401     }
2402   }
2403 
2404   // Skip past any other cast SCEVs.
2405   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2406     ++Idx;
2407 
2408   // If there are add operands they would be next.
2409   if (Idx < Ops.size()) {
2410     bool DeletedAdd = false;
2411     while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2412       if (Ops.size() > AddOpsInlineThreshold ||
2413           Add->getNumOperands() > AddOpsInlineThreshold)
2414         break;
2415       // If we have an add, expand the add operands onto the end of the operands
2416       // list.
2417       Ops.erase(Ops.begin()+Idx);
2418       Ops.append(Add->op_begin(), Add->op_end());
2419       DeletedAdd = true;
2420     }
2421 
2422     // If we deleted at least one add, we added operands to the end of the list,
2423     // and they are not necessarily sorted.  Recurse to resort and resimplify
2424     // any operands we just acquired.
2425     if (DeletedAdd)
2426       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2427   }
2428 
2429   // Skip over the add expression until we get to a multiply.
2430   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2431     ++Idx;
2432 
2433   // Check to see if there are any folding opportunities present with
2434   // operands multiplied by constant values.
2435   if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2436     uint64_t BitWidth = getTypeSizeInBits(Ty);
2437     DenseMap<const SCEV *, APInt> M;
2438     SmallVector<const SCEV *, 8> NewOps;
2439     APInt AccumulatedConstant(BitWidth, 0);
2440     if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2441                                      Ops.data(), Ops.size(),
2442                                      APInt(BitWidth, 1), *this)) {
2443       struct APIntCompare {
2444         bool operator()(const APInt &LHS, const APInt &RHS) const {
2445           return LHS.ult(RHS);
2446         }
2447       };
2448 
2449       // Some interesting folding opportunity is present, so its worthwhile to
2450       // re-generate the operands list. Group the operands by constant scale,
2451       // to avoid multiplying by the same constant scale multiple times.
2452       std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
2453       for (const SCEV *NewOp : NewOps)
2454         MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2455       // Re-generate the operands list.
2456       Ops.clear();
2457       if (AccumulatedConstant != 0)
2458         Ops.push_back(getConstant(AccumulatedConstant));
2459       for (auto &MulOp : MulOpLists)
2460         if (MulOp.first != 0)
2461           Ops.push_back(getMulExpr(
2462               getConstant(MulOp.first),
2463               getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1),
2464               SCEV::FlagAnyWrap, Depth + 1));
2465       if (Ops.empty())
2466         return getZero(Ty);
2467       if (Ops.size() == 1)
2468         return Ops[0];
2469       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2470     }
2471   }
2472 
2473   // If we are adding something to a multiply expression, make sure the
2474   // something is not already an operand of the multiply.  If so, merge it into
2475   // the multiply.
2476   for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2477     const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2478     for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2479       const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2480       if (isa<SCEVConstant>(MulOpSCEV))
2481         continue;
2482       for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
2483         if (MulOpSCEV == Ops[AddOp]) {
2484           // Fold W + X + (X * Y * Z)  -->  W + (X * ((Y*Z)+1))
2485           const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
2486           if (Mul->getNumOperands() != 2) {
2487             // If the multiply has more than two operands, we must get the
2488             // Y*Z term.
2489             SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2490                                                 Mul->op_begin()+MulOp);
2491             MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2492             InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2493           }
2494           SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul};
2495           const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2496           const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV,
2497                                             SCEV::FlagAnyWrap, Depth + 1);
2498           if (Ops.size() == 2) return OuterMul;
2499           if (AddOp < Idx) {
2500             Ops.erase(Ops.begin()+AddOp);
2501             Ops.erase(Ops.begin()+Idx-1);
2502           } else {
2503             Ops.erase(Ops.begin()+Idx);
2504             Ops.erase(Ops.begin()+AddOp-1);
2505           }
2506           Ops.push_back(OuterMul);
2507           return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2508         }
2509 
2510       // Check this multiply against other multiplies being added together.
2511       for (unsigned OtherMulIdx = Idx+1;
2512            OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2513            ++OtherMulIdx) {
2514         const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
2515         // If MulOp occurs in OtherMul, we can fold the two multiplies
2516         // together.
2517         for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2518              OMulOp != e; ++OMulOp)
2519           if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2520             // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
2521             const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
2522             if (Mul->getNumOperands() != 2) {
2523               SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2524                                                   Mul->op_begin()+MulOp);
2525               MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2526               InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2527             }
2528             const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
2529             if (OtherMul->getNumOperands() != 2) {
2530               SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
2531                                                   OtherMul->op_begin()+OMulOp);
2532               MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
2533               InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2534             }
2535             SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2};
2536             const SCEV *InnerMulSum =
2537                 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2538             const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum,
2539                                               SCEV::FlagAnyWrap, Depth + 1);
2540             if (Ops.size() == 2) return OuterMul;
2541             Ops.erase(Ops.begin()+Idx);
2542             Ops.erase(Ops.begin()+OtherMulIdx-1);
2543             Ops.push_back(OuterMul);
2544             return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2545           }
2546       }
2547     }
2548   }
2549 
2550   // If there are any add recurrences in the operands list, see if any other
2551   // added values are loop invariant.  If so, we can fold them into the
2552   // recurrence.
2553   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2554     ++Idx;
2555 
2556   // Scan over all recurrences, trying to fold loop invariants into them.
2557   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2558     // Scan all of the other operands to this add and add them to the vector if
2559     // they are loop invariant w.r.t. the recurrence.
2560     SmallVector<const SCEV *, 8> LIOps;
2561     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2562     const Loop *AddRecLoop = AddRec->getLoop();
2563     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2564       if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2565         LIOps.push_back(Ops[i]);
2566         Ops.erase(Ops.begin()+i);
2567         --i; --e;
2568       }
2569 
2570     // If we found some loop invariants, fold them into the recurrence.
2571     if (!LIOps.empty()) {
2572       //  NLI + LI + {Start,+,Step}  -->  NLI + {LI+Start,+,Step}
2573       LIOps.push_back(AddRec->getStart());
2574 
2575       SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2576                                              AddRec->op_end());
2577       // This follows from the fact that the no-wrap flags on the outer add
2578       // expression are applicable on the 0th iteration, when the add recurrence
2579       // will be equal to its start value.
2580       AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1);
2581 
2582       // Build the new addrec. Propagate the NUW and NSW flags if both the
2583       // outer add and the inner addrec are guaranteed to have no overflow.
2584       // Always propagate NW.
2585       Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2586       const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2587 
2588       // If all of the other operands were loop invariant, we are done.
2589       if (Ops.size() == 1) return NewRec;
2590 
2591       // Otherwise, add the folded AddRec by the non-invariant parts.
2592       for (unsigned i = 0;; ++i)
2593         if (Ops[i] == AddRec) {
2594           Ops[i] = NewRec;
2595           break;
2596         }
2597       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2598     }
2599 
2600     // Okay, if there weren't any loop invariants to be folded, check to see if
2601     // there are multiple AddRec's with the same loop induction variable being
2602     // added together.  If so, we can fold them.
2603     for (unsigned OtherIdx = Idx+1;
2604          OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2605          ++OtherIdx) {
2606       // We expect the AddRecExpr's to be sorted in reverse dominance order,
2607       // so that the 1st found AddRecExpr is dominated by all others.
2608       assert(DT.dominates(
2609            cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
2610            AddRec->getLoop()->getHeader()) &&
2611         "AddRecExprs are not sorted in reverse dominance order?");
2612       if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2613         // Other + {A,+,B}<L> + {C,+,D}<L>  -->  Other + {A+C,+,B+D}<L>
2614         SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2615                                                AddRec->op_end());
2616         for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2617              ++OtherIdx) {
2618           const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2619           if (OtherAddRec->getLoop() == AddRecLoop) {
2620             for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2621                  i != e; ++i) {
2622               if (i >= AddRecOps.size()) {
2623                 AddRecOps.append(OtherAddRec->op_begin()+i,
2624                                  OtherAddRec->op_end());
2625                 break;
2626               }
2627               SmallVector<const SCEV *, 2> TwoOps = {
2628                   AddRecOps[i], OtherAddRec->getOperand(i)};
2629               AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2630             }
2631             Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2632           }
2633         }
2634         // Step size has changed, so we cannot guarantee no self-wraparound.
2635         Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2636         return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2637       }
2638     }
2639 
2640     // Otherwise couldn't fold anything into this recurrence.  Move onto the
2641     // next one.
2642   }
2643 
2644   // Okay, it looks like we really DO need an add expr.  Check to see if we
2645   // already have one, otherwise create a new one.
2646   return getOrCreateAddExpr(Ops, Flags);
2647 }
2648 
2649 const SCEV *
2650 ScalarEvolution::getOrCreateAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2651                                     SCEV::NoWrapFlags Flags) {
2652   FoldingSetNodeID ID;
2653   ID.AddInteger(scAddExpr);
2654   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2655     ID.AddPointer(Ops[i]);
2656   void *IP = nullptr;
2657   SCEVAddExpr *S =
2658       static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2659   if (!S) {
2660     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2661     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2662     S = new (SCEVAllocator)
2663         SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
2664     UniqueSCEVs.InsertNode(S, IP);
2665   }
2666   S->setNoWrapFlags(Flags);
2667   return S;
2668 }
2669 
2670 const SCEV *
2671 ScalarEvolution::getOrCreateMulExpr(SmallVectorImpl<const SCEV *> &Ops,
2672                                     SCEV::NoWrapFlags Flags) {
2673   FoldingSetNodeID ID;
2674   ID.AddInteger(scMulExpr);
2675   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2676     ID.AddPointer(Ops[i]);
2677   void *IP = nullptr;
2678   SCEVMulExpr *S =
2679     static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2680   if (!S) {
2681     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2682     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2683     S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2684                                         O, Ops.size());
2685     UniqueSCEVs.InsertNode(S, IP);
2686   }
2687   S->setNoWrapFlags(Flags);
2688   return S;
2689 }
2690 
2691 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2692   uint64_t k = i*j;
2693   if (j > 1 && k / j != i) Overflow = true;
2694   return k;
2695 }
2696 
2697 /// Compute the result of "n choose k", the binomial coefficient.  If an
2698 /// intermediate computation overflows, Overflow will be set and the return will
2699 /// be garbage. Overflow is not cleared on absence of overflow.
2700 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2701   // We use the multiplicative formula:
2702   //     n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2703   // At each iteration, we take the n-th term of the numeral and divide by the
2704   // (k-n)th term of the denominator.  This division will always produce an
2705   // integral result, and helps reduce the chance of overflow in the
2706   // intermediate computations. However, we can still overflow even when the
2707   // final result would fit.
2708 
2709   if (n == 0 || n == k) return 1;
2710   if (k > n) return 0;
2711 
2712   if (k > n/2)
2713     k = n-k;
2714 
2715   uint64_t r = 1;
2716   for (uint64_t i = 1; i <= k; ++i) {
2717     r = umul_ov(r, n-(i-1), Overflow);
2718     r /= i;
2719   }
2720   return r;
2721 }
2722 
2723 /// Determine if any of the operands in this SCEV are a constant or if
2724 /// any of the add or multiply expressions in this SCEV contain a constant.
2725 static bool containsConstantInAddMulChain(const SCEV *StartExpr) {
2726   struct FindConstantInAddMulChain {
2727     bool FoundConstant = false;
2728 
2729     bool follow(const SCEV *S) {
2730       FoundConstant |= isa<SCEVConstant>(S);
2731       return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
2732     }
2733 
2734     bool isDone() const {
2735       return FoundConstant;
2736     }
2737   };
2738 
2739   FindConstantInAddMulChain F;
2740   SCEVTraversal<FindConstantInAddMulChain> ST(F);
2741   ST.visitAll(StartExpr);
2742   return F.FoundConstant;
2743 }
2744 
2745 /// Get a canonical multiply expression, or something simpler if possible.
2746 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
2747                                         SCEV::NoWrapFlags Flags,
2748                                         unsigned Depth) {
2749   assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&
2750          "only nuw or nsw allowed");
2751   assert(!Ops.empty() && "Cannot get empty mul!");
2752   if (Ops.size() == 1) return Ops[0];
2753 #ifndef NDEBUG
2754   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2755   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2756     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2757            "SCEVMulExpr operand types don't match!");
2758 #endif
2759 
2760   // Sort by complexity, this groups all similar expression types together.
2761   GroupByComplexity(Ops, &LI, DT);
2762 
2763   Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags);
2764 
2765   // Limit recursion calls depth.
2766   if (Depth > MaxArithDepth)
2767     return getOrCreateMulExpr(Ops, Flags);
2768 
2769   // If there are any constants, fold them together.
2770   unsigned Idx = 0;
2771   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2772 
2773     // C1*(C2+V) -> C1*C2 + C1*V
2774     if (Ops.size() == 2)
2775         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
2776           // If any of Add's ops are Adds or Muls with a constant,
2777           // apply this transformation as well.
2778           if (Add->getNumOperands() == 2)
2779             // TODO: There are some cases where this transformation is not
2780             // profitable, for example:
2781             // Add = (C0 + X) * Y + Z.
2782             // Maybe the scope of this transformation should be narrowed down.
2783             if (containsConstantInAddMulChain(Add))
2784               return getAddExpr(getMulExpr(LHSC, Add->getOperand(0),
2785                                            SCEV::FlagAnyWrap, Depth + 1),
2786                                 getMulExpr(LHSC, Add->getOperand(1),
2787                                            SCEV::FlagAnyWrap, Depth + 1),
2788                                 SCEV::FlagAnyWrap, Depth + 1);
2789 
2790     ++Idx;
2791     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2792       // We found two constants, fold them together!
2793       ConstantInt *Fold =
2794           ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt());
2795       Ops[0] = getConstant(Fold);
2796       Ops.erase(Ops.begin()+1);  // Erase the folded element
2797       if (Ops.size() == 1) return Ops[0];
2798       LHSC = cast<SCEVConstant>(Ops[0]);
2799     }
2800 
2801     // If we are left with a constant one being multiplied, strip it off.
2802     if (cast<SCEVConstant>(Ops[0])->getValue()->isOne()) {
2803       Ops.erase(Ops.begin());
2804       --Idx;
2805     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
2806       // If we have a multiply of zero, it will always be zero.
2807       return Ops[0];
2808     } else if (Ops[0]->isAllOnesValue()) {
2809       // If we have a mul by -1 of an add, try distributing the -1 among the
2810       // add operands.
2811       if (Ops.size() == 2) {
2812         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
2813           SmallVector<const SCEV *, 4> NewOps;
2814           bool AnyFolded = false;
2815           for (const SCEV *AddOp : Add->operands()) {
2816             const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap,
2817                                          Depth + 1);
2818             if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
2819             NewOps.push_back(Mul);
2820           }
2821           if (AnyFolded)
2822             return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1);
2823         } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
2824           // Negation preserves a recurrence's no self-wrap property.
2825           SmallVector<const SCEV *, 4> Operands;
2826           for (const SCEV *AddRecOp : AddRec->operands())
2827             Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap,
2828                                           Depth + 1));
2829 
2830           return getAddRecExpr(Operands, AddRec->getLoop(),
2831                                AddRec->getNoWrapFlags(SCEV::FlagNW));
2832         }
2833       }
2834     }
2835 
2836     if (Ops.size() == 1)
2837       return Ops[0];
2838   }
2839 
2840   // Skip over the add expression until we get to a multiply.
2841   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2842     ++Idx;
2843 
2844   // If there are mul operands inline them all into this expression.
2845   if (Idx < Ops.size()) {
2846     bool DeletedMul = false;
2847     while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2848       if (Ops.size() > MulOpsInlineThreshold)
2849         break;
2850       // If we have an mul, expand the mul operands onto the end of the
2851       // operands list.
2852       Ops.erase(Ops.begin()+Idx);
2853       Ops.append(Mul->op_begin(), Mul->op_end());
2854       DeletedMul = true;
2855     }
2856 
2857     // If we deleted at least one mul, we added operands to the end of the
2858     // list, and they are not necessarily sorted.  Recurse to resort and
2859     // resimplify any operands we just acquired.
2860     if (DeletedMul)
2861       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2862   }
2863 
2864   // If there are any add recurrences in the operands list, see if any other
2865   // added values are loop invariant.  If so, we can fold them into the
2866   // recurrence.
2867   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2868     ++Idx;
2869 
2870   // Scan over all recurrences, trying to fold loop invariants into them.
2871   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2872     // Scan all of the other operands to this mul and add them to the vector
2873     // if they are loop invariant w.r.t. the recurrence.
2874     SmallVector<const SCEV *, 8> LIOps;
2875     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2876     const Loop *AddRecLoop = AddRec->getLoop();
2877     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2878       if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2879         LIOps.push_back(Ops[i]);
2880         Ops.erase(Ops.begin()+i);
2881         --i; --e;
2882       }
2883 
2884     // If we found some loop invariants, fold them into the recurrence.
2885     if (!LIOps.empty()) {
2886       //  NLI * LI * {Start,+,Step}  -->  NLI * {LI*Start,+,LI*Step}
2887       SmallVector<const SCEV *, 4> NewOps;
2888       NewOps.reserve(AddRec->getNumOperands());
2889       const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1);
2890       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
2891         NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
2892                                     SCEV::FlagAnyWrap, Depth + 1));
2893 
2894       // Build the new addrec. Propagate the NUW and NSW flags if both the
2895       // outer mul and the inner addrec are guaranteed to have no overflow.
2896       //
2897       // No self-wrap cannot be guaranteed after changing the step size, but
2898       // will be inferred if either NUW or NSW is true.
2899       Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW));
2900       const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
2901 
2902       // If all of the other operands were loop invariant, we are done.
2903       if (Ops.size() == 1) return NewRec;
2904 
2905       // Otherwise, multiply the folded AddRec by the non-invariant parts.
2906       for (unsigned i = 0;; ++i)
2907         if (Ops[i] == AddRec) {
2908           Ops[i] = NewRec;
2909           break;
2910         }
2911       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2912     }
2913 
2914     // Okay, if there weren't any loop invariants to be folded, check to see
2915     // if there are multiple AddRec's with the same loop induction variable
2916     // being multiplied together.  If so, we can fold them.
2917 
2918     // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
2919     // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
2920     //       choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
2921     //   ]]],+,...up to x=2n}.
2922     // Note that the arguments to choose() are always integers with values
2923     // known at compile time, never SCEV objects.
2924     //
2925     // The implementation avoids pointless extra computations when the two
2926     // addrec's are of different length (mathematically, it's equivalent to
2927     // an infinite stream of zeros on the right).
2928     bool OpsModified = false;
2929     for (unsigned OtherIdx = Idx+1;
2930          OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2931          ++OtherIdx) {
2932       const SCEVAddRecExpr *OtherAddRec =
2933         dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2934       if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
2935         continue;
2936 
2937       // Limit max number of arguments to avoid creation of unreasonably big
2938       // SCEVAddRecs with very complex operands.
2939       if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
2940           MaxAddRecSize)
2941         continue;
2942 
2943       bool Overflow = false;
2944       Type *Ty = AddRec->getType();
2945       bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
2946       SmallVector<const SCEV*, 7> AddRecOps;
2947       for (int x = 0, xe = AddRec->getNumOperands() +
2948              OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
2949         const SCEV *Term = getZero(Ty);
2950         for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
2951           uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
2952           for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
2953                  ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
2954                z < ze && !Overflow; ++z) {
2955             uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
2956             uint64_t Coeff;
2957             if (LargerThan64Bits)
2958               Coeff = umul_ov(Coeff1, Coeff2, Overflow);
2959             else
2960               Coeff = Coeff1*Coeff2;
2961             const SCEV *CoeffTerm = getConstant(Ty, Coeff);
2962             const SCEV *Term1 = AddRec->getOperand(y-z);
2963             const SCEV *Term2 = OtherAddRec->getOperand(z);
2964             Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1, Term2,
2965                                                SCEV::FlagAnyWrap, Depth + 1),
2966                               SCEV::FlagAnyWrap, Depth + 1);
2967           }
2968         }
2969         AddRecOps.push_back(Term);
2970       }
2971       if (!Overflow) {
2972         const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
2973                                               SCEV::FlagAnyWrap);
2974         if (Ops.size() == 2) return NewAddRec;
2975         Ops[Idx] = NewAddRec;
2976         Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2977         OpsModified = true;
2978         AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
2979         if (!AddRec)
2980           break;
2981       }
2982     }
2983     if (OpsModified)
2984       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2985 
2986     // Otherwise couldn't fold anything into this recurrence.  Move onto the
2987     // next one.
2988   }
2989 
2990   // Okay, it looks like we really DO need an mul expr.  Check to see if we
2991   // already have one, otherwise create a new one.
2992   return getOrCreateMulExpr(Ops, Flags);
2993 }
2994 
2995 /// Represents an unsigned remainder expression based on unsigned division.
2996 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS,
2997                                          const SCEV *RHS) {
2998   assert(getEffectiveSCEVType(LHS->getType()) ==
2999          getEffectiveSCEVType(RHS->getType()) &&
3000          "SCEVURemExpr operand types don't match!");
3001 
3002   // Short-circuit easy cases
3003   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3004     // If constant is one, the result is trivial
3005     if (RHSC->getValue()->isOne())
3006       return getZero(LHS->getType()); // X urem 1 --> 0
3007 
3008     // If constant is a power of two, fold into a zext(trunc(LHS)).
3009     if (RHSC->getAPInt().isPowerOf2()) {
3010       Type *FullTy = LHS->getType();
3011       Type *TruncTy =
3012           IntegerType::get(getContext(), RHSC->getAPInt().logBase2());
3013       return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy);
3014     }
3015   }
3016 
3017   // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
3018   const SCEV *UDiv = getUDivExpr(LHS, RHS);
3019   const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW);
3020   return getMinusSCEV(LHS, Mult, SCEV::FlagNUW);
3021 }
3022 
3023 /// Get a canonical unsigned division expression, or something simpler if
3024 /// possible.
3025 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
3026                                          const SCEV *RHS) {
3027   assert(getEffectiveSCEVType(LHS->getType()) ==
3028          getEffectiveSCEVType(RHS->getType()) &&
3029          "SCEVUDivExpr operand types don't match!");
3030 
3031   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3032     if (RHSC->getValue()->isOne())
3033       return LHS;                               // X udiv 1 --> x
3034     // If the denominator is zero, the result of the udiv is undefined. Don't
3035     // try to analyze it, because the resolution chosen here may differ from
3036     // the resolution chosen in other parts of the compiler.
3037     if (!RHSC->getValue()->isZero()) {
3038       // Determine if the division can be folded into the operands of
3039       // its operands.
3040       // TODO: Generalize this to non-constants by using known-bits information.
3041       Type *Ty = LHS->getType();
3042       unsigned LZ = RHSC->getAPInt().countLeadingZeros();
3043       unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
3044       // For non-power-of-two values, effectively round the value up to the
3045       // nearest power of two.
3046       if (!RHSC->getAPInt().isPowerOf2())
3047         ++MaxShiftAmt;
3048       IntegerType *ExtTy =
3049         IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
3050       if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
3051         if (const SCEVConstant *Step =
3052             dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
3053           // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
3054           const APInt &StepInt = Step->getAPInt();
3055           const APInt &DivInt = RHSC->getAPInt();
3056           if (!StepInt.urem(DivInt) &&
3057               getZeroExtendExpr(AR, ExtTy) ==
3058               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3059                             getZeroExtendExpr(Step, ExtTy),
3060                             AR->getLoop(), SCEV::FlagAnyWrap)) {
3061             SmallVector<const SCEV *, 4> Operands;
3062             for (const SCEV *Op : AR->operands())
3063               Operands.push_back(getUDivExpr(Op, RHS));
3064             return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
3065           }
3066           /// Get a canonical UDivExpr for a recurrence.
3067           /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
3068           // We can currently only fold X%N if X is constant.
3069           const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
3070           if (StartC && !DivInt.urem(StepInt) &&
3071               getZeroExtendExpr(AR, ExtTy) ==
3072               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3073                             getZeroExtendExpr(Step, ExtTy),
3074                             AR->getLoop(), SCEV::FlagAnyWrap)) {
3075             const APInt &StartInt = StartC->getAPInt();
3076             const APInt &StartRem = StartInt.urem(StepInt);
3077             if (StartRem != 0)
3078               LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step,
3079                                   AR->getLoop(), SCEV::FlagNW);
3080           }
3081         }
3082       // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
3083       if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
3084         SmallVector<const SCEV *, 4> Operands;
3085         for (const SCEV *Op : M->operands())
3086           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3087         if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
3088           // Find an operand that's safely divisible.
3089           for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3090             const SCEV *Op = M->getOperand(i);
3091             const SCEV *Div = getUDivExpr(Op, RHSC);
3092             if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
3093               Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
3094                                                       M->op_end());
3095               Operands[i] = Div;
3096               return getMulExpr(Operands);
3097             }
3098           }
3099       }
3100       // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
3101       if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
3102         SmallVector<const SCEV *, 4> Operands;
3103         for (const SCEV *Op : A->operands())
3104           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3105         if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
3106           Operands.clear();
3107           for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
3108             const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
3109             if (isa<SCEVUDivExpr>(Op) ||
3110                 getMulExpr(Op, RHS) != A->getOperand(i))
3111               break;
3112             Operands.push_back(Op);
3113           }
3114           if (Operands.size() == A->getNumOperands())
3115             return getAddExpr(Operands);
3116         }
3117       }
3118 
3119       // Fold if both operands are constant.
3120       if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
3121         Constant *LHSCV = LHSC->getValue();
3122         Constant *RHSCV = RHSC->getValue();
3123         return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
3124                                                                    RHSCV)));
3125       }
3126     }
3127   }
3128 
3129   FoldingSetNodeID ID;
3130   ID.AddInteger(scUDivExpr);
3131   ID.AddPointer(LHS);
3132   ID.AddPointer(RHS);
3133   void *IP = nullptr;
3134   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3135   SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
3136                                              LHS, RHS);
3137   UniqueSCEVs.InsertNode(S, IP);
3138   return S;
3139 }
3140 
3141 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
3142   APInt A = C1->getAPInt().abs();
3143   APInt B = C2->getAPInt().abs();
3144   uint32_t ABW = A.getBitWidth();
3145   uint32_t BBW = B.getBitWidth();
3146 
3147   if (ABW > BBW)
3148     B = B.zext(ABW);
3149   else if (ABW < BBW)
3150     A = A.zext(BBW);
3151 
3152   return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B));
3153 }
3154 
3155 /// Get a canonical unsigned division expression, or something simpler if
3156 /// possible. There is no representation for an exact udiv in SCEV IR, but we
3157 /// can attempt to remove factors from the LHS and RHS.  We can't do this when
3158 /// it's not exact because the udiv may be clearing bits.
3159 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
3160                                               const SCEV *RHS) {
3161   // TODO: we could try to find factors in all sorts of things, but for now we
3162   // just deal with u/exact (multiply, constant). See SCEVDivision towards the
3163   // end of this file for inspiration.
3164 
3165   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
3166   if (!Mul || !Mul->hasNoUnsignedWrap())
3167     return getUDivExpr(LHS, RHS);
3168 
3169   if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
3170     // If the mulexpr multiplies by a constant, then that constant must be the
3171     // first element of the mulexpr.
3172     if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
3173       if (LHSCst == RHSCst) {
3174         SmallVector<const SCEV *, 2> Operands;
3175         Operands.append(Mul->op_begin() + 1, Mul->op_end());
3176         return getMulExpr(Operands);
3177       }
3178 
3179       // We can't just assume that LHSCst divides RHSCst cleanly, it could be
3180       // that there's a factor provided by one of the other terms. We need to
3181       // check.
3182       APInt Factor = gcd(LHSCst, RHSCst);
3183       if (!Factor.isIntN(1)) {
3184         LHSCst =
3185             cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
3186         RHSCst =
3187             cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
3188         SmallVector<const SCEV *, 2> Operands;
3189         Operands.push_back(LHSCst);
3190         Operands.append(Mul->op_begin() + 1, Mul->op_end());
3191         LHS = getMulExpr(Operands);
3192         RHS = RHSCst;
3193         Mul = dyn_cast<SCEVMulExpr>(LHS);
3194         if (!Mul)
3195           return getUDivExactExpr(LHS, RHS);
3196       }
3197     }
3198   }
3199 
3200   for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3201     if (Mul->getOperand(i) == RHS) {
3202       SmallVector<const SCEV *, 2> Operands;
3203       Operands.append(Mul->op_begin(), Mul->op_begin() + i);
3204       Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
3205       return getMulExpr(Operands);
3206     }
3207   }
3208 
3209   return getUDivExpr(LHS, RHS);
3210 }
3211 
3212 /// Get an add recurrence expression for the specified loop.  Simplify the
3213 /// expression as much as possible.
3214 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
3215                                            const Loop *L,
3216                                            SCEV::NoWrapFlags Flags) {
3217   SmallVector<const SCEV *, 4> Operands;
3218   Operands.push_back(Start);
3219   if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3220     if (StepChrec->getLoop() == L) {
3221       Operands.append(StepChrec->op_begin(), StepChrec->op_end());
3222       return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
3223     }
3224 
3225   Operands.push_back(Step);
3226   return getAddRecExpr(Operands, L, Flags);
3227 }
3228 
3229 /// Get an add recurrence expression for the specified loop.  Simplify the
3230 /// expression as much as possible.
3231 const SCEV *
3232 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
3233                                const Loop *L, SCEV::NoWrapFlags Flags) {
3234   if (Operands.size() == 1) return Operands[0];
3235 #ifndef NDEBUG
3236   Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
3237   for (unsigned i = 1, e = Operands.size(); i != e; ++i)
3238     assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
3239            "SCEVAddRecExpr operand types don't match!");
3240   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3241     assert(isLoopInvariant(Operands[i], L) &&
3242            "SCEVAddRecExpr operand is not loop-invariant!");
3243 #endif
3244 
3245   if (Operands.back()->isZero()) {
3246     Operands.pop_back();
3247     return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0}  -->  X
3248   }
3249 
3250   // It's tempting to want to call getMaxBackedgeTakenCount count here and
3251   // use that information to infer NUW and NSW flags. However, computing a
3252   // BE count requires calling getAddRecExpr, so we may not yet have a
3253   // meaningful BE count at this point (and if we don't, we'd be stuck
3254   // with a SCEVCouldNotCompute as the cached BE count).
3255 
3256   Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
3257 
3258   // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3259   if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3260     const Loop *NestedLoop = NestedAR->getLoop();
3261     if (L->contains(NestedLoop)
3262             ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3263             : (!NestedLoop->contains(L) &&
3264                DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3265       SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
3266                                                   NestedAR->op_end());
3267       Operands[0] = NestedAR->getStart();
3268       // AddRecs require their operands be loop-invariant with respect to their
3269       // loops. Don't perform this transformation if it would break this
3270       // requirement.
3271       bool AllInvariant = all_of(
3272           Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3273 
3274       if (AllInvariant) {
3275         // Create a recurrence for the outer loop with the same step size.
3276         //
3277         // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3278         // inner recurrence has the same property.
3279         SCEV::NoWrapFlags OuterFlags =
3280           maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3281 
3282         NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3283         AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3284           return isLoopInvariant(Op, NestedLoop);
3285         });
3286 
3287         if (AllInvariant) {
3288           // Ok, both add recurrences are valid after the transformation.
3289           //
3290           // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3291           // the outer recurrence has the same property.
3292           SCEV::NoWrapFlags InnerFlags =
3293             maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
3294           return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3295         }
3296       }
3297       // Reset Operands to its original state.
3298       Operands[0] = NestedAR;
3299     }
3300   }
3301 
3302   // Okay, it looks like we really DO need an addrec expr.  Check to see if we
3303   // already have one, otherwise create a new one.
3304   FoldingSetNodeID ID;
3305   ID.AddInteger(scAddRecExpr);
3306   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3307     ID.AddPointer(Operands[i]);
3308   ID.AddPointer(L);
3309   void *IP = nullptr;
3310   SCEVAddRecExpr *S =
3311     static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3312   if (!S) {
3313     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
3314     std::uninitialized_copy(Operands.begin(), Operands.end(), O);
3315     S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
3316                                            O, Operands.size(), L);
3317     UniqueSCEVs.InsertNode(S, IP);
3318   }
3319   S->setNoWrapFlags(Flags);
3320   return S;
3321 }
3322 
3323 const SCEV *
3324 ScalarEvolution::getGEPExpr(GEPOperator *GEP,
3325                             const SmallVectorImpl<const SCEV *> &IndexExprs) {
3326   const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3327   // getSCEV(Base)->getType() has the same address space as Base->getType()
3328   // because SCEV::getType() preserves the address space.
3329   Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType());
3330   // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP
3331   // instruction to its SCEV, because the Instruction may be guarded by control
3332   // flow and the no-overflow bits may not be valid for the expression in any
3333   // context. This can be fixed similarly to how these flags are handled for
3334   // adds.
3335   SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW
3336                                              : SCEV::FlagAnyWrap;
3337 
3338   const SCEV *TotalOffset = getZero(IntPtrTy);
3339   // The array size is unimportant. The first thing we do on CurTy is getting
3340   // its element type.
3341   Type *CurTy = ArrayType::get(GEP->getSourceElementType(), 0);
3342   for (const SCEV *IndexExpr : IndexExprs) {
3343     // Compute the (potentially symbolic) offset in bytes for this index.
3344     if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3345       // For a struct, add the member offset.
3346       ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3347       unsigned FieldNo = Index->getZExtValue();
3348       const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo);
3349 
3350       // Add the field offset to the running total offset.
3351       TotalOffset = getAddExpr(TotalOffset, FieldOffset);
3352 
3353       // Update CurTy to the type of the field at Index.
3354       CurTy = STy->getTypeAtIndex(Index);
3355     } else {
3356       // Update CurTy to its element type.
3357       CurTy = cast<SequentialType>(CurTy)->getElementType();
3358       // For an array, add the element offset, explicitly scaled.
3359       const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy);
3360       // Getelementptr indices are signed.
3361       IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy);
3362 
3363       // Multiply the index by the element size to compute the element offset.
3364       const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap);
3365 
3366       // Add the element offset to the running total offset.
3367       TotalOffset = getAddExpr(TotalOffset, LocalOffset);
3368     }
3369   }
3370 
3371   // Add the total offset from all the GEP indices to the base.
3372   return getAddExpr(BaseExpr, TotalOffset, Wrap);
3373 }
3374 
3375 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
3376                                          const SCEV *RHS) {
3377   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3378   return getSMaxExpr(Ops);
3379 }
3380 
3381 const SCEV *
3382 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3383   assert(!Ops.empty() && "Cannot get empty smax!");
3384   if (Ops.size() == 1) return Ops[0];
3385 #ifndef NDEBUG
3386   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3387   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3388     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3389            "SCEVSMaxExpr operand types don't match!");
3390 #endif
3391 
3392   // Sort by complexity, this groups all similar expression types together.
3393   GroupByComplexity(Ops, &LI, DT);
3394 
3395   // If there are any constants, fold them together.
3396   unsigned Idx = 0;
3397   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3398     ++Idx;
3399     assert(Idx < Ops.size());
3400     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3401       // We found two constants, fold them together!
3402       ConstantInt *Fold = ConstantInt::get(
3403           getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt()));
3404       Ops[0] = getConstant(Fold);
3405       Ops.erase(Ops.begin()+1);  // Erase the folded element
3406       if (Ops.size() == 1) return Ops[0];
3407       LHSC = cast<SCEVConstant>(Ops[0]);
3408     }
3409 
3410     // If we are left with a constant minimum-int, strip it off.
3411     if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
3412       Ops.erase(Ops.begin());
3413       --Idx;
3414     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
3415       // If we have an smax with a constant maximum-int, it will always be
3416       // maximum-int.
3417       return Ops[0];
3418     }
3419 
3420     if (Ops.size() == 1) return Ops[0];
3421   }
3422 
3423   // Find the first SMax
3424   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
3425     ++Idx;
3426 
3427   // Check to see if one of the operands is an SMax. If so, expand its operands
3428   // onto our operand list, and recurse to simplify.
3429   if (Idx < Ops.size()) {
3430     bool DeletedSMax = false;
3431     while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
3432       Ops.erase(Ops.begin()+Idx);
3433       Ops.append(SMax->op_begin(), SMax->op_end());
3434       DeletedSMax = true;
3435     }
3436 
3437     if (DeletedSMax)
3438       return getSMaxExpr(Ops);
3439   }
3440 
3441   // Okay, check to see if the same value occurs in the operand list twice.  If
3442   // so, delete one.  Since we sorted the list, these values are required to
3443   // be adjacent.
3444   for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
3445     //  X smax Y smax Y  -->  X smax Y
3446     //  X smax Y         -->  X, if X is always greater than Y
3447     if (Ops[i] == Ops[i+1] ||
3448         isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
3449       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3450       --i; --e;
3451     } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
3452       Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3453       --i; --e;
3454     }
3455 
3456   if (Ops.size() == 1) return Ops[0];
3457 
3458   assert(!Ops.empty() && "Reduced smax down to nothing!");
3459 
3460   // Okay, it looks like we really DO need an smax expr.  Check to see if we
3461   // already have one, otherwise create a new one.
3462   FoldingSetNodeID ID;
3463   ID.AddInteger(scSMaxExpr);
3464   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3465     ID.AddPointer(Ops[i]);
3466   void *IP = nullptr;
3467   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3468   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3469   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3470   SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
3471                                              O, Ops.size());
3472   UniqueSCEVs.InsertNode(S, IP);
3473   return S;
3474 }
3475 
3476 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
3477                                          const SCEV *RHS) {
3478   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3479   return getUMaxExpr(Ops);
3480 }
3481 
3482 const SCEV *
3483 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3484   assert(!Ops.empty() && "Cannot get empty umax!");
3485   if (Ops.size() == 1) return Ops[0];
3486 #ifndef NDEBUG
3487   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3488   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3489     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3490            "SCEVUMaxExpr operand types don't match!");
3491 #endif
3492 
3493   // Sort by complexity, this groups all similar expression types together.
3494   GroupByComplexity(Ops, &LI, DT);
3495 
3496   // If there are any constants, fold them together.
3497   unsigned Idx = 0;
3498   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3499     ++Idx;
3500     assert(Idx < Ops.size());
3501     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3502       // We found two constants, fold them together!
3503       ConstantInt *Fold = ConstantInt::get(
3504           getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt()));
3505       Ops[0] = getConstant(Fold);
3506       Ops.erase(Ops.begin()+1);  // Erase the folded element
3507       if (Ops.size() == 1) return Ops[0];
3508       LHSC = cast<SCEVConstant>(Ops[0]);
3509     }
3510 
3511     // If we are left with a constant minimum-int, strip it off.
3512     if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
3513       Ops.erase(Ops.begin());
3514       --Idx;
3515     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
3516       // If we have an umax with a constant maximum-int, it will always be
3517       // maximum-int.
3518       return Ops[0];
3519     }
3520 
3521     if (Ops.size() == 1) return Ops[0];
3522   }
3523 
3524   // Find the first UMax
3525   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
3526     ++Idx;
3527 
3528   // Check to see if one of the operands is a UMax. If so, expand its operands
3529   // onto our operand list, and recurse to simplify.
3530   if (Idx < Ops.size()) {
3531     bool DeletedUMax = false;
3532     while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
3533       Ops.erase(Ops.begin()+Idx);
3534       Ops.append(UMax->op_begin(), UMax->op_end());
3535       DeletedUMax = true;
3536     }
3537 
3538     if (DeletedUMax)
3539       return getUMaxExpr(Ops);
3540   }
3541 
3542   // Okay, check to see if the same value occurs in the operand list twice.  If
3543   // so, delete one.  Since we sorted the list, these values are required to
3544   // be adjacent.
3545   for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
3546     //  X umax Y umax Y  -->  X umax Y
3547     //  X umax Y         -->  X, if X is always greater than Y
3548     if (Ops[i] == Ops[i+1] ||
3549         isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
3550       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3551       --i; --e;
3552     } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
3553       Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3554       --i; --e;
3555     }
3556 
3557   if (Ops.size() == 1) return Ops[0];
3558 
3559   assert(!Ops.empty() && "Reduced umax down to nothing!");
3560 
3561   // Okay, it looks like we really DO need a umax expr.  Check to see if we
3562   // already have one, otherwise create a new one.
3563   FoldingSetNodeID ID;
3564   ID.AddInteger(scUMaxExpr);
3565   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3566     ID.AddPointer(Ops[i]);
3567   void *IP = nullptr;
3568   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3569   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3570   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3571   SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
3572                                              O, Ops.size());
3573   UniqueSCEVs.InsertNode(S, IP);
3574   return S;
3575 }
3576 
3577 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
3578                                          const SCEV *RHS) {
3579   // ~smax(~x, ~y) == smin(x, y).
3580   return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3581 }
3582 
3583 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
3584                                          const SCEV *RHS) {
3585   // ~umax(~x, ~y) == umin(x, y)
3586   return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3587 }
3588 
3589 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
3590   // We can bypass creating a target-independent
3591   // constant expression and then folding it back into a ConstantInt.
3592   // This is just a compile-time optimization.
3593   return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
3594 }
3595 
3596 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
3597                                              StructType *STy,
3598                                              unsigned FieldNo) {
3599   // We can bypass creating a target-independent
3600   // constant expression and then folding it back into a ConstantInt.
3601   // This is just a compile-time optimization.
3602   return getConstant(
3603       IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
3604 }
3605 
3606 const SCEV *ScalarEvolution::getUnknown(Value *V) {
3607   // Don't attempt to do anything other than create a SCEVUnknown object
3608   // here.  createSCEV only calls getUnknown after checking for all other
3609   // interesting possibilities, and any other code that calls getUnknown
3610   // is doing so in order to hide a value from SCEV canonicalization.
3611 
3612   FoldingSetNodeID ID;
3613   ID.AddInteger(scUnknown);
3614   ID.AddPointer(V);
3615   void *IP = nullptr;
3616   if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3617     assert(cast<SCEVUnknown>(S)->getValue() == V &&
3618            "Stale SCEVUnknown in uniquing map!");
3619     return S;
3620   }
3621   SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3622                                             FirstUnknown);
3623   FirstUnknown = cast<SCEVUnknown>(S);
3624   UniqueSCEVs.InsertNode(S, IP);
3625   return S;
3626 }
3627 
3628 //===----------------------------------------------------------------------===//
3629 //            Basic SCEV Analysis and PHI Idiom Recognition Code
3630 //
3631 
3632 /// Test if values of the given type are analyzable within the SCEV
3633 /// framework. This primarily includes integer types, and it can optionally
3634 /// include pointer types if the ScalarEvolution class has access to
3635 /// target-specific information.
3636 bool ScalarEvolution::isSCEVable(Type *Ty) const {
3637   // Integers and pointers are always SCEVable.
3638   return Ty->isIntegerTy() || Ty->isPointerTy();
3639 }
3640 
3641 /// Return the size in bits of the specified type, for which isSCEVable must
3642 /// return true.
3643 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
3644   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3645   return getDataLayout().getTypeSizeInBits(Ty);
3646 }
3647 
3648 /// Return a type with the same bitwidth as the given type and which represents
3649 /// how SCEV will treat the given type, for which isSCEVable must return
3650 /// true. For pointer types, this is the pointer-sized integer type.
3651 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
3652   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3653 
3654   if (Ty->isIntegerTy())
3655     return Ty;
3656 
3657   // The only other support type is pointer.
3658   assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
3659   return getDataLayout().getIntPtrType(Ty);
3660 }
3661 
3662 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const {
3663   return  getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
3664 }
3665 
3666 const SCEV *ScalarEvolution::getCouldNotCompute() {
3667   return CouldNotCompute.get();
3668 }
3669 
3670 bool ScalarEvolution::checkValidity(const SCEV *S) const {
3671   bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
3672     auto *SU = dyn_cast<SCEVUnknown>(S);
3673     return SU && SU->getValue() == nullptr;
3674   });
3675 
3676   return !ContainsNulls;
3677 }
3678 
3679 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
3680   HasRecMapType::iterator I = HasRecMap.find(S);
3681   if (I != HasRecMap.end())
3682     return I->second;
3683 
3684   bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>);
3685   HasRecMap.insert({S, FoundAddRec});
3686   return FoundAddRec;
3687 }
3688 
3689 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}.
3690 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an
3691 /// offset I, then return {S', I}, else return {\p S, nullptr}.
3692 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) {
3693   const auto *Add = dyn_cast<SCEVAddExpr>(S);
3694   if (!Add)
3695     return {S, nullptr};
3696 
3697   if (Add->getNumOperands() != 2)
3698     return {S, nullptr};
3699 
3700   auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0));
3701   if (!ConstOp)
3702     return {S, nullptr};
3703 
3704   return {Add->getOperand(1), ConstOp->getValue()};
3705 }
3706 
3707 /// Return the ValueOffsetPair set for \p S. \p S can be represented
3708 /// by the value and offset from any ValueOffsetPair in the set.
3709 SetVector<ScalarEvolution::ValueOffsetPair> *
3710 ScalarEvolution::getSCEVValues(const SCEV *S) {
3711   ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
3712   if (SI == ExprValueMap.end())
3713     return nullptr;
3714 #ifndef NDEBUG
3715   if (VerifySCEVMap) {
3716     // Check there is no dangling Value in the set returned.
3717     for (const auto &VE : SI->second)
3718       assert(ValueExprMap.count(VE.first));
3719   }
3720 #endif
3721   return &SI->second;
3722 }
3723 
3724 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
3725 /// cannot be used separately. eraseValueFromMap should be used to remove
3726 /// V from ValueExprMap and ExprValueMap at the same time.
3727 void ScalarEvolution::eraseValueFromMap(Value *V) {
3728   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3729   if (I != ValueExprMap.end()) {
3730     const SCEV *S = I->second;
3731     // Remove {V, 0} from the set of ExprValueMap[S]
3732     if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S))
3733       SV->remove({V, nullptr});
3734 
3735     // Remove {V, Offset} from the set of ExprValueMap[Stripped]
3736     const SCEV *Stripped;
3737     ConstantInt *Offset;
3738     std::tie(Stripped, Offset) = splitAddExpr(S);
3739     if (Offset != nullptr) {
3740       if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped))
3741         SV->remove({V, Offset});
3742     }
3743     ValueExprMap.erase(V);
3744   }
3745 }
3746 
3747 /// Return an existing SCEV if it exists, otherwise analyze the expression and
3748 /// create a new one.
3749 const SCEV *ScalarEvolution::getSCEV(Value *V) {
3750   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3751 
3752   const SCEV *S = getExistingSCEV(V);
3753   if (S == nullptr) {
3754     S = createSCEV(V);
3755     // During PHI resolution, it is possible to create two SCEVs for the same
3756     // V, so it is needed to double check whether V->S is inserted into
3757     // ValueExprMap before insert S->{V, 0} into ExprValueMap.
3758     std::pair<ValueExprMapType::iterator, bool> Pair =
3759         ValueExprMap.insert({SCEVCallbackVH(V, this), S});
3760     if (Pair.second) {
3761       ExprValueMap[S].insert({V, nullptr});
3762 
3763       // If S == Stripped + Offset, add Stripped -> {V, Offset} into
3764       // ExprValueMap.
3765       const SCEV *Stripped = S;
3766       ConstantInt *Offset = nullptr;
3767       std::tie(Stripped, Offset) = splitAddExpr(S);
3768       // If stripped is SCEVUnknown, don't bother to save
3769       // Stripped -> {V, offset}. It doesn't simplify and sometimes even
3770       // increase the complexity of the expansion code.
3771       // If V is GetElementPtrInst, don't save Stripped -> {V, offset}
3772       // because it may generate add/sub instead of GEP in SCEV expansion.
3773       if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) &&
3774           !isa<GetElementPtrInst>(V))
3775         ExprValueMap[Stripped].insert({V, Offset});
3776     }
3777   }
3778   return S;
3779 }
3780 
3781 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
3782   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3783 
3784   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3785   if (I != ValueExprMap.end()) {
3786     const SCEV *S = I->second;
3787     if (checkValidity(S))
3788       return S;
3789     eraseValueFromMap(V);
3790     forgetMemoizedResults(S);
3791   }
3792   return nullptr;
3793 }
3794 
3795 /// Return a SCEV corresponding to -V = -1*V
3796 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
3797                                              SCEV::NoWrapFlags Flags) {
3798   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3799     return getConstant(
3800                cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
3801 
3802   Type *Ty = V->getType();
3803   Ty = getEffectiveSCEVType(Ty);
3804   return getMulExpr(
3805       V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags);
3806 }
3807 
3808 /// Return a SCEV corresponding to ~V = -1-V
3809 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
3810   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3811     return getConstant(
3812                 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
3813 
3814   Type *Ty = V->getType();
3815   Ty = getEffectiveSCEVType(Ty);
3816   const SCEV *AllOnes =
3817                    getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
3818   return getMinusSCEV(AllOnes, V);
3819 }
3820 
3821 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
3822                                           SCEV::NoWrapFlags Flags,
3823                                           unsigned Depth) {
3824   // Fast path: X - X --> 0.
3825   if (LHS == RHS)
3826     return getZero(LHS->getType());
3827 
3828   // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
3829   // makes it so that we cannot make much use of NUW.
3830   auto AddFlags = SCEV::FlagAnyWrap;
3831   const bool RHSIsNotMinSigned =
3832       !getSignedRangeMin(RHS).isMinSignedValue();
3833   if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) {
3834     // Let M be the minimum representable signed value. Then (-1)*RHS
3835     // signed-wraps if and only if RHS is M. That can happen even for
3836     // a NSW subtraction because e.g. (-1)*M signed-wraps even though
3837     // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
3838     // (-1)*RHS, we need to prove that RHS != M.
3839     //
3840     // If LHS is non-negative and we know that LHS - RHS does not
3841     // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
3842     // either by proving that RHS > M or that LHS >= 0.
3843     if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
3844       AddFlags = SCEV::FlagNSW;
3845     }
3846   }
3847 
3848   // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
3849   // RHS is NSW and LHS >= 0.
3850   //
3851   // The difficulty here is that the NSW flag may have been proven
3852   // relative to a loop that is to be found in a recurrence in LHS and
3853   // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
3854   // larger scope than intended.
3855   auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3856 
3857   return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
3858 }
3859 
3860 const SCEV *
3861 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) {
3862   Type *SrcTy = V->getType();
3863   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3864          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3865          "Cannot truncate or zero extend with non-integer arguments!");
3866   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3867     return V;  // No conversion
3868   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
3869     return getTruncateExpr(V, Ty);
3870   return getZeroExtendExpr(V, Ty);
3871 }
3872 
3873 const SCEV *
3874 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
3875                                          Type *Ty) {
3876   Type *SrcTy = V->getType();
3877   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3878          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3879          "Cannot truncate or zero extend with non-integer arguments!");
3880   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3881     return V;  // No conversion
3882   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
3883     return getTruncateExpr(V, Ty);
3884   return getSignExtendExpr(V, Ty);
3885 }
3886 
3887 const SCEV *
3888 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
3889   Type *SrcTy = V->getType();
3890   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3891          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3892          "Cannot noop or zero extend with non-integer arguments!");
3893   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3894          "getNoopOrZeroExtend cannot truncate!");
3895   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3896     return V;  // No conversion
3897   return getZeroExtendExpr(V, Ty);
3898 }
3899 
3900 const SCEV *
3901 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
3902   Type *SrcTy = V->getType();
3903   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3904          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3905          "Cannot noop or sign extend with non-integer arguments!");
3906   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3907          "getNoopOrSignExtend cannot truncate!");
3908   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3909     return V;  // No conversion
3910   return getSignExtendExpr(V, Ty);
3911 }
3912 
3913 const SCEV *
3914 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
3915   Type *SrcTy = V->getType();
3916   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3917          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3918          "Cannot noop or any extend with non-integer arguments!");
3919   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3920          "getNoopOrAnyExtend cannot truncate!");
3921   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3922     return V;  // No conversion
3923   return getAnyExtendExpr(V, Ty);
3924 }
3925 
3926 const SCEV *
3927 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
3928   Type *SrcTy = V->getType();
3929   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3930          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3931          "Cannot truncate or noop with non-integer arguments!");
3932   assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
3933          "getTruncateOrNoop cannot extend!");
3934   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3935     return V;  // No conversion
3936   return getTruncateExpr(V, Ty);
3937 }
3938 
3939 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
3940                                                         const SCEV *RHS) {
3941   const SCEV *PromotedLHS = LHS;
3942   const SCEV *PromotedRHS = RHS;
3943 
3944   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3945     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3946   else
3947     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3948 
3949   return getUMaxExpr(PromotedLHS, PromotedRHS);
3950 }
3951 
3952 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
3953                                                         const SCEV *RHS) {
3954   const SCEV *PromotedLHS = LHS;
3955   const SCEV *PromotedRHS = RHS;
3956 
3957   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3958     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3959   else
3960     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3961 
3962   return getUMinExpr(PromotedLHS, PromotedRHS);
3963 }
3964 
3965 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
3966   // A pointer operand may evaluate to a nonpointer expression, such as null.
3967   if (!V->getType()->isPointerTy())
3968     return V;
3969 
3970   if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
3971     return getPointerBase(Cast->getOperand());
3972   } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
3973     const SCEV *PtrOp = nullptr;
3974     for (const SCEV *NAryOp : NAry->operands()) {
3975       if (NAryOp->getType()->isPointerTy()) {
3976         // Cannot find the base of an expression with multiple pointer operands.
3977         if (PtrOp)
3978           return V;
3979         PtrOp = NAryOp;
3980       }
3981     }
3982     if (!PtrOp)
3983       return V;
3984     return getPointerBase(PtrOp);
3985   }
3986   return V;
3987 }
3988 
3989 /// Push users of the given Instruction onto the given Worklist.
3990 static void
3991 PushDefUseChildren(Instruction *I,
3992                    SmallVectorImpl<Instruction *> &Worklist) {
3993   // Push the def-use children onto the Worklist stack.
3994   for (User *U : I->users())
3995     Worklist.push_back(cast<Instruction>(U));
3996 }
3997 
3998 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) {
3999   SmallVector<Instruction *, 16> Worklist;
4000   PushDefUseChildren(PN, Worklist);
4001 
4002   SmallPtrSet<Instruction *, 8> Visited;
4003   Visited.insert(PN);
4004   while (!Worklist.empty()) {
4005     Instruction *I = Worklist.pop_back_val();
4006     if (!Visited.insert(I).second)
4007       continue;
4008 
4009     auto It = ValueExprMap.find_as(static_cast<Value *>(I));
4010     if (It != ValueExprMap.end()) {
4011       const SCEV *Old = It->second;
4012 
4013       // Short-circuit the def-use traversal if the symbolic name
4014       // ceases to appear in expressions.
4015       if (Old != SymName && !hasOperand(Old, SymName))
4016         continue;
4017 
4018       // SCEVUnknown for a PHI either means that it has an unrecognized
4019       // structure, it's a PHI that's in the progress of being computed
4020       // by createNodeForPHI, or it's a single-value PHI. In the first case,
4021       // additional loop trip count information isn't going to change anything.
4022       // In the second case, createNodeForPHI will perform the necessary
4023       // updates on its own when it gets to that point. In the third, we do
4024       // want to forget the SCEVUnknown.
4025       if (!isa<PHINode>(I) ||
4026           !isa<SCEVUnknown>(Old) ||
4027           (I != PN && Old == SymName)) {
4028         eraseValueFromMap(It->first);
4029         forgetMemoizedResults(Old);
4030       }
4031     }
4032 
4033     PushDefUseChildren(I, Worklist);
4034   }
4035 }
4036 
4037 namespace {
4038 
4039 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
4040 public:
4041   SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
4042       : SCEVRewriteVisitor(SE), L(L) {}
4043 
4044   static const SCEV *rewrite(const SCEV *S, const Loop *L,
4045                              ScalarEvolution &SE) {
4046     SCEVInitRewriter Rewriter(L, SE);
4047     const SCEV *Result = Rewriter.visit(S);
4048     return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
4049   }
4050 
4051   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4052     if (!SE.isLoopInvariant(Expr, L))
4053       Valid = false;
4054     return Expr;
4055   }
4056 
4057   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4058     // Only allow AddRecExprs for this loop.
4059     if (Expr->getLoop() == L)
4060       return Expr->getStart();
4061     Valid = false;
4062     return Expr;
4063   }
4064 
4065   bool isValid() { return Valid; }
4066 
4067 private:
4068   const Loop *L;
4069   bool Valid = true;
4070 };
4071 
4072 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
4073 public:
4074   SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
4075       : SCEVRewriteVisitor(SE), L(L) {}
4076 
4077   static const SCEV *rewrite(const SCEV *S, const Loop *L,
4078                              ScalarEvolution &SE) {
4079     SCEVShiftRewriter Rewriter(L, SE);
4080     const SCEV *Result = Rewriter.visit(S);
4081     return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
4082   }
4083 
4084   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4085     // Only allow AddRecExprs for this loop.
4086     if (!SE.isLoopInvariant(Expr, L))
4087       Valid = false;
4088     return Expr;
4089   }
4090 
4091   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4092     if (Expr->getLoop() == L && Expr->isAffine())
4093       return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
4094     Valid = false;
4095     return Expr;
4096   }
4097 
4098   bool isValid() { return Valid; }
4099 
4100 private:
4101   const Loop *L;
4102   bool Valid = true;
4103 };
4104 
4105 } // end anonymous namespace
4106 
4107 SCEV::NoWrapFlags
4108 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
4109   if (!AR->isAffine())
4110     return SCEV::FlagAnyWrap;
4111 
4112   using OBO = OverflowingBinaryOperator;
4113 
4114   SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
4115 
4116   if (!AR->hasNoSignedWrap()) {
4117     ConstantRange AddRecRange = getSignedRange(AR);
4118     ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
4119 
4120     auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4121         Instruction::Add, IncRange, OBO::NoSignedWrap);
4122     if (NSWRegion.contains(AddRecRange))
4123       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
4124   }
4125 
4126   if (!AR->hasNoUnsignedWrap()) {
4127     ConstantRange AddRecRange = getUnsignedRange(AR);
4128     ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
4129 
4130     auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4131         Instruction::Add, IncRange, OBO::NoUnsignedWrap);
4132     if (NUWRegion.contains(AddRecRange))
4133       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
4134   }
4135 
4136   return Result;
4137 }
4138 
4139 namespace {
4140 
4141 /// Represents an abstract binary operation.  This may exist as a
4142 /// normal instruction or constant expression, or may have been
4143 /// derived from an expression tree.
4144 struct BinaryOp {
4145   unsigned Opcode;
4146   Value *LHS;
4147   Value *RHS;
4148   bool IsNSW = false;
4149   bool IsNUW = false;
4150 
4151   /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
4152   /// constant expression.
4153   Operator *Op = nullptr;
4154 
4155   explicit BinaryOp(Operator *Op)
4156       : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
4157         Op(Op) {
4158     if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
4159       IsNSW = OBO->hasNoSignedWrap();
4160       IsNUW = OBO->hasNoUnsignedWrap();
4161     }
4162   }
4163 
4164   explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
4165                     bool IsNUW = false)
4166       : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {}
4167 };
4168 
4169 } // end anonymous namespace
4170 
4171 /// Try to map \p V into a BinaryOp, and return \c None on failure.
4172 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) {
4173   auto *Op = dyn_cast<Operator>(V);
4174   if (!Op)
4175     return None;
4176 
4177   // Implementation detail: all the cleverness here should happen without
4178   // creating new SCEV expressions -- our caller knowns tricks to avoid creating
4179   // SCEV expressions when possible, and we should not break that.
4180 
4181   switch (Op->getOpcode()) {
4182   case Instruction::Add:
4183   case Instruction::Sub:
4184   case Instruction::Mul:
4185   case Instruction::UDiv:
4186   case Instruction::URem:
4187   case Instruction::And:
4188   case Instruction::Or:
4189   case Instruction::AShr:
4190   case Instruction::Shl:
4191     return BinaryOp(Op);
4192 
4193   case Instruction::Xor:
4194     if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
4195       // If the RHS of the xor is a signmask, then this is just an add.
4196       // Instcombine turns add of signmask into xor as a strength reduction step.
4197       if (RHSC->getValue().isSignMask())
4198         return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
4199     return BinaryOp(Op);
4200 
4201   case Instruction::LShr:
4202     // Turn logical shift right of a constant into a unsigned divide.
4203     if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
4204       uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
4205 
4206       // If the shift count is not less than the bitwidth, the result of
4207       // the shift is undefined. Don't try to analyze it, because the
4208       // resolution chosen here may differ from the resolution chosen in
4209       // other parts of the compiler.
4210       if (SA->getValue().ult(BitWidth)) {
4211         Constant *X =
4212             ConstantInt::get(SA->getContext(),
4213                              APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
4214         return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
4215       }
4216     }
4217     return BinaryOp(Op);
4218 
4219   case Instruction::ExtractValue: {
4220     auto *EVI = cast<ExtractValueInst>(Op);
4221     if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
4222       break;
4223 
4224     auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand());
4225     if (!CI)
4226       break;
4227 
4228     if (auto *F = CI->getCalledFunction())
4229       switch (F->getIntrinsicID()) {
4230       case Intrinsic::sadd_with_overflow:
4231       case Intrinsic::uadd_with_overflow:
4232         if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT))
4233           return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4234                           CI->getArgOperand(1));
4235 
4236         // Now that we know that all uses of the arithmetic-result component of
4237         // CI are guarded by the overflow check, we can go ahead and pretend
4238         // that the arithmetic is non-overflowing.
4239         if (F->getIntrinsicID() == Intrinsic::sadd_with_overflow)
4240           return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4241                           CI->getArgOperand(1), /* IsNSW = */ true,
4242                           /* IsNUW = */ false);
4243         else
4244           return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4245                           CI->getArgOperand(1), /* IsNSW = */ false,
4246                           /* IsNUW*/ true);
4247       case Intrinsic::ssub_with_overflow:
4248       case Intrinsic::usub_with_overflow:
4249         if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT))
4250           return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
4251                           CI->getArgOperand(1));
4252 
4253         // The same reasoning as sadd/uadd above.
4254         if (F->getIntrinsicID() == Intrinsic::ssub_with_overflow)
4255           return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
4256                           CI->getArgOperand(1), /* IsNSW = */ true,
4257                           /* IsNUW = */ false);
4258         else
4259           return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
4260                           CI->getArgOperand(1), /* IsNSW = */ false,
4261                           /* IsNUW = */ true);
4262       case Intrinsic::smul_with_overflow:
4263       case Intrinsic::umul_with_overflow:
4264         return BinaryOp(Instruction::Mul, CI->getArgOperand(0),
4265                         CI->getArgOperand(1));
4266       default:
4267         break;
4268       }
4269   }
4270 
4271   default:
4272     break;
4273   }
4274 
4275   return None;
4276 }
4277 
4278 /// Helper function to createAddRecFromPHIWithCasts. We have a phi
4279 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
4280 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
4281 /// way. This function checks if \p Op, an operand of this SCEVAddExpr,
4282 /// follows one of the following patterns:
4283 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4284 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4285 /// If the SCEV expression of \p Op conforms with one of the expected patterns
4286 /// we return the type of the truncation operation, and indicate whether the
4287 /// truncated type should be treated as signed/unsigned by setting
4288 /// \p Signed to true/false, respectively.
4289 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
4290                                bool &Signed, ScalarEvolution &SE) {
4291   // The case where Op == SymbolicPHI (that is, with no type conversions on
4292   // the way) is handled by the regular add recurrence creating logic and
4293   // would have already been triggered in createAddRecForPHI. Reaching it here
4294   // means that createAddRecFromPHI had failed for this PHI before (e.g.,
4295   // because one of the other operands of the SCEVAddExpr updating this PHI is
4296   // not invariant).
4297   //
4298   // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
4299   // this case predicates that allow us to prove that Op == SymbolicPHI will
4300   // be added.
4301   if (Op == SymbolicPHI)
4302     return nullptr;
4303 
4304   unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
4305   unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
4306   if (SourceBits != NewBits)
4307     return nullptr;
4308 
4309   const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op);
4310   const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op);
4311   if (!SExt && !ZExt)
4312     return nullptr;
4313   const SCEVTruncateExpr *Trunc =
4314       SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand())
4315            : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand());
4316   if (!Trunc)
4317     return nullptr;
4318   const SCEV *X = Trunc->getOperand();
4319   if (X != SymbolicPHI)
4320     return nullptr;
4321   Signed = SExt != nullptr;
4322   return Trunc->getType();
4323 }
4324 
4325 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
4326   if (!PN->getType()->isIntegerTy())
4327     return nullptr;
4328   const Loop *L = LI.getLoopFor(PN->getParent());
4329   if (!L || L->getHeader() != PN->getParent())
4330     return nullptr;
4331   return L;
4332 }
4333 
4334 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
4335 // computation that updates the phi follows the following pattern:
4336 //   (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
4337 // which correspond to a phi->trunc->sext/zext->add->phi update chain.
4338 // If so, try to see if it can be rewritten as an AddRecExpr under some
4339 // Predicates. If successful, return them as a pair. Also cache the results
4340 // of the analysis.
4341 //
4342 // Example usage scenario:
4343 //    Say the Rewriter is called for the following SCEV:
4344 //         8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4345 //    where:
4346 //         %X = phi i64 (%Start, %BEValue)
4347 //    It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
4348 //    and call this function with %SymbolicPHI = %X.
4349 //
4350 //    The analysis will find that the value coming around the backedge has
4351 //    the following SCEV:
4352 //         BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4353 //    Upon concluding that this matches the desired pattern, the function
4354 //    will return the pair {NewAddRec, SmallPredsVec} where:
4355 //         NewAddRec = {%Start,+,%Step}
4356 //         SmallPredsVec = {P1, P2, P3} as follows:
4357 //           P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
4358 //           P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
4359 //           P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
4360 //    The returned pair means that SymbolicPHI can be rewritten into NewAddRec
4361 //    under the predicates {P1,P2,P3}.
4362 //    This predicated rewrite will be cached in PredicatedSCEVRewrites:
4363 //         PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
4364 //
4365 // TODO's:
4366 //
4367 // 1) Extend the Induction descriptor to also support inductions that involve
4368 //    casts: When needed (namely, when we are called in the context of the
4369 //    vectorizer induction analysis), a Set of cast instructions will be
4370 //    populated by this method, and provided back to isInductionPHI. This is
4371 //    needed to allow the vectorizer to properly record them to be ignored by
4372 //    the cost model and to avoid vectorizing them (otherwise these casts,
4373 //    which are redundant under the runtime overflow checks, will be
4374 //    vectorized, which can be costly).
4375 //
4376 // 2) Support additional induction/PHISCEV patterns: We also want to support
4377 //    inductions where the sext-trunc / zext-trunc operations (partly) occur
4378 //    after the induction update operation (the induction increment):
4379 //
4380 //      (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
4381 //    which correspond to a phi->add->trunc->sext/zext->phi update chain.
4382 //
4383 //      (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
4384 //    which correspond to a phi->trunc->add->sext/zext->phi update chain.
4385 //
4386 // 3) Outline common code with createAddRecFromPHI to avoid duplication.
4387 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4388 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
4389   SmallVector<const SCEVPredicate *, 3> Predicates;
4390 
4391   // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
4392   // return an AddRec expression under some predicate.
4393 
4394   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
4395   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
4396   assert(L && "Expecting an integer loop header phi");
4397 
4398   // The loop may have multiple entrances or multiple exits; we can analyze
4399   // this phi as an addrec if it has a unique entry value and a unique
4400   // backedge value.
4401   Value *BEValueV = nullptr, *StartValueV = nullptr;
4402   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4403     Value *V = PN->getIncomingValue(i);
4404     if (L->contains(PN->getIncomingBlock(i))) {
4405       if (!BEValueV) {
4406         BEValueV = V;
4407       } else if (BEValueV != V) {
4408         BEValueV = nullptr;
4409         break;
4410       }
4411     } else if (!StartValueV) {
4412       StartValueV = V;
4413     } else if (StartValueV != V) {
4414       StartValueV = nullptr;
4415       break;
4416     }
4417   }
4418   if (!BEValueV || !StartValueV)
4419     return None;
4420 
4421   const SCEV *BEValue = getSCEV(BEValueV);
4422 
4423   // If the value coming around the backedge is an add with the symbolic
4424   // value we just inserted, possibly with casts that we can ignore under
4425   // an appropriate runtime guard, then we found a simple induction variable!
4426   const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
4427   if (!Add)
4428     return None;
4429 
4430   // If there is a single occurrence of the symbolic value, possibly
4431   // casted, replace it with a recurrence.
4432   unsigned FoundIndex = Add->getNumOperands();
4433   Type *TruncTy = nullptr;
4434   bool Signed;
4435   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4436     if ((TruncTy =
4437              isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
4438       if (FoundIndex == e) {
4439         FoundIndex = i;
4440         break;
4441       }
4442 
4443   if (FoundIndex == Add->getNumOperands())
4444     return None;
4445 
4446   // Create an add with everything but the specified operand.
4447   SmallVector<const SCEV *, 8> Ops;
4448   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4449     if (i != FoundIndex)
4450       Ops.push_back(Add->getOperand(i));
4451   const SCEV *Accum = getAddExpr(Ops);
4452 
4453   // The runtime checks will not be valid if the step amount is
4454   // varying inside the loop.
4455   if (!isLoopInvariant(Accum, L))
4456     return None;
4457 
4458   // *** Part2: Create the predicates
4459 
4460   // Analysis was successful: we have a phi-with-cast pattern for which we
4461   // can return an AddRec expression under the following predicates:
4462   //
4463   // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
4464   //     fits within the truncated type (does not overflow) for i = 0 to n-1.
4465   // P2: An Equal predicate that guarantees that
4466   //     Start = (Ext ix (Trunc iy (Start) to ix) to iy)
4467   // P3: An Equal predicate that guarantees that
4468   //     Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
4469   //
4470   // As we next prove, the above predicates guarantee that:
4471   //     Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
4472   //
4473   //
4474   // More formally, we want to prove that:
4475   //     Expr(i+1) = Start + (i+1) * Accum
4476   //               = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4477   //
4478   // Given that:
4479   // 1) Expr(0) = Start
4480   // 2) Expr(1) = Start + Accum
4481   //            = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
4482   // 3) Induction hypothesis (step i):
4483   //    Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
4484   //
4485   // Proof:
4486   //  Expr(i+1) =
4487   //   = Start + (i+1)*Accum
4488   //   = (Start + i*Accum) + Accum
4489   //   = Expr(i) + Accum
4490   //   = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
4491   //                                                             :: from step i
4492   //
4493   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
4494   //
4495   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
4496   //     + (Ext ix (Trunc iy (Accum) to ix) to iy)
4497   //     + Accum                                                     :: from P3
4498   //
4499   //   = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
4500   //     + Accum                            :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
4501   //
4502   //   = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
4503   //   = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4504   //
4505   // By induction, the same applies to all iterations 1<=i<n:
4506   //
4507 
4508   // Create a truncated addrec for which we will add a no overflow check (P1).
4509   const SCEV *StartVal = getSCEV(StartValueV);
4510   const SCEV *PHISCEV =
4511       getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
4512                     getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap);
4513 
4514   // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
4515   // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
4516   // will be constant.
4517   //
4518   //  If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
4519   // add P1.
4520   if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
4521     SCEVWrapPredicate::IncrementWrapFlags AddedFlags =
4522         Signed ? SCEVWrapPredicate::IncrementNSSW
4523                : SCEVWrapPredicate::IncrementNUSW;
4524     const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
4525     Predicates.push_back(AddRecPred);
4526   } else
4527     assert(isa<SCEVConstant>(PHISCEV) && "Expected constant SCEV");
4528 
4529   // Create the Equal Predicates P2,P3:
4530 
4531   // It is possible that the predicates P2 and/or P3 are computable at
4532   // compile time due to StartVal and/or Accum being constants.
4533   // If either one is, then we can check that now and escape if either P2
4534   // or P3 is false.
4535 
4536   // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
4537   // for each of StartVal and Accum
4538   auto GetExtendedExpr = [&](const SCEV *Expr) -> const SCEV * {
4539     assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant");
4540     const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
4541     const SCEV *ExtendedExpr =
4542         Signed ? getSignExtendExpr(TruncatedExpr, Expr->getType())
4543                : getZeroExtendExpr(TruncatedExpr, Expr->getType());
4544     return ExtendedExpr;
4545   };
4546 
4547   // Given:
4548   //  ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
4549   //               = GetExtendedExpr(Expr)
4550   // Determine whether the predicate P: Expr == ExtendedExpr
4551   // is known to be false at compile time
4552   auto PredIsKnownFalse = [&](const SCEV *Expr,
4553                               const SCEV *ExtendedExpr) -> bool {
4554     return Expr != ExtendedExpr &&
4555            isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr);
4556   };
4557 
4558   const SCEV *StartExtended = GetExtendedExpr(StartVal);
4559   if (PredIsKnownFalse(StartVal, StartExtended)) {
4560     DEBUG(dbgs() << "P2 is compile-time false\n";);
4561     return None;
4562   }
4563 
4564   const SCEV *AccumExtended = GetExtendedExpr(Accum);
4565   if (PredIsKnownFalse(Accum, AccumExtended)) {
4566     DEBUG(dbgs() << "P3 is compile-time false\n";);
4567     return None;
4568   }
4569 
4570   auto AppendPredicate = [&](const SCEV *Expr,
4571                              const SCEV *ExtendedExpr) -> void {
4572     if (Expr != ExtendedExpr &&
4573         !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
4574       const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
4575       DEBUG (dbgs() << "Added Predicate: " << *Pred);
4576       Predicates.push_back(Pred);
4577     }
4578   };
4579 
4580   AppendPredicate(StartVal, StartExtended);
4581   AppendPredicate(Accum, AccumExtended);
4582 
4583   // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
4584   // which the casts had been folded away. The caller can rewrite SymbolicPHI
4585   // into NewAR if it will also add the runtime overflow checks specified in
4586   // Predicates.
4587   auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap);
4588 
4589   std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
4590       std::make_pair(NewAR, Predicates);
4591   // Remember the result of the analysis for this SCEV at this locayyytion.
4592   PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
4593   return PredRewrite;
4594 }
4595 
4596 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4597 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) {
4598   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
4599   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
4600   if (!L)
4601     return None;
4602 
4603   // Check to see if we already analyzed this PHI.
4604   auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
4605   if (I != PredicatedSCEVRewrites.end()) {
4606     std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
4607         I->second;
4608     // Analysis was done before and failed to create an AddRec:
4609     if (Rewrite.first == SymbolicPHI)
4610       return None;
4611     // Analysis was done before and succeeded to create an AddRec under
4612     // a predicate:
4613     assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec");
4614     assert(!(Rewrite.second).empty() && "Expected to find Predicates");
4615     return Rewrite;
4616   }
4617 
4618   Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4619     Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
4620 
4621   // Record in the cache that the analysis failed
4622   if (!Rewrite) {
4623     SmallVector<const SCEVPredicate *, 3> Predicates;
4624     PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
4625     return None;
4626   }
4627 
4628   return Rewrite;
4629 }
4630 
4631 /// A helper function for createAddRecFromPHI to handle simple cases.
4632 ///
4633 /// This function tries to find an AddRec expression for the simplest (yet most
4634 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
4635 /// If it fails, createAddRecFromPHI will use a more general, but slow,
4636 /// technique for finding the AddRec expression.
4637 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
4638                                                       Value *BEValueV,
4639                                                       Value *StartValueV) {
4640   const Loop *L = LI.getLoopFor(PN->getParent());
4641   assert(L && L->getHeader() == PN->getParent());
4642   assert(BEValueV && StartValueV);
4643 
4644   auto BO = MatchBinaryOp(BEValueV, DT);
4645   if (!BO)
4646     return nullptr;
4647 
4648   if (BO->Opcode != Instruction::Add)
4649     return nullptr;
4650 
4651   const SCEV *Accum = nullptr;
4652   if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
4653     Accum = getSCEV(BO->RHS);
4654   else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
4655     Accum = getSCEV(BO->LHS);
4656 
4657   if (!Accum)
4658     return nullptr;
4659 
4660   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4661   if (BO->IsNUW)
4662     Flags = setFlags(Flags, SCEV::FlagNUW);
4663   if (BO->IsNSW)
4664     Flags = setFlags(Flags, SCEV::FlagNSW);
4665 
4666   const SCEV *StartVal = getSCEV(StartValueV);
4667   const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
4668 
4669   ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
4670 
4671   // We can add Flags to the post-inc expression only if we
4672   // know that it is *undefined behavior* for BEValueV to
4673   // overflow.
4674   if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
4675     if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
4676       (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
4677 
4678   return PHISCEV;
4679 }
4680 
4681 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
4682   const Loop *L = LI.getLoopFor(PN->getParent());
4683   if (!L || L->getHeader() != PN->getParent())
4684     return nullptr;
4685 
4686   // The loop may have multiple entrances or multiple exits; we can analyze
4687   // this phi as an addrec if it has a unique entry value and a unique
4688   // backedge value.
4689   Value *BEValueV = nullptr, *StartValueV = nullptr;
4690   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4691     Value *V = PN->getIncomingValue(i);
4692     if (L->contains(PN->getIncomingBlock(i))) {
4693       if (!BEValueV) {
4694         BEValueV = V;
4695       } else if (BEValueV != V) {
4696         BEValueV = nullptr;
4697         break;
4698       }
4699     } else if (!StartValueV) {
4700       StartValueV = V;
4701     } else if (StartValueV != V) {
4702       StartValueV = nullptr;
4703       break;
4704     }
4705   }
4706   if (!BEValueV || !StartValueV)
4707     return nullptr;
4708 
4709   assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
4710          "PHI node already processed?");
4711 
4712   // First, try to find AddRec expression without creating a fictituos symbolic
4713   // value for PN.
4714   if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
4715     return S;
4716 
4717   // Handle PHI node value symbolically.
4718   const SCEV *SymbolicName = getUnknown(PN);
4719   ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName});
4720 
4721   // Using this symbolic name for the PHI, analyze the value coming around
4722   // the back-edge.
4723   const SCEV *BEValue = getSCEV(BEValueV);
4724 
4725   // NOTE: If BEValue is loop invariant, we know that the PHI node just
4726   // has a special value for the first iteration of the loop.
4727 
4728   // If the value coming around the backedge is an add with the symbolic
4729   // value we just inserted, then we found a simple induction variable!
4730   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
4731     // If there is a single occurrence of the symbolic value, replace it
4732     // with a recurrence.
4733     unsigned FoundIndex = Add->getNumOperands();
4734     for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4735       if (Add->getOperand(i) == SymbolicName)
4736         if (FoundIndex == e) {
4737           FoundIndex = i;
4738           break;
4739         }
4740 
4741     if (FoundIndex != Add->getNumOperands()) {
4742       // Create an add with everything but the specified operand.
4743       SmallVector<const SCEV *, 8> Ops;
4744       for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4745         if (i != FoundIndex)
4746           Ops.push_back(Add->getOperand(i));
4747       const SCEV *Accum = getAddExpr(Ops);
4748 
4749       // This is not a valid addrec if the step amount is varying each
4750       // loop iteration, but is not itself an addrec in this loop.
4751       if (isLoopInvariant(Accum, L) ||
4752           (isa<SCEVAddRecExpr>(Accum) &&
4753            cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
4754         SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4755 
4756         if (auto BO = MatchBinaryOp(BEValueV, DT)) {
4757           if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
4758             if (BO->IsNUW)
4759               Flags = setFlags(Flags, SCEV::FlagNUW);
4760             if (BO->IsNSW)
4761               Flags = setFlags(Flags, SCEV::FlagNSW);
4762           }
4763         } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
4764           // If the increment is an inbounds GEP, then we know the address
4765           // space cannot be wrapped around. We cannot make any guarantee
4766           // about signed or unsigned overflow because pointers are
4767           // unsigned but we may have a negative index from the base
4768           // pointer. We can guarantee that no unsigned wrap occurs if the
4769           // indices form a positive value.
4770           if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
4771             Flags = setFlags(Flags, SCEV::FlagNW);
4772 
4773             const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
4774             if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
4775               Flags = setFlags(Flags, SCEV::FlagNUW);
4776           }
4777 
4778           // We cannot transfer nuw and nsw flags from subtraction
4779           // operations -- sub nuw X, Y is not the same as add nuw X, -Y
4780           // for instance.
4781         }
4782 
4783         const SCEV *StartVal = getSCEV(StartValueV);
4784         const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
4785 
4786         // Okay, for the entire analysis of this edge we assumed the PHI
4787         // to be symbolic.  We now need to go back and purge all of the
4788         // entries for the scalars that use the symbolic expression.
4789         forgetSymbolicName(PN, SymbolicName);
4790         ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
4791 
4792         // We can add Flags to the post-inc expression only if we
4793         // know that it is *undefined behavior* for BEValueV to
4794         // overflow.
4795         if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
4796           if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
4797             (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
4798 
4799         return PHISCEV;
4800       }
4801     }
4802   } else {
4803     // Otherwise, this could be a loop like this:
4804     //     i = 0;  for (j = 1; ..; ++j) { ....  i = j; }
4805     // In this case, j = {1,+,1}  and BEValue is j.
4806     // Because the other in-value of i (0) fits the evolution of BEValue
4807     // i really is an addrec evolution.
4808     //
4809     // We can generalize this saying that i is the shifted value of BEValue
4810     // by one iteration:
4811     //   PHI(f(0), f({1,+,1})) --> f({0,+,1})
4812     const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
4813     const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this);
4814     if (Shifted != getCouldNotCompute() &&
4815         Start != getCouldNotCompute()) {
4816       const SCEV *StartVal = getSCEV(StartValueV);
4817       if (Start == StartVal) {
4818         // Okay, for the entire analysis of this edge we assumed the PHI
4819         // to be symbolic.  We now need to go back and purge all of the
4820         // entries for the scalars that use the symbolic expression.
4821         forgetSymbolicName(PN, SymbolicName);
4822         ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted;
4823         return Shifted;
4824       }
4825     }
4826   }
4827 
4828   // Remove the temporary PHI node SCEV that has been inserted while intending
4829   // to create an AddRecExpr for this PHI node. We can not keep this temporary
4830   // as it will prevent later (possibly simpler) SCEV expressions to be added
4831   // to the ValueExprMap.
4832   eraseValueFromMap(PN);
4833 
4834   return nullptr;
4835 }
4836 
4837 // Checks if the SCEV S is available at BB.  S is considered available at BB
4838 // if S can be materialized at BB without introducing a fault.
4839 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
4840                                BasicBlock *BB) {
4841   struct CheckAvailable {
4842     bool TraversalDone = false;
4843     bool Available = true;
4844 
4845     const Loop *L = nullptr;  // The loop BB is in (can be nullptr)
4846     BasicBlock *BB = nullptr;
4847     DominatorTree &DT;
4848 
4849     CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
4850       : L(L), BB(BB), DT(DT) {}
4851 
4852     bool setUnavailable() {
4853       TraversalDone = true;
4854       Available = false;
4855       return false;
4856     }
4857 
4858     bool follow(const SCEV *S) {
4859       switch (S->getSCEVType()) {
4860       case scConstant: case scTruncate: case scZeroExtend: case scSignExtend:
4861       case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr:
4862         // These expressions are available if their operand(s) is/are.
4863         return true;
4864 
4865       case scAddRecExpr: {
4866         // We allow add recurrences that are on the loop BB is in, or some
4867         // outer loop.  This guarantees availability because the value of the
4868         // add recurrence at BB is simply the "current" value of the induction
4869         // variable.  We can relax this in the future; for instance an add
4870         // recurrence on a sibling dominating loop is also available at BB.
4871         const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
4872         if (L && (ARLoop == L || ARLoop->contains(L)))
4873           return true;
4874 
4875         return setUnavailable();
4876       }
4877 
4878       case scUnknown: {
4879         // For SCEVUnknown, we check for simple dominance.
4880         const auto *SU = cast<SCEVUnknown>(S);
4881         Value *V = SU->getValue();
4882 
4883         if (isa<Argument>(V))
4884           return false;
4885 
4886         if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
4887           return false;
4888 
4889         return setUnavailable();
4890       }
4891 
4892       case scUDivExpr:
4893       case scCouldNotCompute:
4894         // We do not try to smart about these at all.
4895         return setUnavailable();
4896       }
4897       llvm_unreachable("switch should be fully covered!");
4898     }
4899 
4900     bool isDone() { return TraversalDone; }
4901   };
4902 
4903   CheckAvailable CA(L, BB, DT);
4904   SCEVTraversal<CheckAvailable> ST(CA);
4905 
4906   ST.visitAll(S);
4907   return CA.Available;
4908 }
4909 
4910 // Try to match a control flow sequence that branches out at BI and merges back
4911 // at Merge into a "C ? LHS : RHS" select pattern.  Return true on a successful
4912 // match.
4913 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
4914                           Value *&C, Value *&LHS, Value *&RHS) {
4915   C = BI->getCondition();
4916 
4917   BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
4918   BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
4919 
4920   if (!LeftEdge.isSingleEdge())
4921     return false;
4922 
4923   assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
4924 
4925   Use &LeftUse = Merge->getOperandUse(0);
4926   Use &RightUse = Merge->getOperandUse(1);
4927 
4928   if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
4929     LHS = LeftUse;
4930     RHS = RightUse;
4931     return true;
4932   }
4933 
4934   if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
4935     LHS = RightUse;
4936     RHS = LeftUse;
4937     return true;
4938   }
4939 
4940   return false;
4941 }
4942 
4943 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
4944   auto IsReachable =
4945       [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
4946   if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
4947     const Loop *L = LI.getLoopFor(PN->getParent());
4948 
4949     // We don't want to break LCSSA, even in a SCEV expression tree.
4950     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
4951       if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
4952         return nullptr;
4953 
4954     // Try to match
4955     //
4956     //  br %cond, label %left, label %right
4957     // left:
4958     //  br label %merge
4959     // right:
4960     //  br label %merge
4961     // merge:
4962     //  V = phi [ %x, %left ], [ %y, %right ]
4963     //
4964     // as "select %cond, %x, %y"
4965 
4966     BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
4967     assert(IDom && "At least the entry block should dominate PN");
4968 
4969     auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
4970     Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
4971 
4972     if (BI && BI->isConditional() &&
4973         BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
4974         IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
4975         IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
4976       return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
4977   }
4978 
4979   return nullptr;
4980 }
4981 
4982 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
4983   if (const SCEV *S = createAddRecFromPHI(PN))
4984     return S;
4985 
4986   if (const SCEV *S = createNodeFromSelectLikePHI(PN))
4987     return S;
4988 
4989   // If the PHI has a single incoming value, follow that value, unless the
4990   // PHI's incoming blocks are in a different loop, in which case doing so
4991   // risks breaking LCSSA form. Instcombine would normally zap these, but
4992   // it doesn't have DominatorTree information, so it may miss cases.
4993   if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC}))
4994     if (LI.replacementPreservesLCSSAForm(PN, V))
4995       return getSCEV(V);
4996 
4997   // If it's not a loop phi, we can't handle it yet.
4998   return getUnknown(PN);
4999 }
5000 
5001 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I,
5002                                                       Value *Cond,
5003                                                       Value *TrueVal,
5004                                                       Value *FalseVal) {
5005   // Handle "constant" branch or select. This can occur for instance when a
5006   // loop pass transforms an inner loop and moves on to process the outer loop.
5007   if (auto *CI = dyn_cast<ConstantInt>(Cond))
5008     return getSCEV(CI->isOne() ? TrueVal : FalseVal);
5009 
5010   // Try to match some simple smax or umax patterns.
5011   auto *ICI = dyn_cast<ICmpInst>(Cond);
5012   if (!ICI)
5013     return getUnknown(I);
5014 
5015   Value *LHS = ICI->getOperand(0);
5016   Value *RHS = ICI->getOperand(1);
5017 
5018   switch (ICI->getPredicate()) {
5019   case ICmpInst::ICMP_SLT:
5020   case ICmpInst::ICMP_SLE:
5021     std::swap(LHS, RHS);
5022     LLVM_FALLTHROUGH;
5023   case ICmpInst::ICMP_SGT:
5024   case ICmpInst::ICMP_SGE:
5025     // a >s b ? a+x : b+x  ->  smax(a, b)+x
5026     // a >s b ? b+x : a+x  ->  smin(a, b)+x
5027     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5028       const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType());
5029       const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType());
5030       const SCEV *LA = getSCEV(TrueVal);
5031       const SCEV *RA = getSCEV(FalseVal);
5032       const SCEV *LDiff = getMinusSCEV(LA, LS);
5033       const SCEV *RDiff = getMinusSCEV(RA, RS);
5034       if (LDiff == RDiff)
5035         return getAddExpr(getSMaxExpr(LS, RS), LDiff);
5036       LDiff = getMinusSCEV(LA, RS);
5037       RDiff = getMinusSCEV(RA, LS);
5038       if (LDiff == RDiff)
5039         return getAddExpr(getSMinExpr(LS, RS), LDiff);
5040     }
5041     break;
5042   case ICmpInst::ICMP_ULT:
5043   case ICmpInst::ICMP_ULE:
5044     std::swap(LHS, RHS);
5045     LLVM_FALLTHROUGH;
5046   case ICmpInst::ICMP_UGT:
5047   case ICmpInst::ICMP_UGE:
5048     // a >u b ? a+x : b+x  ->  umax(a, b)+x
5049     // a >u b ? b+x : a+x  ->  umin(a, b)+x
5050     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5051       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5052       const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType());
5053       const SCEV *LA = getSCEV(TrueVal);
5054       const SCEV *RA = getSCEV(FalseVal);
5055       const SCEV *LDiff = getMinusSCEV(LA, LS);
5056       const SCEV *RDiff = getMinusSCEV(RA, RS);
5057       if (LDiff == RDiff)
5058         return getAddExpr(getUMaxExpr(LS, RS), LDiff);
5059       LDiff = getMinusSCEV(LA, RS);
5060       RDiff = getMinusSCEV(RA, LS);
5061       if (LDiff == RDiff)
5062         return getAddExpr(getUMinExpr(LS, RS), LDiff);
5063     }
5064     break;
5065   case ICmpInst::ICMP_NE:
5066     // n != 0 ? n+x : 1+x  ->  umax(n, 1)+x
5067     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5068         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5069       const SCEV *One = getOne(I->getType());
5070       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5071       const SCEV *LA = getSCEV(TrueVal);
5072       const SCEV *RA = getSCEV(FalseVal);
5073       const SCEV *LDiff = getMinusSCEV(LA, LS);
5074       const SCEV *RDiff = getMinusSCEV(RA, One);
5075       if (LDiff == RDiff)
5076         return getAddExpr(getUMaxExpr(One, LS), LDiff);
5077     }
5078     break;
5079   case ICmpInst::ICMP_EQ:
5080     // n == 0 ? 1+x : n+x  ->  umax(n, 1)+x
5081     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5082         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5083       const SCEV *One = getOne(I->getType());
5084       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5085       const SCEV *LA = getSCEV(TrueVal);
5086       const SCEV *RA = getSCEV(FalseVal);
5087       const SCEV *LDiff = getMinusSCEV(LA, One);
5088       const SCEV *RDiff = getMinusSCEV(RA, LS);
5089       if (LDiff == RDiff)
5090         return getAddExpr(getUMaxExpr(One, LS), LDiff);
5091     }
5092     break;
5093   default:
5094     break;
5095   }
5096 
5097   return getUnknown(I);
5098 }
5099 
5100 /// Expand GEP instructions into add and multiply operations. This allows them
5101 /// to be analyzed by regular SCEV code.
5102 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
5103   // Don't attempt to analyze GEPs over unsized objects.
5104   if (!GEP->getSourceElementType()->isSized())
5105     return getUnknown(GEP);
5106 
5107   SmallVector<const SCEV *, 4> IndexExprs;
5108   for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
5109     IndexExprs.push_back(getSCEV(*Index));
5110   return getGEPExpr(GEP, IndexExprs);
5111 }
5112 
5113 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) {
5114   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5115     return C->getAPInt().countTrailingZeros();
5116 
5117   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
5118     return std::min(GetMinTrailingZeros(T->getOperand()),
5119                     (uint32_t)getTypeSizeInBits(T->getType()));
5120 
5121   if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
5122     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5123     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5124                ? getTypeSizeInBits(E->getType())
5125                : OpRes;
5126   }
5127 
5128   if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
5129     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5130     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5131                ? getTypeSizeInBits(E->getType())
5132                : OpRes;
5133   }
5134 
5135   if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
5136     // The result is the min of all operands results.
5137     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5138     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5139       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5140     return MinOpRes;
5141   }
5142 
5143   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
5144     // The result is the sum of all operands results.
5145     uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
5146     uint32_t BitWidth = getTypeSizeInBits(M->getType());
5147     for (unsigned i = 1, e = M->getNumOperands();
5148          SumOpRes != BitWidth && i != e; ++i)
5149       SumOpRes =
5150           std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth);
5151     return SumOpRes;
5152   }
5153 
5154   if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
5155     // The result is the min of all operands results.
5156     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5157     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5158       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5159     return MinOpRes;
5160   }
5161 
5162   if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
5163     // The result is the min of all operands results.
5164     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5165     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5166       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5167     return MinOpRes;
5168   }
5169 
5170   if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
5171     // The result is the min of all operands results.
5172     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5173     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5174       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5175     return MinOpRes;
5176   }
5177 
5178   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5179     // For a SCEVUnknown, ask ValueTracking.
5180     KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT);
5181     return Known.countMinTrailingZeros();
5182   }
5183 
5184   // SCEVUDivExpr
5185   return 0;
5186 }
5187 
5188 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
5189   auto I = MinTrailingZerosCache.find(S);
5190   if (I != MinTrailingZerosCache.end())
5191     return I->second;
5192 
5193   uint32_t Result = GetMinTrailingZerosImpl(S);
5194   auto InsertPair = MinTrailingZerosCache.insert({S, Result});
5195   assert(InsertPair.second && "Should insert a new key");
5196   return InsertPair.first->second;
5197 }
5198 
5199 /// Helper method to assign a range to V from metadata present in the IR.
5200 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
5201   if (Instruction *I = dyn_cast<Instruction>(V))
5202     if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
5203       return getConstantRangeFromMetadata(*MD);
5204 
5205   return None;
5206 }
5207 
5208 /// Determine the range for a particular SCEV.  If SignHint is
5209 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
5210 /// with a "cleaner" unsigned (resp. signed) representation.
5211 const ConstantRange &
5212 ScalarEvolution::getRangeRef(const SCEV *S,
5213                              ScalarEvolution::RangeSignHint SignHint) {
5214   DenseMap<const SCEV *, ConstantRange> &Cache =
5215       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
5216                                                        : SignedRanges;
5217 
5218   // See if we've computed this range already.
5219   DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
5220   if (I != Cache.end())
5221     return I->second;
5222 
5223   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5224     return setRange(C, SignHint, ConstantRange(C->getAPInt()));
5225 
5226   unsigned BitWidth = getTypeSizeInBits(S->getType());
5227   ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
5228 
5229   // If the value has known zeros, the maximum value will have those known zeros
5230   // as well.
5231   uint32_t TZ = GetMinTrailingZeros(S);
5232   if (TZ != 0) {
5233     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
5234       ConservativeResult =
5235           ConstantRange(APInt::getMinValue(BitWidth),
5236                         APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
5237     else
5238       ConservativeResult = ConstantRange(
5239           APInt::getSignedMinValue(BitWidth),
5240           APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
5241   }
5242 
5243   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
5244     ConstantRange X = getRangeRef(Add->getOperand(0), SignHint);
5245     for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
5246       X = X.add(getRangeRef(Add->getOperand(i), SignHint));
5247     return setRange(Add, SignHint, ConservativeResult.intersectWith(X));
5248   }
5249 
5250   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
5251     ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint);
5252     for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
5253       X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint));
5254     return setRange(Mul, SignHint, ConservativeResult.intersectWith(X));
5255   }
5256 
5257   if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
5258     ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint);
5259     for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
5260       X = X.smax(getRangeRef(SMax->getOperand(i), SignHint));
5261     return setRange(SMax, SignHint, ConservativeResult.intersectWith(X));
5262   }
5263 
5264   if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
5265     ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint);
5266     for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
5267       X = X.umax(getRangeRef(UMax->getOperand(i), SignHint));
5268     return setRange(UMax, SignHint, ConservativeResult.intersectWith(X));
5269   }
5270 
5271   if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
5272     ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint);
5273     ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint);
5274     return setRange(UDiv, SignHint,
5275                     ConservativeResult.intersectWith(X.udiv(Y)));
5276   }
5277 
5278   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
5279     ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint);
5280     return setRange(ZExt, SignHint,
5281                     ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
5282   }
5283 
5284   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
5285     ConstantRange X = getRangeRef(SExt->getOperand(), SignHint);
5286     return setRange(SExt, SignHint,
5287                     ConservativeResult.intersectWith(X.signExtend(BitWidth)));
5288   }
5289 
5290   if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
5291     ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint);
5292     return setRange(Trunc, SignHint,
5293                     ConservativeResult.intersectWith(X.truncate(BitWidth)));
5294   }
5295 
5296   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
5297     // If there's no unsigned wrap, the value will never be less than its
5298     // initial value.
5299     if (AddRec->hasNoUnsignedWrap())
5300       if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
5301         if (!C->getValue()->isZero())
5302           ConservativeResult = ConservativeResult.intersectWith(
5303               ConstantRange(C->getAPInt(), APInt(BitWidth, 0)));
5304 
5305     // If there's no signed wrap, and all the operands have the same sign or
5306     // zero, the value won't ever change sign.
5307     if (AddRec->hasNoSignedWrap()) {
5308       bool AllNonNeg = true;
5309       bool AllNonPos = true;
5310       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
5311         if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
5312         if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
5313       }
5314       if (AllNonNeg)
5315         ConservativeResult = ConservativeResult.intersectWith(
5316           ConstantRange(APInt(BitWidth, 0),
5317                         APInt::getSignedMinValue(BitWidth)));
5318       else if (AllNonPos)
5319         ConservativeResult = ConservativeResult.intersectWith(
5320           ConstantRange(APInt::getSignedMinValue(BitWidth),
5321                         APInt(BitWidth, 1)));
5322     }
5323 
5324     // TODO: non-affine addrec
5325     if (AddRec->isAffine()) {
5326       const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
5327       if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
5328           getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
5329         auto RangeFromAffine = getRangeForAffineAR(
5330             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
5331             BitWidth);
5332         if (!RangeFromAffine.isFullSet())
5333           ConservativeResult =
5334               ConservativeResult.intersectWith(RangeFromAffine);
5335 
5336         auto RangeFromFactoring = getRangeViaFactoring(
5337             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
5338             BitWidth);
5339         if (!RangeFromFactoring.isFullSet())
5340           ConservativeResult =
5341               ConservativeResult.intersectWith(RangeFromFactoring);
5342       }
5343     }
5344 
5345     return setRange(AddRec, SignHint, std::move(ConservativeResult));
5346   }
5347 
5348   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5349     // Check if the IR explicitly contains !range metadata.
5350     Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
5351     if (MDRange.hasValue())
5352       ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue());
5353 
5354     // Split here to avoid paying the compile-time cost of calling both
5355     // computeKnownBits and ComputeNumSignBits.  This restriction can be lifted
5356     // if needed.
5357     const DataLayout &DL = getDataLayout();
5358     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
5359       // For a SCEVUnknown, ask ValueTracking.
5360       KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
5361       if (Known.One != ~Known.Zero + 1)
5362         ConservativeResult =
5363             ConservativeResult.intersectWith(ConstantRange(Known.One,
5364                                                            ~Known.Zero + 1));
5365     } else {
5366       assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED &&
5367              "generalize as needed!");
5368       unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
5369       if (NS > 1)
5370         ConservativeResult = ConservativeResult.intersectWith(
5371             ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
5372                           APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1));
5373     }
5374 
5375     return setRange(U, SignHint, std::move(ConservativeResult));
5376   }
5377 
5378   return setRange(S, SignHint, std::move(ConservativeResult));
5379 }
5380 
5381 // Given a StartRange, Step and MaxBECount for an expression compute a range of
5382 // values that the expression can take. Initially, the expression has a value
5383 // from StartRange and then is changed by Step up to MaxBECount times. Signed
5384 // argument defines if we treat Step as signed or unsigned.
5385 static ConstantRange getRangeForAffineARHelper(APInt Step,
5386                                                const ConstantRange &StartRange,
5387                                                const APInt &MaxBECount,
5388                                                unsigned BitWidth, bool Signed) {
5389   // If either Step or MaxBECount is 0, then the expression won't change, and we
5390   // just need to return the initial range.
5391   if (Step == 0 || MaxBECount == 0)
5392     return StartRange;
5393 
5394   // If we don't know anything about the initial value (i.e. StartRange is
5395   // FullRange), then we don't know anything about the final range either.
5396   // Return FullRange.
5397   if (StartRange.isFullSet())
5398     return ConstantRange(BitWidth, /* isFullSet = */ true);
5399 
5400   // If Step is signed and negative, then we use its absolute value, but we also
5401   // note that we're moving in the opposite direction.
5402   bool Descending = Signed && Step.isNegative();
5403 
5404   if (Signed)
5405     // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
5406     // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
5407     // This equations hold true due to the well-defined wrap-around behavior of
5408     // APInt.
5409     Step = Step.abs();
5410 
5411   // Check if Offset is more than full span of BitWidth. If it is, the
5412   // expression is guaranteed to overflow.
5413   if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
5414     return ConstantRange(BitWidth, /* isFullSet = */ true);
5415 
5416   // Offset is by how much the expression can change. Checks above guarantee no
5417   // overflow here.
5418   APInt Offset = Step * MaxBECount;
5419 
5420   // Minimum value of the final range will match the minimal value of StartRange
5421   // if the expression is increasing and will be decreased by Offset otherwise.
5422   // Maximum value of the final range will match the maximal value of StartRange
5423   // if the expression is decreasing and will be increased by Offset otherwise.
5424   APInt StartLower = StartRange.getLower();
5425   APInt StartUpper = StartRange.getUpper() - 1;
5426   APInt MovedBoundary = Descending ? (StartLower - std::move(Offset))
5427                                    : (StartUpper + std::move(Offset));
5428 
5429   // It's possible that the new minimum/maximum value will fall into the initial
5430   // range (due to wrap around). This means that the expression can take any
5431   // value in this bitwidth, and we have to return full range.
5432   if (StartRange.contains(MovedBoundary))
5433     return ConstantRange(BitWidth, /* isFullSet = */ true);
5434 
5435   APInt NewLower =
5436       Descending ? std::move(MovedBoundary) : std::move(StartLower);
5437   APInt NewUpper =
5438       Descending ? std::move(StartUpper) : std::move(MovedBoundary);
5439   NewUpper += 1;
5440 
5441   // If we end up with full range, return a proper full range.
5442   if (NewLower == NewUpper)
5443     return ConstantRange(BitWidth, /* isFullSet = */ true);
5444 
5445   // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
5446   return ConstantRange(std::move(NewLower), std::move(NewUpper));
5447 }
5448 
5449 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
5450                                                    const SCEV *Step,
5451                                                    const SCEV *MaxBECount,
5452                                                    unsigned BitWidth) {
5453   assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&
5454          getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
5455          "Precondition!");
5456 
5457   MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType());
5458   APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount);
5459 
5460   // First, consider step signed.
5461   ConstantRange StartSRange = getSignedRange(Start);
5462   ConstantRange StepSRange = getSignedRange(Step);
5463 
5464   // If Step can be both positive and negative, we need to find ranges for the
5465   // maximum absolute step values in both directions and union them.
5466   ConstantRange SR =
5467       getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange,
5468                                 MaxBECountValue, BitWidth, /* Signed = */ true);
5469   SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(),
5470                                               StartSRange, MaxBECountValue,
5471                                               BitWidth, /* Signed = */ true));
5472 
5473   // Next, consider step unsigned.
5474   ConstantRange UR = getRangeForAffineARHelper(
5475       getUnsignedRangeMax(Step), getUnsignedRange(Start),
5476       MaxBECountValue, BitWidth, /* Signed = */ false);
5477 
5478   // Finally, intersect signed and unsigned ranges.
5479   return SR.intersectWith(UR);
5480 }
5481 
5482 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
5483                                                     const SCEV *Step,
5484                                                     const SCEV *MaxBECount,
5485                                                     unsigned BitWidth) {
5486   //    RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
5487   // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
5488 
5489   struct SelectPattern {
5490     Value *Condition = nullptr;
5491     APInt TrueValue;
5492     APInt FalseValue;
5493 
5494     explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
5495                            const SCEV *S) {
5496       Optional<unsigned> CastOp;
5497       APInt Offset(BitWidth, 0);
5498 
5499       assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&
5500              "Should be!");
5501 
5502       // Peel off a constant offset:
5503       if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
5504         // In the future we could consider being smarter here and handle
5505         // {Start+Step,+,Step} too.
5506         if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
5507           return;
5508 
5509         Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
5510         S = SA->getOperand(1);
5511       }
5512 
5513       // Peel off a cast operation
5514       if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) {
5515         CastOp = SCast->getSCEVType();
5516         S = SCast->getOperand();
5517       }
5518 
5519       using namespace llvm::PatternMatch;
5520 
5521       auto *SU = dyn_cast<SCEVUnknown>(S);
5522       const APInt *TrueVal, *FalseVal;
5523       if (!SU ||
5524           !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
5525                                           m_APInt(FalseVal)))) {
5526         Condition = nullptr;
5527         return;
5528       }
5529 
5530       TrueValue = *TrueVal;
5531       FalseValue = *FalseVal;
5532 
5533       // Re-apply the cast we peeled off earlier
5534       if (CastOp.hasValue())
5535         switch (*CastOp) {
5536         default:
5537           llvm_unreachable("Unknown SCEV cast type!");
5538 
5539         case scTruncate:
5540           TrueValue = TrueValue.trunc(BitWidth);
5541           FalseValue = FalseValue.trunc(BitWidth);
5542           break;
5543         case scZeroExtend:
5544           TrueValue = TrueValue.zext(BitWidth);
5545           FalseValue = FalseValue.zext(BitWidth);
5546           break;
5547         case scSignExtend:
5548           TrueValue = TrueValue.sext(BitWidth);
5549           FalseValue = FalseValue.sext(BitWidth);
5550           break;
5551         }
5552 
5553       // Re-apply the constant offset we peeled off earlier
5554       TrueValue += Offset;
5555       FalseValue += Offset;
5556     }
5557 
5558     bool isRecognized() { return Condition != nullptr; }
5559   };
5560 
5561   SelectPattern StartPattern(*this, BitWidth, Start);
5562   if (!StartPattern.isRecognized())
5563     return ConstantRange(BitWidth, /* isFullSet = */ true);
5564 
5565   SelectPattern StepPattern(*this, BitWidth, Step);
5566   if (!StepPattern.isRecognized())
5567     return ConstantRange(BitWidth, /* isFullSet = */ true);
5568 
5569   if (StartPattern.Condition != StepPattern.Condition) {
5570     // We don't handle this case today; but we could, by considering four
5571     // possibilities below instead of two. I'm not sure if there are cases where
5572     // that will help over what getRange already does, though.
5573     return ConstantRange(BitWidth, /* isFullSet = */ true);
5574   }
5575 
5576   // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
5577   // construct arbitrary general SCEV expressions here.  This function is called
5578   // from deep in the call stack, and calling getSCEV (on a sext instruction,
5579   // say) can end up caching a suboptimal value.
5580 
5581   // FIXME: without the explicit `this` receiver below, MSVC errors out with
5582   // C2352 and C2512 (otherwise it isn't needed).
5583 
5584   const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
5585   const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
5586   const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
5587   const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
5588 
5589   ConstantRange TrueRange =
5590       this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
5591   ConstantRange FalseRange =
5592       this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
5593 
5594   return TrueRange.unionWith(FalseRange);
5595 }
5596 
5597 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
5598   if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
5599   const BinaryOperator *BinOp = cast<BinaryOperator>(V);
5600 
5601   // Return early if there are no flags to propagate to the SCEV.
5602   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5603   if (BinOp->hasNoUnsignedWrap())
5604     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
5605   if (BinOp->hasNoSignedWrap())
5606     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
5607   if (Flags == SCEV::FlagAnyWrap)
5608     return SCEV::FlagAnyWrap;
5609 
5610   return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
5611 }
5612 
5613 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
5614   // Here we check that I is in the header of the innermost loop containing I,
5615   // since we only deal with instructions in the loop header. The actual loop we
5616   // need to check later will come from an add recurrence, but getting that
5617   // requires computing the SCEV of the operands, which can be expensive. This
5618   // check we can do cheaply to rule out some cases early.
5619   Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent());
5620   if (InnermostContainingLoop == nullptr ||
5621       InnermostContainingLoop->getHeader() != I->getParent())
5622     return false;
5623 
5624   // Only proceed if we can prove that I does not yield poison.
5625   if (!programUndefinedIfFullPoison(I))
5626     return false;
5627 
5628   // At this point we know that if I is executed, then it does not wrap
5629   // according to at least one of NSW or NUW. If I is not executed, then we do
5630   // not know if the calculation that I represents would wrap. Multiple
5631   // instructions can map to the same SCEV. If we apply NSW or NUW from I to
5632   // the SCEV, we must guarantee no wrapping for that SCEV also when it is
5633   // derived from other instructions that map to the same SCEV. We cannot make
5634   // that guarantee for cases where I is not executed. So we need to find the
5635   // loop that I is considered in relation to and prove that I is executed for
5636   // every iteration of that loop. That implies that the value that I
5637   // calculates does not wrap anywhere in the loop, so then we can apply the
5638   // flags to the SCEV.
5639   //
5640   // We check isLoopInvariant to disambiguate in case we are adding recurrences
5641   // from different loops, so that we know which loop to prove that I is
5642   // executed in.
5643   for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) {
5644     // I could be an extractvalue from a call to an overflow intrinsic.
5645     // TODO: We can do better here in some cases.
5646     if (!isSCEVable(I->getOperand(OpIndex)->getType()))
5647       return false;
5648     const SCEV *Op = getSCEV(I->getOperand(OpIndex));
5649     if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
5650       bool AllOtherOpsLoopInvariant = true;
5651       for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands();
5652            ++OtherOpIndex) {
5653         if (OtherOpIndex != OpIndex) {
5654           const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex));
5655           if (!isLoopInvariant(OtherOp, AddRec->getLoop())) {
5656             AllOtherOpsLoopInvariant = false;
5657             break;
5658           }
5659         }
5660       }
5661       if (AllOtherOpsLoopInvariant &&
5662           isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop()))
5663         return true;
5664     }
5665   }
5666   return false;
5667 }
5668 
5669 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
5670   // If we know that \c I can never be poison period, then that's enough.
5671   if (isSCEVExprNeverPoison(I))
5672     return true;
5673 
5674   // For an add recurrence specifically, we assume that infinite loops without
5675   // side effects are undefined behavior, and then reason as follows:
5676   //
5677   // If the add recurrence is poison in any iteration, it is poison on all
5678   // future iterations (since incrementing poison yields poison). If the result
5679   // of the add recurrence is fed into the loop latch condition and the loop
5680   // does not contain any throws or exiting blocks other than the latch, we now
5681   // have the ability to "choose" whether the backedge is taken or not (by
5682   // choosing a sufficiently evil value for the poison feeding into the branch)
5683   // for every iteration including and after the one in which \p I first became
5684   // poison.  There are two possibilities (let's call the iteration in which \p
5685   // I first became poison as K):
5686   //
5687   //  1. In the set of iterations including and after K, the loop body executes
5688   //     no side effects.  In this case executing the backege an infinte number
5689   //     of times will yield undefined behavior.
5690   //
5691   //  2. In the set of iterations including and after K, the loop body executes
5692   //     at least one side effect.  In this case, that specific instance of side
5693   //     effect is control dependent on poison, which also yields undefined
5694   //     behavior.
5695 
5696   auto *ExitingBB = L->getExitingBlock();
5697   auto *LatchBB = L->getLoopLatch();
5698   if (!ExitingBB || !LatchBB || ExitingBB != LatchBB)
5699     return false;
5700 
5701   SmallPtrSet<const Instruction *, 16> Pushed;
5702   SmallVector<const Instruction *, 8> PoisonStack;
5703 
5704   // We start by assuming \c I, the post-inc add recurrence, is poison.  Only
5705   // things that are known to be fully poison under that assumption go on the
5706   // PoisonStack.
5707   Pushed.insert(I);
5708   PoisonStack.push_back(I);
5709 
5710   bool LatchControlDependentOnPoison = false;
5711   while (!PoisonStack.empty() && !LatchControlDependentOnPoison) {
5712     const Instruction *Poison = PoisonStack.pop_back_val();
5713 
5714     for (auto *PoisonUser : Poison->users()) {
5715       if (propagatesFullPoison(cast<Instruction>(PoisonUser))) {
5716         if (Pushed.insert(cast<Instruction>(PoisonUser)).second)
5717           PoisonStack.push_back(cast<Instruction>(PoisonUser));
5718       } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) {
5719         assert(BI->isConditional() && "Only possibility!");
5720         if (BI->getParent() == LatchBB) {
5721           LatchControlDependentOnPoison = true;
5722           break;
5723         }
5724       }
5725     }
5726   }
5727 
5728   return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L);
5729 }
5730 
5731 ScalarEvolution::LoopProperties
5732 ScalarEvolution::getLoopProperties(const Loop *L) {
5733   using LoopProperties = ScalarEvolution::LoopProperties;
5734 
5735   auto Itr = LoopPropertiesCache.find(L);
5736   if (Itr == LoopPropertiesCache.end()) {
5737     auto HasSideEffects = [](Instruction *I) {
5738       if (auto *SI = dyn_cast<StoreInst>(I))
5739         return !SI->isSimple();
5740 
5741       return I->mayHaveSideEffects();
5742     };
5743 
5744     LoopProperties LP = {/* HasNoAbnormalExits */ true,
5745                          /*HasNoSideEffects*/ true};
5746 
5747     for (auto *BB : L->getBlocks())
5748       for (auto &I : *BB) {
5749         if (!isGuaranteedToTransferExecutionToSuccessor(&I))
5750           LP.HasNoAbnormalExits = false;
5751         if (HasSideEffects(&I))
5752           LP.HasNoSideEffects = false;
5753         if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
5754           break; // We're already as pessimistic as we can get.
5755       }
5756 
5757     auto InsertPair = LoopPropertiesCache.insert({L, LP});
5758     assert(InsertPair.second && "We just checked!");
5759     Itr = InsertPair.first;
5760   }
5761 
5762   return Itr->second;
5763 }
5764 
5765 const SCEV *ScalarEvolution::createSCEV(Value *V) {
5766   if (!isSCEVable(V->getType()))
5767     return getUnknown(V);
5768 
5769   if (Instruction *I = dyn_cast<Instruction>(V)) {
5770     // Don't attempt to analyze instructions in blocks that aren't
5771     // reachable. Such instructions don't matter, and they aren't required
5772     // to obey basic rules for definitions dominating uses which this
5773     // analysis depends on.
5774     if (!DT.isReachableFromEntry(I->getParent()))
5775       return getUnknown(V);
5776   } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
5777     return getConstant(CI);
5778   else if (isa<ConstantPointerNull>(V))
5779     return getZero(V->getType());
5780   else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
5781     return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee());
5782   else if (!isa<ConstantExpr>(V))
5783     return getUnknown(V);
5784 
5785   Operator *U = cast<Operator>(V);
5786   if (auto BO = MatchBinaryOp(U, DT)) {
5787     switch (BO->Opcode) {
5788     case Instruction::Add: {
5789       // The simple thing to do would be to just call getSCEV on both operands
5790       // and call getAddExpr with the result. However if we're looking at a
5791       // bunch of things all added together, this can be quite inefficient,
5792       // because it leads to N-1 getAddExpr calls for N ultimate operands.
5793       // Instead, gather up all the operands and make a single getAddExpr call.
5794       // LLVM IR canonical form means we need only traverse the left operands.
5795       SmallVector<const SCEV *, 4> AddOps;
5796       do {
5797         if (BO->Op) {
5798           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
5799             AddOps.push_back(OpSCEV);
5800             break;
5801           }
5802 
5803           // If a NUW or NSW flag can be applied to the SCEV for this
5804           // addition, then compute the SCEV for this addition by itself
5805           // with a separate call to getAddExpr. We need to do that
5806           // instead of pushing the operands of the addition onto AddOps,
5807           // since the flags are only known to apply to this particular
5808           // addition - they may not apply to other additions that can be
5809           // formed with operands from AddOps.
5810           const SCEV *RHS = getSCEV(BO->RHS);
5811           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
5812           if (Flags != SCEV::FlagAnyWrap) {
5813             const SCEV *LHS = getSCEV(BO->LHS);
5814             if (BO->Opcode == Instruction::Sub)
5815               AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
5816             else
5817               AddOps.push_back(getAddExpr(LHS, RHS, Flags));
5818             break;
5819           }
5820         }
5821 
5822         if (BO->Opcode == Instruction::Sub)
5823           AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
5824         else
5825           AddOps.push_back(getSCEV(BO->RHS));
5826 
5827         auto NewBO = MatchBinaryOp(BO->LHS, DT);
5828         if (!NewBO || (NewBO->Opcode != Instruction::Add &&
5829                        NewBO->Opcode != Instruction::Sub)) {
5830           AddOps.push_back(getSCEV(BO->LHS));
5831           break;
5832         }
5833         BO = NewBO;
5834       } while (true);
5835 
5836       return getAddExpr(AddOps);
5837     }
5838 
5839     case Instruction::Mul: {
5840       SmallVector<const SCEV *, 4> MulOps;
5841       do {
5842         if (BO->Op) {
5843           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
5844             MulOps.push_back(OpSCEV);
5845             break;
5846           }
5847 
5848           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
5849           if (Flags != SCEV::FlagAnyWrap) {
5850             MulOps.push_back(
5851                 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags));
5852             break;
5853           }
5854         }
5855 
5856         MulOps.push_back(getSCEV(BO->RHS));
5857         auto NewBO = MatchBinaryOp(BO->LHS, DT);
5858         if (!NewBO || NewBO->Opcode != Instruction::Mul) {
5859           MulOps.push_back(getSCEV(BO->LHS));
5860           break;
5861         }
5862         BO = NewBO;
5863       } while (true);
5864 
5865       return getMulExpr(MulOps);
5866     }
5867     case Instruction::UDiv:
5868       return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
5869     case Instruction::URem:
5870       return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
5871     case Instruction::Sub: {
5872       SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5873       if (BO->Op)
5874         Flags = getNoWrapFlagsFromUB(BO->Op);
5875       return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags);
5876     }
5877     case Instruction::And:
5878       // For an expression like x&255 that merely masks off the high bits,
5879       // use zext(trunc(x)) as the SCEV expression.
5880       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5881         if (CI->isZero())
5882           return getSCEV(BO->RHS);
5883         if (CI->isMinusOne())
5884           return getSCEV(BO->LHS);
5885         const APInt &A = CI->getValue();
5886 
5887         // Instcombine's ShrinkDemandedConstant may strip bits out of
5888         // constants, obscuring what would otherwise be a low-bits mask.
5889         // Use computeKnownBits to compute what ShrinkDemandedConstant
5890         // knew about to reconstruct a low-bits mask value.
5891         unsigned LZ = A.countLeadingZeros();
5892         unsigned TZ = A.countTrailingZeros();
5893         unsigned BitWidth = A.getBitWidth();
5894         KnownBits Known(BitWidth);
5895         computeKnownBits(BO->LHS, Known, getDataLayout(),
5896                          0, &AC, nullptr, &DT);
5897 
5898         APInt EffectiveMask =
5899             APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
5900         if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
5901           const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
5902           const SCEV *LHS = getSCEV(BO->LHS);
5903           const SCEV *ShiftedLHS = nullptr;
5904           if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
5905             if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
5906               // For an expression like (x * 8) & 8, simplify the multiply.
5907               unsigned MulZeros = OpC->getAPInt().countTrailingZeros();
5908               unsigned GCD = std::min(MulZeros, TZ);
5909               APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
5910               SmallVector<const SCEV*, 4> MulOps;
5911               MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD)));
5912               MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end());
5913               auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
5914               ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
5915             }
5916           }
5917           if (!ShiftedLHS)
5918             ShiftedLHS = getUDivExpr(LHS, MulCount);
5919           return getMulExpr(
5920               getZeroExtendExpr(
5921                   getTruncateExpr(ShiftedLHS,
5922                       IntegerType::get(getContext(), BitWidth - LZ - TZ)),
5923                   BO->LHS->getType()),
5924               MulCount);
5925         }
5926       }
5927       break;
5928 
5929     case Instruction::Or:
5930       // If the RHS of the Or is a constant, we may have something like:
5931       // X*4+1 which got turned into X*4|1.  Handle this as an Add so loop
5932       // optimizations will transparently handle this case.
5933       //
5934       // In order for this transformation to be safe, the LHS must be of the
5935       // form X*(2^n) and the Or constant must be less than 2^n.
5936       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5937         const SCEV *LHS = getSCEV(BO->LHS);
5938         const APInt &CIVal = CI->getValue();
5939         if (GetMinTrailingZeros(LHS) >=
5940             (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
5941           // Build a plain add SCEV.
5942           const SCEV *S = getAddExpr(LHS, getSCEV(CI));
5943           // If the LHS of the add was an addrec and it has no-wrap flags,
5944           // transfer the no-wrap flags, since an or won't introduce a wrap.
5945           if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
5946             const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
5947             const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags(
5948                 OldAR->getNoWrapFlags());
5949           }
5950           return S;
5951         }
5952       }
5953       break;
5954 
5955     case Instruction::Xor:
5956       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5957         // If the RHS of xor is -1, then this is a not operation.
5958         if (CI->isMinusOne())
5959           return getNotSCEV(getSCEV(BO->LHS));
5960 
5961         // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
5962         // This is a variant of the check for xor with -1, and it handles
5963         // the case where instcombine has trimmed non-demanded bits out
5964         // of an xor with -1.
5965         if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
5966           if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
5967             if (LBO->getOpcode() == Instruction::And &&
5968                 LCI->getValue() == CI->getValue())
5969               if (const SCEVZeroExtendExpr *Z =
5970                       dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
5971                 Type *UTy = BO->LHS->getType();
5972                 const SCEV *Z0 = Z->getOperand();
5973                 Type *Z0Ty = Z0->getType();
5974                 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
5975 
5976                 // If C is a low-bits mask, the zero extend is serving to
5977                 // mask off the high bits. Complement the operand and
5978                 // re-apply the zext.
5979                 if (CI->getValue().isMask(Z0TySize))
5980                   return getZeroExtendExpr(getNotSCEV(Z0), UTy);
5981 
5982                 // If C is a single bit, it may be in the sign-bit position
5983                 // before the zero-extend. In this case, represent the xor
5984                 // using an add, which is equivalent, and re-apply the zext.
5985                 APInt Trunc = CI->getValue().trunc(Z0TySize);
5986                 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
5987                     Trunc.isSignMask())
5988                   return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
5989                                            UTy);
5990               }
5991       }
5992       break;
5993 
5994   case Instruction::Shl:
5995     // Turn shift left of a constant amount into a multiply.
5996     if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
5997       uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
5998 
5999       // If the shift count is not less than the bitwidth, the result of
6000       // the shift is undefined. Don't try to analyze it, because the
6001       // resolution chosen here may differ from the resolution chosen in
6002       // other parts of the compiler.
6003       if (SA->getValue().uge(BitWidth))
6004         break;
6005 
6006       // It is currently not resolved how to interpret NSW for left
6007       // shift by BitWidth - 1, so we avoid applying flags in that
6008       // case. Remove this check (or this comment) once the situation
6009       // is resolved. See
6010       // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html
6011       // and http://reviews.llvm.org/D8890 .
6012       auto Flags = SCEV::FlagAnyWrap;
6013       if (BO->Op && SA->getValue().ult(BitWidth - 1))
6014         Flags = getNoWrapFlagsFromUB(BO->Op);
6015 
6016       Constant *X = ConstantInt::get(getContext(),
6017         APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
6018       return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags);
6019     }
6020     break;
6021 
6022     case Instruction::AShr: {
6023       // AShr X, C, where C is a constant.
6024       ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
6025       if (!CI)
6026         break;
6027 
6028       Type *OuterTy = BO->LHS->getType();
6029       uint64_t BitWidth = getTypeSizeInBits(OuterTy);
6030       // If the shift count is not less than the bitwidth, the result of
6031       // the shift is undefined. Don't try to analyze it, because the
6032       // resolution chosen here may differ from the resolution chosen in
6033       // other parts of the compiler.
6034       if (CI->getValue().uge(BitWidth))
6035         break;
6036 
6037       if (CI->isZero())
6038         return getSCEV(BO->LHS); // shift by zero --> noop
6039 
6040       uint64_t AShrAmt = CI->getZExtValue();
6041       Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
6042 
6043       Operator *L = dyn_cast<Operator>(BO->LHS);
6044       if (L && L->getOpcode() == Instruction::Shl) {
6045         // X = Shl A, n
6046         // Y = AShr X, m
6047         // Both n and m are constant.
6048 
6049         const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
6050         if (L->getOperand(1) == BO->RHS)
6051           // For a two-shift sext-inreg, i.e. n = m,
6052           // use sext(trunc(x)) as the SCEV expression.
6053           return getSignExtendExpr(
6054               getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy);
6055 
6056         ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
6057         if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) {
6058           uint64_t ShlAmt = ShlAmtCI->getZExtValue();
6059           if (ShlAmt > AShrAmt) {
6060             // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
6061             // expression. We already checked that ShlAmt < BitWidth, so
6062             // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
6063             // ShlAmt - AShrAmt < Amt.
6064             APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
6065                                             ShlAmt - AShrAmt);
6066             return getSignExtendExpr(
6067                 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy),
6068                 getConstant(Mul)), OuterTy);
6069           }
6070         }
6071       }
6072       break;
6073     }
6074     }
6075   }
6076 
6077   switch (U->getOpcode()) {
6078   case Instruction::Trunc:
6079     return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
6080 
6081   case Instruction::ZExt:
6082     return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
6083 
6084   case Instruction::SExt:
6085     if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) {
6086       // The NSW flag of a subtract does not always survive the conversion to
6087       // A + (-1)*B.  By pushing sign extension onto its operands we are much
6088       // more likely to preserve NSW and allow later AddRec optimisations.
6089       //
6090       // NOTE: This is effectively duplicating this logic from getSignExtend:
6091       //   sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
6092       // but by that point the NSW information has potentially been lost.
6093       if (BO->Opcode == Instruction::Sub && BO->IsNSW) {
6094         Type *Ty = U->getType();
6095         auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty);
6096         auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty);
6097         return getMinusSCEV(V1, V2, SCEV::FlagNSW);
6098       }
6099     }
6100     return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
6101 
6102   case Instruction::BitCast:
6103     // BitCasts are no-op casts so we just eliminate the cast.
6104     if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
6105       return getSCEV(U->getOperand(0));
6106     break;
6107 
6108   // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
6109   // lead to pointer expressions which cannot safely be expanded to GEPs,
6110   // because ScalarEvolution doesn't respect the GEP aliasing rules when
6111   // simplifying integer expressions.
6112 
6113   case Instruction::GetElementPtr:
6114     return createNodeForGEP(cast<GEPOperator>(U));
6115 
6116   case Instruction::PHI:
6117     return createNodeForPHI(cast<PHINode>(U));
6118 
6119   case Instruction::Select:
6120     // U can also be a select constant expr, which let fall through.  Since
6121     // createNodeForSelect only works for a condition that is an `ICmpInst`, and
6122     // constant expressions cannot have instructions as operands, we'd have
6123     // returned getUnknown for a select constant expressions anyway.
6124     if (isa<Instruction>(U))
6125       return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0),
6126                                       U->getOperand(1), U->getOperand(2));
6127     break;
6128 
6129   case Instruction::Call:
6130   case Instruction::Invoke:
6131     if (Value *RV = CallSite(U).getReturnedArgOperand())
6132       return getSCEV(RV);
6133     break;
6134   }
6135 
6136   return getUnknown(V);
6137 }
6138 
6139 //===----------------------------------------------------------------------===//
6140 //                   Iteration Count Computation Code
6141 //
6142 
6143 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
6144   if (!ExitCount)
6145     return 0;
6146 
6147   ConstantInt *ExitConst = ExitCount->getValue();
6148 
6149   // Guard against huge trip counts.
6150   if (ExitConst->getValue().getActiveBits() > 32)
6151     return 0;
6152 
6153   // In case of integer overflow, this returns 0, which is correct.
6154   return ((unsigned)ExitConst->getZExtValue()) + 1;
6155 }
6156 
6157 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) {
6158   if (BasicBlock *ExitingBB = L->getExitingBlock())
6159     return getSmallConstantTripCount(L, ExitingBB);
6160 
6161   // No trip count information for multiple exits.
6162   return 0;
6163 }
6164 
6165 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L,
6166                                                     BasicBlock *ExitingBlock) {
6167   assert(ExitingBlock && "Must pass a non-null exiting block!");
6168   assert(L->isLoopExiting(ExitingBlock) &&
6169          "Exiting block must actually branch out of the loop!");
6170   const SCEVConstant *ExitCount =
6171       dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
6172   return getConstantTripCount(ExitCount);
6173 }
6174 
6175 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) {
6176   const auto *MaxExitCount =
6177       dyn_cast<SCEVConstant>(getMaxBackedgeTakenCount(L));
6178   return getConstantTripCount(MaxExitCount);
6179 }
6180 
6181 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) {
6182   if (BasicBlock *ExitingBB = L->getExitingBlock())
6183     return getSmallConstantTripMultiple(L, ExitingBB);
6184 
6185   // No trip multiple information for multiple exits.
6186   return 0;
6187 }
6188 
6189 /// Returns the largest constant divisor of the trip count of this loop as a
6190 /// normal unsigned value, if possible. This means that the actual trip count is
6191 /// always a multiple of the returned value (don't forget the trip count could
6192 /// very well be zero as well!).
6193 ///
6194 /// Returns 1 if the trip count is unknown or not guaranteed to be the
6195 /// multiple of a constant (which is also the case if the trip count is simply
6196 /// constant, use getSmallConstantTripCount for that case), Will also return 1
6197 /// if the trip count is very large (>= 2^32).
6198 ///
6199 /// As explained in the comments for getSmallConstantTripCount, this assumes
6200 /// that control exits the loop via ExitingBlock.
6201 unsigned
6202 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
6203                                               BasicBlock *ExitingBlock) {
6204   assert(ExitingBlock && "Must pass a non-null exiting block!");
6205   assert(L->isLoopExiting(ExitingBlock) &&
6206          "Exiting block must actually branch out of the loop!");
6207   const SCEV *ExitCount = getExitCount(L, ExitingBlock);
6208   if (ExitCount == getCouldNotCompute())
6209     return 1;
6210 
6211   // Get the trip count from the BE count by adding 1.
6212   const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType()));
6213 
6214   const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr);
6215   if (!TC)
6216     // Attempt to factor more general cases. Returns the greatest power of
6217     // two divisor. If overflow happens, the trip count expression is still
6218     // divisible by the greatest power of 2 divisor returned.
6219     return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr));
6220 
6221   ConstantInt *Result = TC->getValue();
6222 
6223   // Guard against huge trip counts (this requires checking
6224   // for zero to handle the case where the trip count == -1 and the
6225   // addition wraps).
6226   if (!Result || Result->getValue().getActiveBits() > 32 ||
6227       Result->getValue().getActiveBits() == 0)
6228     return 1;
6229 
6230   return (unsigned)Result->getZExtValue();
6231 }
6232 
6233 /// Get the expression for the number of loop iterations for which this loop is
6234 /// guaranteed not to exit via ExitingBlock. Otherwise return
6235 /// SCEVCouldNotCompute.
6236 const SCEV *ScalarEvolution::getExitCount(const Loop *L,
6237                                           BasicBlock *ExitingBlock) {
6238   return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
6239 }
6240 
6241 const SCEV *
6242 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
6243                                                  SCEVUnionPredicate &Preds) {
6244   return getPredicatedBackedgeTakenInfo(L).getExact(this, &Preds);
6245 }
6246 
6247 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
6248   return getBackedgeTakenInfo(L).getExact(this);
6249 }
6250 
6251 /// Similar to getBackedgeTakenCount, except return the least SCEV value that is
6252 /// known never to be less than the actual backedge taken count.
6253 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
6254   return getBackedgeTakenInfo(L).getMax(this);
6255 }
6256 
6257 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) {
6258   return getBackedgeTakenInfo(L).isMaxOrZero(this);
6259 }
6260 
6261 /// Push PHI nodes in the header of the given loop onto the given Worklist.
6262 static void
6263 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
6264   BasicBlock *Header = L->getHeader();
6265 
6266   // Push all Loop-header PHIs onto the Worklist stack.
6267   for (BasicBlock::iterator I = Header->begin();
6268        PHINode *PN = dyn_cast<PHINode>(I); ++I)
6269     Worklist.push_back(PN);
6270 }
6271 
6272 const ScalarEvolution::BackedgeTakenInfo &
6273 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
6274   auto &BTI = getBackedgeTakenInfo(L);
6275   if (BTI.hasFullInfo())
6276     return BTI;
6277 
6278   auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
6279 
6280   if (!Pair.second)
6281     return Pair.first->second;
6282 
6283   BackedgeTakenInfo Result =
6284       computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
6285 
6286   return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
6287 }
6288 
6289 const ScalarEvolution::BackedgeTakenInfo &
6290 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
6291   // Initially insert an invalid entry for this loop. If the insertion
6292   // succeeds, proceed to actually compute a backedge-taken count and
6293   // update the value. The temporary CouldNotCompute value tells SCEV
6294   // code elsewhere that it shouldn't attempt to request a new
6295   // backedge-taken count, which could result in infinite recursion.
6296   std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
6297       BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
6298   if (!Pair.second)
6299     return Pair.first->second;
6300 
6301   // computeBackedgeTakenCount may allocate memory for its result. Inserting it
6302   // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
6303   // must be cleared in this scope.
6304   BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
6305 
6306   if (Result.getExact(this) != getCouldNotCompute()) {
6307     assert(isLoopInvariant(Result.getExact(this), L) &&
6308            isLoopInvariant(Result.getMax(this), L) &&
6309            "Computed backedge-taken count isn't loop invariant for loop!");
6310     ++NumTripCountsComputed;
6311   }
6312   else if (Result.getMax(this) == getCouldNotCompute() &&
6313            isa<PHINode>(L->getHeader()->begin())) {
6314     // Only count loops that have phi nodes as not being computable.
6315     ++NumTripCountsNotComputed;
6316   }
6317 
6318   // Now that we know more about the trip count for this loop, forget any
6319   // existing SCEV values for PHI nodes in this loop since they are only
6320   // conservative estimates made without the benefit of trip count
6321   // information. This is similar to the code in forgetLoop, except that
6322   // it handles SCEVUnknown PHI nodes specially.
6323   if (Result.hasAnyInfo()) {
6324     SmallVector<Instruction *, 16> Worklist;
6325     PushLoopPHIs(L, Worklist);
6326 
6327     SmallPtrSet<Instruction *, 8> Visited;
6328     while (!Worklist.empty()) {
6329       Instruction *I = Worklist.pop_back_val();
6330       if (!Visited.insert(I).second)
6331         continue;
6332 
6333       ValueExprMapType::iterator It =
6334         ValueExprMap.find_as(static_cast<Value *>(I));
6335       if (It != ValueExprMap.end()) {
6336         const SCEV *Old = It->second;
6337 
6338         // SCEVUnknown for a PHI either means that it has an unrecognized
6339         // structure, or it's a PHI that's in the progress of being computed
6340         // by createNodeForPHI.  In the former case, additional loop trip
6341         // count information isn't going to change anything. In the later
6342         // case, createNodeForPHI will perform the necessary updates on its
6343         // own when it gets to that point.
6344         if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
6345           eraseValueFromMap(It->first);
6346           forgetMemoizedResults(Old, false);
6347         }
6348         if (PHINode *PN = dyn_cast<PHINode>(I))
6349           ConstantEvolutionLoopExitValue.erase(PN);
6350       }
6351 
6352       PushDefUseChildren(I, Worklist);
6353     }
6354   }
6355 
6356   // Re-lookup the insert position, since the call to
6357   // computeBackedgeTakenCount above could result in a
6358   // recusive call to getBackedgeTakenInfo (on a different
6359   // loop), which would invalidate the iterator computed
6360   // earlier.
6361   return BackedgeTakenCounts.find(L)->second = std::move(Result);
6362 }
6363 
6364 void ScalarEvolution::forgetLoop(const Loop *L) {
6365   // Drop any stored trip count value.
6366   auto RemoveLoopFromBackedgeMap =
6367       [](DenseMap<const Loop *, BackedgeTakenInfo> &Map, const Loop *L) {
6368         auto BTCPos = Map.find(L);
6369         if (BTCPos != Map.end()) {
6370           BTCPos->second.clear();
6371           Map.erase(BTCPos);
6372         }
6373       };
6374 
6375   SmallVector<const Loop *, 16> LoopWorklist(1, L);
6376   SmallVector<Instruction *, 32> Worklist;
6377   SmallPtrSet<Instruction *, 16> Visited;
6378 
6379   // Iterate over all the loops and sub-loops to drop SCEV information.
6380   while (!LoopWorklist.empty()) {
6381     auto *CurrL = LoopWorklist.pop_back_val();
6382 
6383     RemoveLoopFromBackedgeMap(BackedgeTakenCounts, CurrL);
6384     RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts, CurrL);
6385 
6386     // Drop information about predicated SCEV rewrites for this loop.
6387     for (auto I = PredicatedSCEVRewrites.begin();
6388          I != PredicatedSCEVRewrites.end();) {
6389       std::pair<const SCEV *, const Loop *> Entry = I->first;
6390       if (Entry.second == CurrL)
6391         PredicatedSCEVRewrites.erase(I++);
6392       else
6393         ++I;
6394     }
6395 
6396     // Drop information about expressions based on loop-header PHIs.
6397     PushLoopPHIs(CurrL, Worklist);
6398 
6399     while (!Worklist.empty()) {
6400       Instruction *I = Worklist.pop_back_val();
6401       if (!Visited.insert(I).second)
6402         continue;
6403 
6404       ValueExprMapType::iterator It =
6405           ValueExprMap.find_as(static_cast<Value *>(I));
6406       if (It != ValueExprMap.end()) {
6407         eraseValueFromMap(It->first);
6408         forgetMemoizedResults(It->second);
6409         if (PHINode *PN = dyn_cast<PHINode>(I))
6410           ConstantEvolutionLoopExitValue.erase(PN);
6411       }
6412 
6413       PushDefUseChildren(I, Worklist);
6414     }
6415 
6416     for (auto I = ExitLimits.begin(); I != ExitLimits.end(); ++I) {
6417       auto &Query = I->first;
6418       if (Query.L == CurrL)
6419         ExitLimits.erase(I);
6420     }
6421 
6422     LoopPropertiesCache.erase(CurrL);
6423     // Forget all contained loops too, to avoid dangling entries in the
6424     // ValuesAtScopes map.
6425     LoopWorklist.append(CurrL->begin(), CurrL->end());
6426   }
6427 }
6428 
6429 void ScalarEvolution::forgetValue(Value *V) {
6430   Instruction *I = dyn_cast<Instruction>(V);
6431   if (!I) return;
6432 
6433   // Drop information about expressions based on loop-header PHIs.
6434   SmallVector<Instruction *, 16> Worklist;
6435   Worklist.push_back(I);
6436 
6437   SmallPtrSet<Instruction *, 8> Visited;
6438   while (!Worklist.empty()) {
6439     I = Worklist.pop_back_val();
6440     if (!Visited.insert(I).second)
6441       continue;
6442 
6443     ValueExprMapType::iterator It =
6444       ValueExprMap.find_as(static_cast<Value *>(I));
6445     if (It != ValueExprMap.end()) {
6446       eraseValueFromMap(It->first);
6447       forgetMemoizedResults(It->second);
6448       if (PHINode *PN = dyn_cast<PHINode>(I))
6449         ConstantEvolutionLoopExitValue.erase(PN);
6450     }
6451 
6452     PushDefUseChildren(I, Worklist);
6453   }
6454 }
6455 
6456 /// Get the exact loop backedge taken count considering all loop exits. A
6457 /// computable result can only be returned for loops with a single exit.
6458 /// Returning the minimum taken count among all exits is incorrect because one
6459 /// of the loop's exit limit's may have been skipped. howFarToZero assumes that
6460 /// the limit of each loop test is never skipped. This is a valid assumption as
6461 /// long as the loop exits via that test. For precise results, it is the
6462 /// caller's responsibility to specify the relevant loop exit using
6463 /// getExact(ExitingBlock, SE).
6464 const SCEV *
6465 ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE,
6466                                              SCEVUnionPredicate *Preds) const {
6467   // If any exits were not computable, the loop is not computable.
6468   if (!isComplete() || ExitNotTaken.empty())
6469     return SE->getCouldNotCompute();
6470 
6471   const SCEV *BECount = nullptr;
6472   for (auto &ENT : ExitNotTaken) {
6473     assert(ENT.ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV");
6474 
6475     if (!BECount)
6476       BECount = ENT.ExactNotTaken;
6477     else if (BECount != ENT.ExactNotTaken)
6478       return SE->getCouldNotCompute();
6479     if (Preds && !ENT.hasAlwaysTruePredicate())
6480       Preds->add(ENT.Predicate.get());
6481 
6482     assert((Preds || ENT.hasAlwaysTruePredicate()) &&
6483            "Predicate should be always true!");
6484   }
6485 
6486   assert(BECount && "Invalid not taken count for loop exit");
6487   return BECount;
6488 }
6489 
6490 /// Get the exact not taken count for this loop exit.
6491 const SCEV *
6492 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock,
6493                                              ScalarEvolution *SE) const {
6494   for (auto &ENT : ExitNotTaken)
6495     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
6496       return ENT.ExactNotTaken;
6497 
6498   return SE->getCouldNotCompute();
6499 }
6500 
6501 /// getMax - Get the max backedge taken count for the loop.
6502 const SCEV *
6503 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const {
6504   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
6505     return !ENT.hasAlwaysTruePredicate();
6506   };
6507 
6508   if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax())
6509     return SE->getCouldNotCompute();
6510 
6511   assert((isa<SCEVCouldNotCompute>(getMax()) || isa<SCEVConstant>(getMax())) &&
6512          "No point in having a non-constant max backedge taken count!");
6513   return getMax();
6514 }
6515 
6516 bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const {
6517   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
6518     return !ENT.hasAlwaysTruePredicate();
6519   };
6520   return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
6521 }
6522 
6523 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S,
6524                                                     ScalarEvolution *SE) const {
6525   if (getMax() && getMax() != SE->getCouldNotCompute() &&
6526       SE->hasOperand(getMax(), S))
6527     return true;
6528 
6529   for (auto &ENT : ExitNotTaken)
6530     if (ENT.ExactNotTaken != SE->getCouldNotCompute() &&
6531         SE->hasOperand(ENT.ExactNotTaken, S))
6532       return true;
6533 
6534   return false;
6535 }
6536 
6537 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E)
6538     : ExactNotTaken(E), MaxNotTaken(E) {
6539   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6540           isa<SCEVConstant>(MaxNotTaken)) &&
6541          "No point in having a non-constant max backedge taken count!");
6542 }
6543 
6544 ScalarEvolution::ExitLimit::ExitLimit(
6545     const SCEV *E, const SCEV *M, bool MaxOrZero,
6546     ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList)
6547     : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) {
6548   assert((isa<SCEVCouldNotCompute>(ExactNotTaken) ||
6549           !isa<SCEVCouldNotCompute>(MaxNotTaken)) &&
6550          "Exact is not allowed to be less precise than Max");
6551   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6552           isa<SCEVConstant>(MaxNotTaken)) &&
6553          "No point in having a non-constant max backedge taken count!");
6554   for (auto *PredSet : PredSetList)
6555     for (auto *P : *PredSet)
6556       addPredicate(P);
6557 }
6558 
6559 ScalarEvolution::ExitLimit::ExitLimit(
6560     const SCEV *E, const SCEV *M, bool MaxOrZero,
6561     const SmallPtrSetImpl<const SCEVPredicate *> &PredSet)
6562     : ExitLimit(E, M, MaxOrZero, {&PredSet}) {
6563   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6564           isa<SCEVConstant>(MaxNotTaken)) &&
6565          "No point in having a non-constant max backedge taken count!");
6566 }
6567 
6568 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M,
6569                                       bool MaxOrZero)
6570     : ExitLimit(E, M, MaxOrZero, None) {
6571   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6572           isa<SCEVConstant>(MaxNotTaken)) &&
6573          "No point in having a non-constant max backedge taken count!");
6574 }
6575 
6576 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
6577 /// computable exit into a persistent ExitNotTakenInfo array.
6578 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
6579     SmallVectorImpl<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo>
6580         &&ExitCounts,
6581     bool Complete, const SCEV *MaxCount, bool MaxOrZero)
6582     : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) {
6583   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
6584 
6585   ExitNotTaken.reserve(ExitCounts.size());
6586   std::transform(
6587       ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken),
6588       [&](const EdgeExitInfo &EEI) {
6589         BasicBlock *ExitBB = EEI.first;
6590         const ExitLimit &EL = EEI.second;
6591         if (EL.Predicates.empty())
6592           return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr);
6593 
6594         std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate);
6595         for (auto *Pred : EL.Predicates)
6596           Predicate->add(Pred);
6597 
6598         return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, std::move(Predicate));
6599       });
6600   assert((isa<SCEVCouldNotCompute>(MaxCount) || isa<SCEVConstant>(MaxCount)) &&
6601          "No point in having a non-constant max backedge taken count!");
6602 }
6603 
6604 /// Invalidate this result and free the ExitNotTakenInfo array.
6605 void ScalarEvolution::BackedgeTakenInfo::clear() {
6606   ExitNotTaken.clear();
6607 }
6608 
6609 /// Compute the number of times the backedge of the specified loop will execute.
6610 ScalarEvolution::BackedgeTakenInfo
6611 ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
6612                                            bool AllowPredicates) {
6613   SmallVector<BasicBlock *, 8> ExitingBlocks;
6614   L->getExitingBlocks(ExitingBlocks);
6615 
6616   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
6617 
6618   SmallVector<EdgeExitInfo, 4> ExitCounts;
6619   bool CouldComputeBECount = true;
6620   BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
6621   const SCEV *MustExitMaxBECount = nullptr;
6622   const SCEV *MayExitMaxBECount = nullptr;
6623   bool MustExitMaxOrZero = false;
6624 
6625   // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
6626   // and compute maxBECount.
6627   // Do a union of all the predicates here.
6628   for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
6629     BasicBlock *ExitBB = ExitingBlocks[i];
6630     ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
6631 
6632     assert((AllowPredicates || EL.Predicates.empty()) &&
6633            "Predicated exit limit when predicates are not allowed!");
6634 
6635     // 1. For each exit that can be computed, add an entry to ExitCounts.
6636     // CouldComputeBECount is true only if all exits can be computed.
6637     if (EL.ExactNotTaken == getCouldNotCompute())
6638       // We couldn't compute an exact value for this exit, so
6639       // we won't be able to compute an exact value for the loop.
6640       CouldComputeBECount = false;
6641     else
6642       ExitCounts.emplace_back(ExitBB, EL);
6643 
6644     // 2. Derive the loop's MaxBECount from each exit's max number of
6645     // non-exiting iterations. Partition the loop exits into two kinds:
6646     // LoopMustExits and LoopMayExits.
6647     //
6648     // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
6649     // is a LoopMayExit.  If any computable LoopMustExit is found, then
6650     // MaxBECount is the minimum EL.MaxNotTaken of computable
6651     // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
6652     // EL.MaxNotTaken, where CouldNotCompute is considered greater than any
6653     // computable EL.MaxNotTaken.
6654     if (EL.MaxNotTaken != getCouldNotCompute() && Latch &&
6655         DT.dominates(ExitBB, Latch)) {
6656       if (!MustExitMaxBECount) {
6657         MustExitMaxBECount = EL.MaxNotTaken;
6658         MustExitMaxOrZero = EL.MaxOrZero;
6659       } else {
6660         MustExitMaxBECount =
6661             getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken);
6662       }
6663     } else if (MayExitMaxBECount != getCouldNotCompute()) {
6664       if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute())
6665         MayExitMaxBECount = EL.MaxNotTaken;
6666       else {
6667         MayExitMaxBECount =
6668             getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken);
6669       }
6670     }
6671   }
6672   const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
6673     (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
6674   // The loop backedge will be taken the maximum or zero times if there's
6675   // a single exit that must be taken the maximum or zero times.
6676   bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
6677   return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
6678                            MaxBECount, MaxOrZero);
6679 }
6680 
6681 ScalarEvolution::ExitLimit
6682 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
6683                                   bool AllowPredicates) {
6684   ExitLimitQuery Query(L, ExitingBlock, AllowPredicates);
6685   auto MaybeEL = ExitLimits.find(Query);
6686   if (MaybeEL != ExitLimits.end())
6687     return MaybeEL->second;
6688   ExitLimit EL = computeExitLimitImpl(L, ExitingBlock, AllowPredicates);
6689   ExitLimits.insert({Query, EL});
6690   return EL;
6691 }
6692 
6693 ScalarEvolution::ExitLimit
6694 ScalarEvolution::computeExitLimitImpl(const Loop *L, BasicBlock *ExitingBlock,
6695                                       bool AllowPredicates) {
6696   // Okay, we've chosen an exiting block.  See what condition causes us to exit
6697   // at this block and remember the exit block and whether all other targets
6698   // lead to the loop header.
6699   bool MustExecuteLoopHeader = true;
6700   BasicBlock *Exit = nullptr;
6701   for (auto *SBB : successors(ExitingBlock))
6702     if (!L->contains(SBB)) {
6703       if (Exit) // Multiple exit successors.
6704         return getCouldNotCompute();
6705       Exit = SBB;
6706     } else if (SBB != L->getHeader()) {
6707       MustExecuteLoopHeader = false;
6708     }
6709 
6710   // At this point, we know we have a conditional branch that determines whether
6711   // the loop is exited.  However, we don't know if the branch is executed each
6712   // time through the loop.  If not, then the execution count of the branch will
6713   // not be equal to the trip count of the loop.
6714   //
6715   // Currently we check for this by checking to see if the Exit branch goes to
6716   // the loop header.  If so, we know it will always execute the same number of
6717   // times as the loop.  We also handle the case where the exit block *is* the
6718   // loop header.  This is common for un-rotated loops.
6719   //
6720   // If both of those tests fail, walk up the unique predecessor chain to the
6721   // header, stopping if there is an edge that doesn't exit the loop. If the
6722   // header is reached, the execution count of the branch will be equal to the
6723   // trip count of the loop.
6724   //
6725   //  More extensive analysis could be done to handle more cases here.
6726   //
6727   if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) {
6728     // The simple checks failed, try climbing the unique predecessor chain
6729     // up to the header.
6730     bool Ok = false;
6731     for (BasicBlock *BB = ExitingBlock; BB; ) {
6732       BasicBlock *Pred = BB->getUniquePredecessor();
6733       if (!Pred)
6734         return getCouldNotCompute();
6735       TerminatorInst *PredTerm = Pred->getTerminator();
6736       for (const BasicBlock *PredSucc : PredTerm->successors()) {
6737         if (PredSucc == BB)
6738           continue;
6739         // If the predecessor has a successor that isn't BB and isn't
6740         // outside the loop, assume the worst.
6741         if (L->contains(PredSucc))
6742           return getCouldNotCompute();
6743       }
6744       if (Pred == L->getHeader()) {
6745         Ok = true;
6746         break;
6747       }
6748       BB = Pred;
6749     }
6750     if (!Ok)
6751       return getCouldNotCompute();
6752   }
6753 
6754   bool IsOnlyExit = (L->getExitingBlock() != nullptr);
6755   TerminatorInst *Term = ExitingBlock->getTerminator();
6756   if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
6757     assert(BI->isConditional() && "If unconditional, it can't be in loop!");
6758     // Proceed to the next level to examine the exit condition expression.
6759     return computeExitLimitFromCond(
6760         L, BI->getCondition(), BI->getSuccessor(0), BI->getSuccessor(1),
6761         /*ControlsExit=*/IsOnlyExit, AllowPredicates);
6762   }
6763 
6764   if (SwitchInst *SI = dyn_cast<SwitchInst>(Term))
6765     return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
6766                                                 /*ControlsExit=*/IsOnlyExit);
6767 
6768   return getCouldNotCompute();
6769 }
6770 
6771 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond(
6772     const Loop *L, Value *ExitCond, BasicBlock *TBB, BasicBlock *FBB,
6773     bool ControlsExit, bool AllowPredicates) {
6774   ScalarEvolution::ExitLimitCacheTy Cache(L, TBB, FBB, AllowPredicates);
6775   return computeExitLimitFromCondCached(Cache, L, ExitCond, TBB, FBB,
6776                                         ControlsExit, AllowPredicates);
6777 }
6778 
6779 Optional<ScalarEvolution::ExitLimit>
6780 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
6781                                       BasicBlock *TBB, BasicBlock *FBB,
6782                                       bool ControlsExit, bool AllowPredicates) {
6783   (void)this->L;
6784   (void)this->TBB;
6785   (void)this->FBB;
6786   (void)this->AllowPredicates;
6787 
6788   assert(this->L == L && this->TBB == TBB && this->FBB == FBB &&
6789          this->AllowPredicates == AllowPredicates &&
6790          "Variance in assumed invariant key components!");
6791   auto Itr = TripCountMap.find({ExitCond, ControlsExit});
6792   if (Itr == TripCountMap.end())
6793     return None;
6794   return Itr->second;
6795 }
6796 
6797 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
6798                                              BasicBlock *TBB, BasicBlock *FBB,
6799                                              bool ControlsExit,
6800                                              bool AllowPredicates,
6801                                              const ExitLimit &EL) {
6802   assert(this->L == L && this->TBB == TBB && this->FBB == FBB &&
6803          this->AllowPredicates == AllowPredicates &&
6804          "Variance in assumed invariant key components!");
6805 
6806   auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL});
6807   assert(InsertResult.second && "Expected successful insertion!");
6808   (void)InsertResult;
6809 }
6810 
6811 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
6812     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, BasicBlock *TBB,
6813     BasicBlock *FBB, bool ControlsExit, bool AllowPredicates) {
6814 
6815   if (auto MaybeEL =
6816           Cache.find(L, ExitCond, TBB, FBB, ControlsExit, AllowPredicates))
6817     return *MaybeEL;
6818 
6819   ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, TBB, FBB,
6820                                               ControlsExit, AllowPredicates);
6821   Cache.insert(L, ExitCond, TBB, FBB, ControlsExit, AllowPredicates, EL);
6822   return EL;
6823 }
6824 
6825 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
6826     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, BasicBlock *TBB,
6827     BasicBlock *FBB, bool ControlsExit, bool AllowPredicates) {
6828   // Check if the controlling expression for this loop is an And or Or.
6829   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
6830     if (BO->getOpcode() == Instruction::And) {
6831       // Recurse on the operands of the and.
6832       bool EitherMayExit = L->contains(TBB);
6833       ExitLimit EL0 = computeExitLimitFromCondCached(
6834           Cache, L, BO->getOperand(0), TBB, FBB, ControlsExit && !EitherMayExit,
6835           AllowPredicates);
6836       ExitLimit EL1 = computeExitLimitFromCondCached(
6837           Cache, L, BO->getOperand(1), TBB, FBB, ControlsExit && !EitherMayExit,
6838           AllowPredicates);
6839       const SCEV *BECount = getCouldNotCompute();
6840       const SCEV *MaxBECount = getCouldNotCompute();
6841       if (EitherMayExit) {
6842         // Both conditions must be true for the loop to continue executing.
6843         // Choose the less conservative count.
6844         if (EL0.ExactNotTaken == getCouldNotCompute() ||
6845             EL1.ExactNotTaken == getCouldNotCompute())
6846           BECount = getCouldNotCompute();
6847         else
6848           BECount =
6849               getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
6850         if (EL0.MaxNotTaken == getCouldNotCompute())
6851           MaxBECount = EL1.MaxNotTaken;
6852         else if (EL1.MaxNotTaken == getCouldNotCompute())
6853           MaxBECount = EL0.MaxNotTaken;
6854         else
6855           MaxBECount =
6856               getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
6857       } else {
6858         // Both conditions must be true at the same time for the loop to exit.
6859         // For now, be conservative.
6860         assert(L->contains(FBB) && "Loop block has no successor in loop!");
6861         if (EL0.MaxNotTaken == EL1.MaxNotTaken)
6862           MaxBECount = EL0.MaxNotTaken;
6863         if (EL0.ExactNotTaken == EL1.ExactNotTaken)
6864           BECount = EL0.ExactNotTaken;
6865       }
6866 
6867       // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
6868       // to be more aggressive when computing BECount than when computing
6869       // MaxBECount.  In these cases it is possible for EL0.ExactNotTaken and
6870       // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
6871       // to not.
6872       if (isa<SCEVCouldNotCompute>(MaxBECount) &&
6873           !isa<SCEVCouldNotCompute>(BECount))
6874         MaxBECount = getConstant(getUnsignedRangeMax(BECount));
6875 
6876       return ExitLimit(BECount, MaxBECount, false,
6877                        {&EL0.Predicates, &EL1.Predicates});
6878     }
6879     if (BO->getOpcode() == Instruction::Or) {
6880       // Recurse on the operands of the or.
6881       bool EitherMayExit = L->contains(FBB);
6882       ExitLimit EL0 = computeExitLimitFromCondCached(
6883           Cache, L, BO->getOperand(0), TBB, FBB, ControlsExit && !EitherMayExit,
6884           AllowPredicates);
6885       ExitLimit EL1 = computeExitLimitFromCondCached(
6886           Cache, L, BO->getOperand(1), TBB, FBB, ControlsExit && !EitherMayExit,
6887           AllowPredicates);
6888       const SCEV *BECount = getCouldNotCompute();
6889       const SCEV *MaxBECount = getCouldNotCompute();
6890       if (EitherMayExit) {
6891         // Both conditions must be false for the loop to continue executing.
6892         // Choose the less conservative count.
6893         if (EL0.ExactNotTaken == getCouldNotCompute() ||
6894             EL1.ExactNotTaken == getCouldNotCompute())
6895           BECount = getCouldNotCompute();
6896         else
6897           BECount =
6898               getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
6899         if (EL0.MaxNotTaken == getCouldNotCompute())
6900           MaxBECount = EL1.MaxNotTaken;
6901         else if (EL1.MaxNotTaken == getCouldNotCompute())
6902           MaxBECount = EL0.MaxNotTaken;
6903         else
6904           MaxBECount =
6905               getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
6906       } else {
6907         // Both conditions must be false at the same time for the loop to exit.
6908         // For now, be conservative.
6909         assert(L->contains(TBB) && "Loop block has no successor in loop!");
6910         if (EL0.MaxNotTaken == EL1.MaxNotTaken)
6911           MaxBECount = EL0.MaxNotTaken;
6912         if (EL0.ExactNotTaken == EL1.ExactNotTaken)
6913           BECount = EL0.ExactNotTaken;
6914       }
6915 
6916       return ExitLimit(BECount, MaxBECount, false,
6917                        {&EL0.Predicates, &EL1.Predicates});
6918     }
6919   }
6920 
6921   // With an icmp, it may be feasible to compute an exact backedge-taken count.
6922   // Proceed to the next level to examine the icmp.
6923   if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
6924     ExitLimit EL =
6925         computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit);
6926     if (EL.hasFullInfo() || !AllowPredicates)
6927       return EL;
6928 
6929     // Try again, but use SCEV predicates this time.
6930     return computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit,
6931                                     /*AllowPredicates=*/true);
6932   }
6933 
6934   // Check for a constant condition. These are normally stripped out by
6935   // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
6936   // preserve the CFG and is temporarily leaving constant conditions
6937   // in place.
6938   if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
6939     if (L->contains(FBB) == !CI->getZExtValue())
6940       // The backedge is always taken.
6941       return getCouldNotCompute();
6942     else
6943       // The backedge is never taken.
6944       return getZero(CI->getType());
6945   }
6946 
6947   // If it's not an integer or pointer comparison then compute it the hard way.
6948   return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
6949 }
6950 
6951 ScalarEvolution::ExitLimit
6952 ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
6953                                           ICmpInst *ExitCond,
6954                                           BasicBlock *TBB,
6955                                           BasicBlock *FBB,
6956                                           bool ControlsExit,
6957                                           bool AllowPredicates) {
6958   // If the condition was exit on true, convert the condition to exit on false
6959   ICmpInst::Predicate Cond;
6960   if (!L->contains(FBB))
6961     Cond = ExitCond->getPredicate();
6962   else
6963     Cond = ExitCond->getInversePredicate();
6964 
6965   // Handle common loops like: for (X = "string"; *X; ++X)
6966   if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
6967     if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
6968       ExitLimit ItCnt =
6969         computeLoadConstantCompareExitLimit(LI, RHS, L, Cond);
6970       if (ItCnt.hasAnyInfo())
6971         return ItCnt;
6972     }
6973 
6974   const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
6975   const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
6976 
6977   // Try to evaluate any dependencies out of the loop.
6978   LHS = getSCEVAtScope(LHS, L);
6979   RHS = getSCEVAtScope(RHS, L);
6980 
6981   // At this point, we would like to compute how many iterations of the
6982   // loop the predicate will return true for these inputs.
6983   if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
6984     // If there is a loop-invariant, force it into the RHS.
6985     std::swap(LHS, RHS);
6986     Cond = ICmpInst::getSwappedPredicate(Cond);
6987   }
6988 
6989   // Simplify the operands before analyzing them.
6990   (void)SimplifyICmpOperands(Cond, LHS, RHS);
6991 
6992   // If we have a comparison of a chrec against a constant, try to use value
6993   // ranges to answer this query.
6994   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
6995     if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
6996       if (AddRec->getLoop() == L) {
6997         // Form the constant range.
6998         ConstantRange CompRange =
6999             ConstantRange::makeExactICmpRegion(Cond, RHSC->getAPInt());
7000 
7001         const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
7002         if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
7003       }
7004 
7005   switch (Cond) {
7006   case ICmpInst::ICMP_NE: {                     // while (X != Y)
7007     // Convert to: while (X-Y != 0)
7008     ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit,
7009                                 AllowPredicates);
7010     if (EL.hasAnyInfo()) return EL;
7011     break;
7012   }
7013   case ICmpInst::ICMP_EQ: {                     // while (X == Y)
7014     // Convert to: while (X-Y == 0)
7015     ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
7016     if (EL.hasAnyInfo()) return EL;
7017     break;
7018   }
7019   case ICmpInst::ICMP_SLT:
7020   case ICmpInst::ICMP_ULT: {                    // while (X < Y)
7021     bool IsSigned = Cond == ICmpInst::ICMP_SLT;
7022     ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit,
7023                                     AllowPredicates);
7024     if (EL.hasAnyInfo()) return EL;
7025     break;
7026   }
7027   case ICmpInst::ICMP_SGT:
7028   case ICmpInst::ICMP_UGT: {                    // while (X > Y)
7029     bool IsSigned = Cond == ICmpInst::ICMP_SGT;
7030     ExitLimit EL =
7031         howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
7032                             AllowPredicates);
7033     if (EL.hasAnyInfo()) return EL;
7034     break;
7035   }
7036   default:
7037     break;
7038   }
7039 
7040   auto *ExhaustiveCount =
7041       computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
7042 
7043   if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
7044     return ExhaustiveCount;
7045 
7046   return computeShiftCompareExitLimit(ExitCond->getOperand(0),
7047                                       ExitCond->getOperand(1), L, Cond);
7048 }
7049 
7050 ScalarEvolution::ExitLimit
7051 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
7052                                                       SwitchInst *Switch,
7053                                                       BasicBlock *ExitingBlock,
7054                                                       bool ControlsExit) {
7055   assert(!L->contains(ExitingBlock) && "Not an exiting block!");
7056 
7057   // Give up if the exit is the default dest of a switch.
7058   if (Switch->getDefaultDest() == ExitingBlock)
7059     return getCouldNotCompute();
7060 
7061   assert(L->contains(Switch->getDefaultDest()) &&
7062          "Default case must not exit the loop!");
7063   const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
7064   const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
7065 
7066   // while (X != Y) --> while (X-Y != 0)
7067   ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
7068   if (EL.hasAnyInfo())
7069     return EL;
7070 
7071   return getCouldNotCompute();
7072 }
7073 
7074 static ConstantInt *
7075 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
7076                                 ScalarEvolution &SE) {
7077   const SCEV *InVal = SE.getConstant(C);
7078   const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
7079   assert(isa<SCEVConstant>(Val) &&
7080          "Evaluation of SCEV at constant didn't fold correctly?");
7081   return cast<SCEVConstant>(Val)->getValue();
7082 }
7083 
7084 /// Given an exit condition of 'icmp op load X, cst', try to see if we can
7085 /// compute the backedge execution count.
7086 ScalarEvolution::ExitLimit
7087 ScalarEvolution::computeLoadConstantCompareExitLimit(
7088   LoadInst *LI,
7089   Constant *RHS,
7090   const Loop *L,
7091   ICmpInst::Predicate predicate) {
7092   if (LI->isVolatile()) return getCouldNotCompute();
7093 
7094   // Check to see if the loaded pointer is a getelementptr of a global.
7095   // TODO: Use SCEV instead of manually grubbing with GEPs.
7096   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
7097   if (!GEP) return getCouldNotCompute();
7098 
7099   // Make sure that it is really a constant global we are gepping, with an
7100   // initializer, and make sure the first IDX is really 0.
7101   GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
7102   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
7103       GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
7104       !cast<Constant>(GEP->getOperand(1))->isNullValue())
7105     return getCouldNotCompute();
7106 
7107   // Okay, we allow one non-constant index into the GEP instruction.
7108   Value *VarIdx = nullptr;
7109   std::vector<Constant*> Indexes;
7110   unsigned VarIdxNum = 0;
7111   for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
7112     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
7113       Indexes.push_back(CI);
7114     } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
7115       if (VarIdx) return getCouldNotCompute();  // Multiple non-constant idx's.
7116       VarIdx = GEP->getOperand(i);
7117       VarIdxNum = i-2;
7118       Indexes.push_back(nullptr);
7119     }
7120 
7121   // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
7122   if (!VarIdx)
7123     return getCouldNotCompute();
7124 
7125   // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
7126   // Check to see if X is a loop variant variable value now.
7127   const SCEV *Idx = getSCEV(VarIdx);
7128   Idx = getSCEVAtScope(Idx, L);
7129 
7130   // We can only recognize very limited forms of loop index expressions, in
7131   // particular, only affine AddRec's like {C1,+,C2}.
7132   const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
7133   if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
7134       !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
7135       !isa<SCEVConstant>(IdxExpr->getOperand(1)))
7136     return getCouldNotCompute();
7137 
7138   unsigned MaxSteps = MaxBruteForceIterations;
7139   for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
7140     ConstantInt *ItCst = ConstantInt::get(
7141                            cast<IntegerType>(IdxExpr->getType()), IterationNum);
7142     ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
7143 
7144     // Form the GEP offset.
7145     Indexes[VarIdxNum] = Val;
7146 
7147     Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
7148                                                          Indexes);
7149     if (!Result) break;  // Cannot compute!
7150 
7151     // Evaluate the condition for this iteration.
7152     Result = ConstantExpr::getICmp(predicate, Result, RHS);
7153     if (!isa<ConstantInt>(Result)) break;  // Couldn't decide for sure
7154     if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
7155       ++NumArrayLenItCounts;
7156       return getConstant(ItCst);   // Found terminating iteration!
7157     }
7158   }
7159   return getCouldNotCompute();
7160 }
7161 
7162 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
7163     Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
7164   ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
7165   if (!RHS)
7166     return getCouldNotCompute();
7167 
7168   const BasicBlock *Latch = L->getLoopLatch();
7169   if (!Latch)
7170     return getCouldNotCompute();
7171 
7172   const BasicBlock *Predecessor = L->getLoopPredecessor();
7173   if (!Predecessor)
7174     return getCouldNotCompute();
7175 
7176   // Return true if V is of the form "LHS `shift_op` <positive constant>".
7177   // Return LHS in OutLHS and shift_opt in OutOpCode.
7178   auto MatchPositiveShift =
7179       [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
7180 
7181     using namespace PatternMatch;
7182 
7183     ConstantInt *ShiftAmt;
7184     if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7185       OutOpCode = Instruction::LShr;
7186     else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7187       OutOpCode = Instruction::AShr;
7188     else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7189       OutOpCode = Instruction::Shl;
7190     else
7191       return false;
7192 
7193     return ShiftAmt->getValue().isStrictlyPositive();
7194   };
7195 
7196   // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
7197   //
7198   // loop:
7199   //   %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
7200   //   %iv.shifted = lshr i32 %iv, <positive constant>
7201   //
7202   // Return true on a successful match.  Return the corresponding PHI node (%iv
7203   // above) in PNOut and the opcode of the shift operation in OpCodeOut.
7204   auto MatchShiftRecurrence =
7205       [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
7206     Optional<Instruction::BinaryOps> PostShiftOpCode;
7207 
7208     {
7209       Instruction::BinaryOps OpC;
7210       Value *V;
7211 
7212       // If we encounter a shift instruction, "peel off" the shift operation,
7213       // and remember that we did so.  Later when we inspect %iv's backedge
7214       // value, we will make sure that the backedge value uses the same
7215       // operation.
7216       //
7217       // Note: the peeled shift operation does not have to be the same
7218       // instruction as the one feeding into the PHI's backedge value.  We only
7219       // really care about it being the same *kind* of shift instruction --
7220       // that's all that is required for our later inferences to hold.
7221       if (MatchPositiveShift(LHS, V, OpC)) {
7222         PostShiftOpCode = OpC;
7223         LHS = V;
7224       }
7225     }
7226 
7227     PNOut = dyn_cast<PHINode>(LHS);
7228     if (!PNOut || PNOut->getParent() != L->getHeader())
7229       return false;
7230 
7231     Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
7232     Value *OpLHS;
7233 
7234     return
7235         // The backedge value for the PHI node must be a shift by a positive
7236         // amount
7237         MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
7238 
7239         // of the PHI node itself
7240         OpLHS == PNOut &&
7241 
7242         // and the kind of shift should be match the kind of shift we peeled
7243         // off, if any.
7244         (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut);
7245   };
7246 
7247   PHINode *PN;
7248   Instruction::BinaryOps OpCode;
7249   if (!MatchShiftRecurrence(LHS, PN, OpCode))
7250     return getCouldNotCompute();
7251 
7252   const DataLayout &DL = getDataLayout();
7253 
7254   // The key rationale for this optimization is that for some kinds of shift
7255   // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
7256   // within a finite number of iterations.  If the condition guarding the
7257   // backedge (in the sense that the backedge is taken if the condition is true)
7258   // is false for the value the shift recurrence stabilizes to, then we know
7259   // that the backedge is taken only a finite number of times.
7260 
7261   ConstantInt *StableValue = nullptr;
7262   switch (OpCode) {
7263   default:
7264     llvm_unreachable("Impossible case!");
7265 
7266   case Instruction::AShr: {
7267     // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
7268     // bitwidth(K) iterations.
7269     Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
7270     KnownBits Known = computeKnownBits(FirstValue, DL, 0, nullptr,
7271                                        Predecessor->getTerminator(), &DT);
7272     auto *Ty = cast<IntegerType>(RHS->getType());
7273     if (Known.isNonNegative())
7274       StableValue = ConstantInt::get(Ty, 0);
7275     else if (Known.isNegative())
7276       StableValue = ConstantInt::get(Ty, -1, true);
7277     else
7278       return getCouldNotCompute();
7279 
7280     break;
7281   }
7282   case Instruction::LShr:
7283   case Instruction::Shl:
7284     // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
7285     // stabilize to 0 in at most bitwidth(K) iterations.
7286     StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
7287     break;
7288   }
7289 
7290   auto *Result =
7291       ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
7292   assert(Result->getType()->isIntegerTy(1) &&
7293          "Otherwise cannot be an operand to a branch instruction");
7294 
7295   if (Result->isZeroValue()) {
7296     unsigned BitWidth = getTypeSizeInBits(RHS->getType());
7297     const SCEV *UpperBound =
7298         getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
7299     return ExitLimit(getCouldNotCompute(), UpperBound, false);
7300   }
7301 
7302   return getCouldNotCompute();
7303 }
7304 
7305 /// Return true if we can constant fold an instruction of the specified type,
7306 /// assuming that all operands were constants.
7307 static bool CanConstantFold(const Instruction *I) {
7308   if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
7309       isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
7310       isa<LoadInst>(I))
7311     return true;
7312 
7313   if (const CallInst *CI = dyn_cast<CallInst>(I))
7314     if (const Function *F = CI->getCalledFunction())
7315       return canConstantFoldCallTo(CI, F);
7316   return false;
7317 }
7318 
7319 /// Determine whether this instruction can constant evolve within this loop
7320 /// assuming its operands can all constant evolve.
7321 static bool canConstantEvolve(Instruction *I, const Loop *L) {
7322   // An instruction outside of the loop can't be derived from a loop PHI.
7323   if (!L->contains(I)) return false;
7324 
7325   if (isa<PHINode>(I)) {
7326     // We don't currently keep track of the control flow needed to evaluate
7327     // PHIs, so we cannot handle PHIs inside of loops.
7328     return L->getHeader() == I->getParent();
7329   }
7330 
7331   // If we won't be able to constant fold this expression even if the operands
7332   // are constants, bail early.
7333   return CanConstantFold(I);
7334 }
7335 
7336 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
7337 /// recursing through each instruction operand until reaching a loop header phi.
7338 static PHINode *
7339 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
7340                                DenseMap<Instruction *, PHINode *> &PHIMap,
7341                                unsigned Depth) {
7342   if (Depth > MaxConstantEvolvingDepth)
7343     return nullptr;
7344 
7345   // Otherwise, we can evaluate this instruction if all of its operands are
7346   // constant or derived from a PHI node themselves.
7347   PHINode *PHI = nullptr;
7348   for (Value *Op : UseInst->operands()) {
7349     if (isa<Constant>(Op)) continue;
7350 
7351     Instruction *OpInst = dyn_cast<Instruction>(Op);
7352     if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
7353 
7354     PHINode *P = dyn_cast<PHINode>(OpInst);
7355     if (!P)
7356       // If this operand is already visited, reuse the prior result.
7357       // We may have P != PHI if this is the deepest point at which the
7358       // inconsistent paths meet.
7359       P = PHIMap.lookup(OpInst);
7360     if (!P) {
7361       // Recurse and memoize the results, whether a phi is found or not.
7362       // This recursive call invalidates pointers into PHIMap.
7363       P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1);
7364       PHIMap[OpInst] = P;
7365     }
7366     if (!P)
7367       return nullptr;  // Not evolving from PHI
7368     if (PHI && PHI != P)
7369       return nullptr;  // Evolving from multiple different PHIs.
7370     PHI = P;
7371   }
7372   // This is a expression evolving from a constant PHI!
7373   return PHI;
7374 }
7375 
7376 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
7377 /// in the loop that V is derived from.  We allow arbitrary operations along the
7378 /// way, but the operands of an operation must either be constants or a value
7379 /// derived from a constant PHI.  If this expression does not fit with these
7380 /// constraints, return null.
7381 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
7382   Instruction *I = dyn_cast<Instruction>(V);
7383   if (!I || !canConstantEvolve(I, L)) return nullptr;
7384 
7385   if (PHINode *PN = dyn_cast<PHINode>(I))
7386     return PN;
7387 
7388   // Record non-constant instructions contained by the loop.
7389   DenseMap<Instruction *, PHINode *> PHIMap;
7390   return getConstantEvolvingPHIOperands(I, L, PHIMap, 0);
7391 }
7392 
7393 /// EvaluateExpression - Given an expression that passes the
7394 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
7395 /// in the loop has the value PHIVal.  If we can't fold this expression for some
7396 /// reason, return null.
7397 static Constant *EvaluateExpression(Value *V, const Loop *L,
7398                                     DenseMap<Instruction *, Constant *> &Vals,
7399                                     const DataLayout &DL,
7400                                     const TargetLibraryInfo *TLI) {
7401   // Convenient constant check, but redundant for recursive calls.
7402   if (Constant *C = dyn_cast<Constant>(V)) return C;
7403   Instruction *I = dyn_cast<Instruction>(V);
7404   if (!I) return nullptr;
7405 
7406   if (Constant *C = Vals.lookup(I)) return C;
7407 
7408   // An instruction inside the loop depends on a value outside the loop that we
7409   // weren't given a mapping for, or a value such as a call inside the loop.
7410   if (!canConstantEvolve(I, L)) return nullptr;
7411 
7412   // An unmapped PHI can be due to a branch or another loop inside this loop,
7413   // or due to this not being the initial iteration through a loop where we
7414   // couldn't compute the evolution of this particular PHI last time.
7415   if (isa<PHINode>(I)) return nullptr;
7416 
7417   std::vector<Constant*> Operands(I->getNumOperands());
7418 
7419   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
7420     Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
7421     if (!Operand) {
7422       Operands[i] = dyn_cast<Constant>(I->getOperand(i));
7423       if (!Operands[i]) return nullptr;
7424       continue;
7425     }
7426     Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
7427     Vals[Operand] = C;
7428     if (!C) return nullptr;
7429     Operands[i] = C;
7430   }
7431 
7432   if (CmpInst *CI = dyn_cast<CmpInst>(I))
7433     return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
7434                                            Operands[1], DL, TLI);
7435   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
7436     if (!LI->isVolatile())
7437       return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
7438   }
7439   return ConstantFoldInstOperands(I, Operands, DL, TLI);
7440 }
7441 
7442 
7443 // If every incoming value to PN except the one for BB is a specific Constant,
7444 // return that, else return nullptr.
7445 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
7446   Constant *IncomingVal = nullptr;
7447 
7448   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
7449     if (PN->getIncomingBlock(i) == BB)
7450       continue;
7451 
7452     auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
7453     if (!CurrentVal)
7454       return nullptr;
7455 
7456     if (IncomingVal != CurrentVal) {
7457       if (IncomingVal)
7458         return nullptr;
7459       IncomingVal = CurrentVal;
7460     }
7461   }
7462 
7463   return IncomingVal;
7464 }
7465 
7466 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
7467 /// in the header of its containing loop, we know the loop executes a
7468 /// constant number of times, and the PHI node is just a recurrence
7469 /// involving constants, fold it.
7470 Constant *
7471 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
7472                                                    const APInt &BEs,
7473                                                    const Loop *L) {
7474   auto I = ConstantEvolutionLoopExitValue.find(PN);
7475   if (I != ConstantEvolutionLoopExitValue.end())
7476     return I->second;
7477 
7478   if (BEs.ugt(MaxBruteForceIterations))
7479     return ConstantEvolutionLoopExitValue[PN] = nullptr;  // Not going to evaluate it.
7480 
7481   Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
7482 
7483   DenseMap<Instruction *, Constant *> CurrentIterVals;
7484   BasicBlock *Header = L->getHeader();
7485   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
7486 
7487   BasicBlock *Latch = L->getLoopLatch();
7488   if (!Latch)
7489     return nullptr;
7490 
7491   for (auto &I : *Header) {
7492     PHINode *PHI = dyn_cast<PHINode>(&I);
7493     if (!PHI) break;
7494     auto *StartCST = getOtherIncomingValue(PHI, Latch);
7495     if (!StartCST) continue;
7496     CurrentIterVals[PHI] = StartCST;
7497   }
7498   if (!CurrentIterVals.count(PN))
7499     return RetVal = nullptr;
7500 
7501   Value *BEValue = PN->getIncomingValueForBlock(Latch);
7502 
7503   // Execute the loop symbolically to determine the exit value.
7504   assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) &&
7505          "BEs is <= MaxBruteForceIterations which is an 'unsigned'!");
7506 
7507   unsigned NumIterations = BEs.getZExtValue(); // must be in range
7508   unsigned IterationNum = 0;
7509   const DataLayout &DL = getDataLayout();
7510   for (; ; ++IterationNum) {
7511     if (IterationNum == NumIterations)
7512       return RetVal = CurrentIterVals[PN];  // Got exit value!
7513 
7514     // Compute the value of the PHIs for the next iteration.
7515     // EvaluateExpression adds non-phi values to the CurrentIterVals map.
7516     DenseMap<Instruction *, Constant *> NextIterVals;
7517     Constant *NextPHI =
7518         EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
7519     if (!NextPHI)
7520       return nullptr;        // Couldn't evaluate!
7521     NextIterVals[PN] = NextPHI;
7522 
7523     bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
7524 
7525     // Also evaluate the other PHI nodes.  However, we don't get to stop if we
7526     // cease to be able to evaluate one of them or if they stop evolving,
7527     // because that doesn't necessarily prevent us from computing PN.
7528     SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
7529     for (const auto &I : CurrentIterVals) {
7530       PHINode *PHI = dyn_cast<PHINode>(I.first);
7531       if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
7532       PHIsToCompute.emplace_back(PHI, I.second);
7533     }
7534     // We use two distinct loops because EvaluateExpression may invalidate any
7535     // iterators into CurrentIterVals.
7536     for (const auto &I : PHIsToCompute) {
7537       PHINode *PHI = I.first;
7538       Constant *&NextPHI = NextIterVals[PHI];
7539       if (!NextPHI) {   // Not already computed.
7540         Value *BEValue = PHI->getIncomingValueForBlock(Latch);
7541         NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
7542       }
7543       if (NextPHI != I.second)
7544         StoppedEvolving = false;
7545     }
7546 
7547     // If all entries in CurrentIterVals == NextIterVals then we can stop
7548     // iterating, the loop can't continue to change.
7549     if (StoppedEvolving)
7550       return RetVal = CurrentIterVals[PN];
7551 
7552     CurrentIterVals.swap(NextIterVals);
7553   }
7554 }
7555 
7556 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
7557                                                           Value *Cond,
7558                                                           bool ExitWhen) {
7559   PHINode *PN = getConstantEvolvingPHI(Cond, L);
7560   if (!PN) return getCouldNotCompute();
7561 
7562   // If the loop is canonicalized, the PHI will have exactly two entries.
7563   // That's the only form we support here.
7564   if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
7565 
7566   DenseMap<Instruction *, Constant *> CurrentIterVals;
7567   BasicBlock *Header = L->getHeader();
7568   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
7569 
7570   BasicBlock *Latch = L->getLoopLatch();
7571   assert(Latch && "Should follow from NumIncomingValues == 2!");
7572 
7573   for (auto &I : *Header) {
7574     PHINode *PHI = dyn_cast<PHINode>(&I);
7575     if (!PHI)
7576       break;
7577     auto *StartCST = getOtherIncomingValue(PHI, Latch);
7578     if (!StartCST) continue;
7579     CurrentIterVals[PHI] = StartCST;
7580   }
7581   if (!CurrentIterVals.count(PN))
7582     return getCouldNotCompute();
7583 
7584   // Okay, we find a PHI node that defines the trip count of this loop.  Execute
7585   // the loop symbolically to determine when the condition gets a value of
7586   // "ExitWhen".
7587   unsigned MaxIterations = MaxBruteForceIterations;   // Limit analysis.
7588   const DataLayout &DL = getDataLayout();
7589   for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
7590     auto *CondVal = dyn_cast_or_null<ConstantInt>(
7591         EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
7592 
7593     // Couldn't symbolically evaluate.
7594     if (!CondVal) return getCouldNotCompute();
7595 
7596     if (CondVal->getValue() == uint64_t(ExitWhen)) {
7597       ++NumBruteForceTripCountsComputed;
7598       return getConstant(Type::getInt32Ty(getContext()), IterationNum);
7599     }
7600 
7601     // Update all the PHI nodes for the next iteration.
7602     DenseMap<Instruction *, Constant *> NextIterVals;
7603 
7604     // Create a list of which PHIs we need to compute. We want to do this before
7605     // calling EvaluateExpression on them because that may invalidate iterators
7606     // into CurrentIterVals.
7607     SmallVector<PHINode *, 8> PHIsToCompute;
7608     for (const auto &I : CurrentIterVals) {
7609       PHINode *PHI = dyn_cast<PHINode>(I.first);
7610       if (!PHI || PHI->getParent() != Header) continue;
7611       PHIsToCompute.push_back(PHI);
7612     }
7613     for (PHINode *PHI : PHIsToCompute) {
7614       Constant *&NextPHI = NextIterVals[PHI];
7615       if (NextPHI) continue;    // Already computed!
7616 
7617       Value *BEValue = PHI->getIncomingValueForBlock(Latch);
7618       NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
7619     }
7620     CurrentIterVals.swap(NextIterVals);
7621   }
7622 
7623   // Too many iterations were needed to evaluate.
7624   return getCouldNotCompute();
7625 }
7626 
7627 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
7628   SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
7629       ValuesAtScopes[V];
7630   // Check to see if we've folded this expression at this loop before.
7631   for (auto &LS : Values)
7632     if (LS.first == L)
7633       return LS.second ? LS.second : V;
7634 
7635   Values.emplace_back(L, nullptr);
7636 
7637   // Otherwise compute it.
7638   const SCEV *C = computeSCEVAtScope(V, L);
7639   for (auto &LS : reverse(ValuesAtScopes[V]))
7640     if (LS.first == L) {
7641       LS.second = C;
7642       break;
7643     }
7644   return C;
7645 }
7646 
7647 /// This builds up a Constant using the ConstantExpr interface.  That way, we
7648 /// will return Constants for objects which aren't represented by a
7649 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
7650 /// Returns NULL if the SCEV isn't representable as a Constant.
7651 static Constant *BuildConstantFromSCEV(const SCEV *V) {
7652   switch (static_cast<SCEVTypes>(V->getSCEVType())) {
7653     case scCouldNotCompute:
7654     case scAddRecExpr:
7655       break;
7656     case scConstant:
7657       return cast<SCEVConstant>(V)->getValue();
7658     case scUnknown:
7659       return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
7660     case scSignExtend: {
7661       const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
7662       if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
7663         return ConstantExpr::getSExt(CastOp, SS->getType());
7664       break;
7665     }
7666     case scZeroExtend: {
7667       const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
7668       if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
7669         return ConstantExpr::getZExt(CastOp, SZ->getType());
7670       break;
7671     }
7672     case scTruncate: {
7673       const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
7674       if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
7675         return ConstantExpr::getTrunc(CastOp, ST->getType());
7676       break;
7677     }
7678     case scAddExpr: {
7679       const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
7680       if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
7681         if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
7682           unsigned AS = PTy->getAddressSpace();
7683           Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
7684           C = ConstantExpr::getBitCast(C, DestPtrTy);
7685         }
7686         for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
7687           Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
7688           if (!C2) return nullptr;
7689 
7690           // First pointer!
7691           if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
7692             unsigned AS = C2->getType()->getPointerAddressSpace();
7693             std::swap(C, C2);
7694             Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
7695             // The offsets have been converted to bytes.  We can add bytes to an
7696             // i8* by GEP with the byte count in the first index.
7697             C = ConstantExpr::getBitCast(C, DestPtrTy);
7698           }
7699 
7700           // Don't bother trying to sum two pointers. We probably can't
7701           // statically compute a load that results from it anyway.
7702           if (C2->getType()->isPointerTy())
7703             return nullptr;
7704 
7705           if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
7706             if (PTy->getElementType()->isStructTy())
7707               C2 = ConstantExpr::getIntegerCast(
7708                   C2, Type::getInt32Ty(C->getContext()), true);
7709             C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2);
7710           } else
7711             C = ConstantExpr::getAdd(C, C2);
7712         }
7713         return C;
7714       }
7715       break;
7716     }
7717     case scMulExpr: {
7718       const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
7719       if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
7720         // Don't bother with pointers at all.
7721         if (C->getType()->isPointerTy()) return nullptr;
7722         for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
7723           Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
7724           if (!C2 || C2->getType()->isPointerTy()) return nullptr;
7725           C = ConstantExpr::getMul(C, C2);
7726         }
7727         return C;
7728       }
7729       break;
7730     }
7731     case scUDivExpr: {
7732       const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
7733       if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
7734         if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
7735           if (LHS->getType() == RHS->getType())
7736             return ConstantExpr::getUDiv(LHS, RHS);
7737       break;
7738     }
7739     case scSMaxExpr:
7740     case scUMaxExpr:
7741       break; // TODO: smax, umax.
7742   }
7743   return nullptr;
7744 }
7745 
7746 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
7747   if (isa<SCEVConstant>(V)) return V;
7748 
7749   // If this instruction is evolved from a constant-evolving PHI, compute the
7750   // exit value from the loop without using SCEVs.
7751   if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
7752     if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
7753       const Loop *LI = this->LI[I->getParent()];
7754       if (LI && LI->getParentLoop() == L)  // Looking for loop exit value.
7755         if (PHINode *PN = dyn_cast<PHINode>(I))
7756           if (PN->getParent() == LI->getHeader()) {
7757             // Okay, there is no closed form solution for the PHI node.  Check
7758             // to see if the loop that contains it has a known backedge-taken
7759             // count.  If so, we may be able to force computation of the exit
7760             // value.
7761             const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
7762             if (const SCEVConstant *BTCC =
7763                   dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
7764 
7765               // This trivial case can show up in some degenerate cases where
7766               // the incoming IR has not yet been fully simplified.
7767               if (BTCC->getValue()->isZero()) {
7768                 Value *InitValue = nullptr;
7769                 bool MultipleInitValues = false;
7770                 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
7771                   if (!LI->contains(PN->getIncomingBlock(i))) {
7772                     if (!InitValue)
7773                       InitValue = PN->getIncomingValue(i);
7774                     else if (InitValue != PN->getIncomingValue(i)) {
7775                       MultipleInitValues = true;
7776                       break;
7777                     }
7778                   }
7779                   if (!MultipleInitValues && InitValue)
7780                     return getSCEV(InitValue);
7781                 }
7782               }
7783               // Okay, we know how many times the containing loop executes.  If
7784               // this is a constant evolving PHI node, get the final value at
7785               // the specified iteration number.
7786               Constant *RV =
7787                   getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI);
7788               if (RV) return getSCEV(RV);
7789             }
7790           }
7791 
7792       // Okay, this is an expression that we cannot symbolically evaluate
7793       // into a SCEV.  Check to see if it's possible to symbolically evaluate
7794       // the arguments into constants, and if so, try to constant propagate the
7795       // result.  This is particularly useful for computing loop exit values.
7796       if (CanConstantFold(I)) {
7797         SmallVector<Constant *, 4> Operands;
7798         bool MadeImprovement = false;
7799         for (Value *Op : I->operands()) {
7800           if (Constant *C = dyn_cast<Constant>(Op)) {
7801             Operands.push_back(C);
7802             continue;
7803           }
7804 
7805           // If any of the operands is non-constant and if they are
7806           // non-integer and non-pointer, don't even try to analyze them
7807           // with scev techniques.
7808           if (!isSCEVable(Op->getType()))
7809             return V;
7810 
7811           const SCEV *OrigV = getSCEV(Op);
7812           const SCEV *OpV = getSCEVAtScope(OrigV, L);
7813           MadeImprovement |= OrigV != OpV;
7814 
7815           Constant *C = BuildConstantFromSCEV(OpV);
7816           if (!C) return V;
7817           if (C->getType() != Op->getType())
7818             C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
7819                                                               Op->getType(),
7820                                                               false),
7821                                       C, Op->getType());
7822           Operands.push_back(C);
7823         }
7824 
7825         // Check to see if getSCEVAtScope actually made an improvement.
7826         if (MadeImprovement) {
7827           Constant *C = nullptr;
7828           const DataLayout &DL = getDataLayout();
7829           if (const CmpInst *CI = dyn_cast<CmpInst>(I))
7830             C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
7831                                                 Operands[1], DL, &TLI);
7832           else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
7833             if (!LI->isVolatile())
7834               C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
7835           } else
7836             C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
7837           if (!C) return V;
7838           return getSCEV(C);
7839         }
7840       }
7841     }
7842 
7843     // This is some other type of SCEVUnknown, just return it.
7844     return V;
7845   }
7846 
7847   if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
7848     // Avoid performing the look-up in the common case where the specified
7849     // expression has no loop-variant portions.
7850     for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
7851       const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
7852       if (OpAtScope != Comm->getOperand(i)) {
7853         // Okay, at least one of these operands is loop variant but might be
7854         // foldable.  Build a new instance of the folded commutative expression.
7855         SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
7856                                             Comm->op_begin()+i);
7857         NewOps.push_back(OpAtScope);
7858 
7859         for (++i; i != e; ++i) {
7860           OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
7861           NewOps.push_back(OpAtScope);
7862         }
7863         if (isa<SCEVAddExpr>(Comm))
7864           return getAddExpr(NewOps);
7865         if (isa<SCEVMulExpr>(Comm))
7866           return getMulExpr(NewOps);
7867         if (isa<SCEVSMaxExpr>(Comm))
7868           return getSMaxExpr(NewOps);
7869         if (isa<SCEVUMaxExpr>(Comm))
7870           return getUMaxExpr(NewOps);
7871         llvm_unreachable("Unknown commutative SCEV type!");
7872       }
7873     }
7874     // If we got here, all operands are loop invariant.
7875     return Comm;
7876   }
7877 
7878   if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
7879     const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
7880     const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
7881     if (LHS == Div->getLHS() && RHS == Div->getRHS())
7882       return Div;   // must be loop invariant
7883     return getUDivExpr(LHS, RHS);
7884   }
7885 
7886   // If this is a loop recurrence for a loop that does not contain L, then we
7887   // are dealing with the final value computed by the loop.
7888   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
7889     // First, attempt to evaluate each operand.
7890     // Avoid performing the look-up in the common case where the specified
7891     // expression has no loop-variant portions.
7892     for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
7893       const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
7894       if (OpAtScope == AddRec->getOperand(i))
7895         continue;
7896 
7897       // Okay, at least one of these operands is loop variant but might be
7898       // foldable.  Build a new instance of the folded commutative expression.
7899       SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
7900                                           AddRec->op_begin()+i);
7901       NewOps.push_back(OpAtScope);
7902       for (++i; i != e; ++i)
7903         NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
7904 
7905       const SCEV *FoldedRec =
7906         getAddRecExpr(NewOps, AddRec->getLoop(),
7907                       AddRec->getNoWrapFlags(SCEV::FlagNW));
7908       AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
7909       // The addrec may be folded to a nonrecurrence, for example, if the
7910       // induction variable is multiplied by zero after constant folding. Go
7911       // ahead and return the folded value.
7912       if (!AddRec)
7913         return FoldedRec;
7914       break;
7915     }
7916 
7917     // If the scope is outside the addrec's loop, evaluate it by using the
7918     // loop exit value of the addrec.
7919     if (!AddRec->getLoop()->contains(L)) {
7920       // To evaluate this recurrence, we need to know how many times the AddRec
7921       // loop iterates.  Compute this now.
7922       const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
7923       if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
7924 
7925       // Then, evaluate the AddRec.
7926       return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
7927     }
7928 
7929     return AddRec;
7930   }
7931 
7932   if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
7933     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
7934     if (Op == Cast->getOperand())
7935       return Cast;  // must be loop invariant
7936     return getZeroExtendExpr(Op, Cast->getType());
7937   }
7938 
7939   if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
7940     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
7941     if (Op == Cast->getOperand())
7942       return Cast;  // must be loop invariant
7943     return getSignExtendExpr(Op, Cast->getType());
7944   }
7945 
7946   if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
7947     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
7948     if (Op == Cast->getOperand())
7949       return Cast;  // must be loop invariant
7950     return getTruncateExpr(Op, Cast->getType());
7951   }
7952 
7953   llvm_unreachable("Unknown SCEV type!");
7954 }
7955 
7956 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
7957   return getSCEVAtScope(getSCEV(V), L);
7958 }
7959 
7960 /// Finds the minimum unsigned root of the following equation:
7961 ///
7962 ///     A * X = B (mod N)
7963 ///
7964 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
7965 /// A and B isn't important.
7966 ///
7967 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
7968 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B,
7969                                                ScalarEvolution &SE) {
7970   uint32_t BW = A.getBitWidth();
7971   assert(BW == SE.getTypeSizeInBits(B->getType()));
7972   assert(A != 0 && "A must be non-zero.");
7973 
7974   // 1. D = gcd(A, N)
7975   //
7976   // The gcd of A and N may have only one prime factor: 2. The number of
7977   // trailing zeros in A is its multiplicity
7978   uint32_t Mult2 = A.countTrailingZeros();
7979   // D = 2^Mult2
7980 
7981   // 2. Check if B is divisible by D.
7982   //
7983   // B is divisible by D if and only if the multiplicity of prime factor 2 for B
7984   // is not less than multiplicity of this prime factor for D.
7985   if (SE.GetMinTrailingZeros(B) < Mult2)
7986     return SE.getCouldNotCompute();
7987 
7988   // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
7989   // modulo (N / D).
7990   //
7991   // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
7992   // (N / D) in general. The inverse itself always fits into BW bits, though,
7993   // so we immediately truncate it.
7994   APInt AD = A.lshr(Mult2).zext(BW + 1);  // AD = A / D
7995   APInt Mod(BW + 1, 0);
7996   Mod.setBit(BW - Mult2);  // Mod = N / D
7997   APInt I = AD.multiplicativeInverse(Mod).trunc(BW);
7998 
7999   // 4. Compute the minimum unsigned root of the equation:
8000   // I * (B / D) mod (N / D)
8001   // To simplify the computation, we factor out the divide by D:
8002   // (I * B mod N) / D
8003   const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
8004   return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
8005 }
8006 
8007 /// Find the roots of the quadratic equation for the given quadratic chrec
8008 /// {L,+,M,+,N}.  This returns either the two roots (which might be the same) or
8009 /// two SCEVCouldNotCompute objects.
8010 static Optional<std::pair<const SCEVConstant *,const SCEVConstant *>>
8011 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
8012   assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
8013   const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
8014   const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
8015   const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
8016 
8017   // We currently can only solve this if the coefficients are constants.
8018   if (!LC || !MC || !NC)
8019     return None;
8020 
8021   uint32_t BitWidth = LC->getAPInt().getBitWidth();
8022   const APInt &L = LC->getAPInt();
8023   const APInt &M = MC->getAPInt();
8024   const APInt &N = NC->getAPInt();
8025   APInt Two(BitWidth, 2);
8026 
8027   // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
8028 
8029   // The A coefficient is N/2
8030   APInt A = N.sdiv(Two);
8031 
8032   // The B coefficient is M-N/2
8033   APInt B = M;
8034   B -= A; // A is the same as N/2.
8035 
8036   // The C coefficient is L.
8037   const APInt& C = L;
8038 
8039   // Compute the B^2-4ac term.
8040   APInt SqrtTerm = B;
8041   SqrtTerm *= B;
8042   SqrtTerm -= 4 * (A * C);
8043 
8044   if (SqrtTerm.isNegative()) {
8045     // The loop is provably infinite.
8046     return None;
8047   }
8048 
8049   // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
8050   // integer value or else APInt::sqrt() will assert.
8051   APInt SqrtVal = SqrtTerm.sqrt();
8052 
8053   // Compute the two solutions for the quadratic formula.
8054   // The divisions must be performed as signed divisions.
8055   APInt NegB = -std::move(B);
8056   APInt TwoA = std::move(A);
8057   TwoA <<= 1;
8058   if (TwoA.isNullValue())
8059     return None;
8060 
8061   LLVMContext &Context = SE.getContext();
8062 
8063   ConstantInt *Solution1 =
8064     ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
8065   ConstantInt *Solution2 =
8066     ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
8067 
8068   return std::make_pair(cast<SCEVConstant>(SE.getConstant(Solution1)),
8069                         cast<SCEVConstant>(SE.getConstant(Solution2)));
8070 }
8071 
8072 ScalarEvolution::ExitLimit
8073 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit,
8074                               bool AllowPredicates) {
8075 
8076   // This is only used for loops with a "x != y" exit test. The exit condition
8077   // is now expressed as a single expression, V = x-y. So the exit test is
8078   // effectively V != 0.  We know and take advantage of the fact that this
8079   // expression only being used in a comparison by zero context.
8080 
8081   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
8082   // If the value is a constant
8083   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
8084     // If the value is already zero, the branch will execute zero times.
8085     if (C->getValue()->isZero()) return C;
8086     return getCouldNotCompute();  // Otherwise it will loop infinitely.
8087   }
8088 
8089   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
8090   if (!AddRec && AllowPredicates)
8091     // Try to make this an AddRec using runtime tests, in the first X
8092     // iterations of this loop, where X is the SCEV expression found by the
8093     // algorithm below.
8094     AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
8095 
8096   if (!AddRec || AddRec->getLoop() != L)
8097     return getCouldNotCompute();
8098 
8099   // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
8100   // the quadratic equation to solve it.
8101   if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
8102     if (auto Roots = SolveQuadraticEquation(AddRec, *this)) {
8103       const SCEVConstant *R1 = Roots->first;
8104       const SCEVConstant *R2 = Roots->second;
8105       // Pick the smallest positive root value.
8106       if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
8107               CmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
8108         if (!CB->getZExtValue())
8109           std::swap(R1, R2); // R1 is the minimum root now.
8110 
8111         // We can only use this value if the chrec ends up with an exact zero
8112         // value at this index.  When solving for "X*X != 5", for example, we
8113         // should not accept a root of 2.
8114         const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
8115         if (Val->isZero())
8116           // We found a quadratic root!
8117           return ExitLimit(R1, R1, false, Predicates);
8118       }
8119     }
8120     return getCouldNotCompute();
8121   }
8122 
8123   // Otherwise we can only handle this if it is affine.
8124   if (!AddRec->isAffine())
8125     return getCouldNotCompute();
8126 
8127   // If this is an affine expression, the execution count of this branch is
8128   // the minimum unsigned root of the following equation:
8129   //
8130   //     Start + Step*N = 0 (mod 2^BW)
8131   //
8132   // equivalent to:
8133   //
8134   //             Step*N = -Start (mod 2^BW)
8135   //
8136   // where BW is the common bit width of Start and Step.
8137 
8138   // Get the initial value for the loop.
8139   const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
8140   const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
8141 
8142   // For now we handle only constant steps.
8143   //
8144   // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
8145   // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
8146   // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
8147   // We have not yet seen any such cases.
8148   const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
8149   if (!StepC || StepC->getValue()->isZero())
8150     return getCouldNotCompute();
8151 
8152   // For positive steps (counting up until unsigned overflow):
8153   //   N = -Start/Step (as unsigned)
8154   // For negative steps (counting down to zero):
8155   //   N = Start/-Step
8156   // First compute the unsigned distance from zero in the direction of Step.
8157   bool CountDown = StepC->getAPInt().isNegative();
8158   const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
8159 
8160   // Handle unitary steps, which cannot wraparound.
8161   // 1*N = -Start; -1*N = Start (mod 2^BW), so:
8162   //   N = Distance (as unsigned)
8163   if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) {
8164     APInt MaxBECount = getUnsignedRangeMax(Distance);
8165 
8166     // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
8167     // we end up with a loop whose backedge-taken count is n - 1.  Detect this
8168     // case, and see if we can improve the bound.
8169     //
8170     // Explicitly handling this here is necessary because getUnsignedRange
8171     // isn't context-sensitive; it doesn't know that we only care about the
8172     // range inside the loop.
8173     const SCEV *Zero = getZero(Distance->getType());
8174     const SCEV *One = getOne(Distance->getType());
8175     const SCEV *DistancePlusOne = getAddExpr(Distance, One);
8176     if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
8177       // If Distance + 1 doesn't overflow, we can compute the maximum distance
8178       // as "unsigned_max(Distance + 1) - 1".
8179       ConstantRange CR = getUnsignedRange(DistancePlusOne);
8180       MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1);
8181     }
8182     return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates);
8183   }
8184 
8185   // If the condition controls loop exit (the loop exits only if the expression
8186   // is true) and the addition is no-wrap we can use unsigned divide to
8187   // compute the backedge count.  In this case, the step may not divide the
8188   // distance, but we don't care because if the condition is "missed" the loop
8189   // will have undefined behavior due to wrapping.
8190   if (ControlsExit && AddRec->hasNoSelfWrap() &&
8191       loopHasNoAbnormalExits(AddRec->getLoop())) {
8192     const SCEV *Exact =
8193         getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
8194     const SCEV *Max =
8195         Exact == getCouldNotCompute()
8196             ? Exact
8197             : getConstant(getUnsignedRangeMax(Exact));
8198     return ExitLimit(Exact, Max, false, Predicates);
8199   }
8200 
8201   // Solve the general equation.
8202   const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(),
8203                                                getNegativeSCEV(Start), *this);
8204   const SCEV *M = E == getCouldNotCompute()
8205                       ? E
8206                       : getConstant(getUnsignedRangeMax(E));
8207   return ExitLimit(E, M, false, Predicates);
8208 }
8209 
8210 ScalarEvolution::ExitLimit
8211 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
8212   // Loops that look like: while (X == 0) are very strange indeed.  We don't
8213   // handle them yet except for the trivial case.  This could be expanded in the
8214   // future as needed.
8215 
8216   // If the value is a constant, check to see if it is known to be non-zero
8217   // already.  If so, the backedge will execute zero times.
8218   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
8219     if (!C->getValue()->isZero())
8220       return getZero(C->getType());
8221     return getCouldNotCompute();  // Otherwise it will loop infinitely.
8222   }
8223 
8224   // We could implement others, but I really doubt anyone writes loops like
8225   // this, and if they did, they would already be constant folded.
8226   return getCouldNotCompute();
8227 }
8228 
8229 std::pair<BasicBlock *, BasicBlock *>
8230 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
8231   // If the block has a unique predecessor, then there is no path from the
8232   // predecessor to the block that does not go through the direct edge
8233   // from the predecessor to the block.
8234   if (BasicBlock *Pred = BB->getSinglePredecessor())
8235     return {Pred, BB};
8236 
8237   // A loop's header is defined to be a block that dominates the loop.
8238   // If the header has a unique predecessor outside the loop, it must be
8239   // a block that has exactly one successor that can reach the loop.
8240   if (Loop *L = LI.getLoopFor(BB))
8241     return {L->getLoopPredecessor(), L->getHeader()};
8242 
8243   return {nullptr, nullptr};
8244 }
8245 
8246 /// SCEV structural equivalence is usually sufficient for testing whether two
8247 /// expressions are equal, however for the purposes of looking for a condition
8248 /// guarding a loop, it can be useful to be a little more general, since a
8249 /// front-end may have replicated the controlling expression.
8250 static bool HasSameValue(const SCEV *A, const SCEV *B) {
8251   // Quick check to see if they are the same SCEV.
8252   if (A == B) return true;
8253 
8254   auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
8255     // Not all instructions that are "identical" compute the same value.  For
8256     // instance, two distinct alloca instructions allocating the same type are
8257     // identical and do not read memory; but compute distinct values.
8258     return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
8259   };
8260 
8261   // Otherwise, if they're both SCEVUnknown, it's possible that they hold
8262   // two different instructions with the same value. Check for this case.
8263   if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
8264     if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
8265       if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
8266         if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
8267           if (ComputesEqualValues(AI, BI))
8268             return true;
8269 
8270   // Otherwise assume they may have a different value.
8271   return false;
8272 }
8273 
8274 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
8275                                            const SCEV *&LHS, const SCEV *&RHS,
8276                                            unsigned Depth) {
8277   bool Changed = false;
8278 
8279   // If we hit the max recursion limit bail out.
8280   if (Depth >= 3)
8281     return false;
8282 
8283   // Canonicalize a constant to the right side.
8284   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
8285     // Check for both operands constant.
8286     if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
8287       if (ConstantExpr::getICmp(Pred,
8288                                 LHSC->getValue(),
8289                                 RHSC->getValue())->isNullValue())
8290         goto trivially_false;
8291       else
8292         goto trivially_true;
8293     }
8294     // Otherwise swap the operands to put the constant on the right.
8295     std::swap(LHS, RHS);
8296     Pred = ICmpInst::getSwappedPredicate(Pred);
8297     Changed = true;
8298   }
8299 
8300   // If we're comparing an addrec with a value which is loop-invariant in the
8301   // addrec's loop, put the addrec on the left. Also make a dominance check,
8302   // as both operands could be addrecs loop-invariant in each other's loop.
8303   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
8304     const Loop *L = AR->getLoop();
8305     if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
8306       std::swap(LHS, RHS);
8307       Pred = ICmpInst::getSwappedPredicate(Pred);
8308       Changed = true;
8309     }
8310   }
8311 
8312   // If there's a constant operand, canonicalize comparisons with boundary
8313   // cases, and canonicalize *-or-equal comparisons to regular comparisons.
8314   if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
8315     const APInt &RA = RC->getAPInt();
8316 
8317     bool SimplifiedByConstantRange = false;
8318 
8319     if (!ICmpInst::isEquality(Pred)) {
8320       ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA);
8321       if (ExactCR.isFullSet())
8322         goto trivially_true;
8323       else if (ExactCR.isEmptySet())
8324         goto trivially_false;
8325 
8326       APInt NewRHS;
8327       CmpInst::Predicate NewPred;
8328       if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
8329           ICmpInst::isEquality(NewPred)) {
8330         // We were able to convert an inequality to an equality.
8331         Pred = NewPred;
8332         RHS = getConstant(NewRHS);
8333         Changed = SimplifiedByConstantRange = true;
8334       }
8335     }
8336 
8337     if (!SimplifiedByConstantRange) {
8338       switch (Pred) {
8339       default:
8340         break;
8341       case ICmpInst::ICMP_EQ:
8342       case ICmpInst::ICMP_NE:
8343         // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
8344         if (!RA)
8345           if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
8346             if (const SCEVMulExpr *ME =
8347                     dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
8348               if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
8349                   ME->getOperand(0)->isAllOnesValue()) {
8350                 RHS = AE->getOperand(1);
8351                 LHS = ME->getOperand(1);
8352                 Changed = true;
8353               }
8354         break;
8355 
8356 
8357         // The "Should have been caught earlier!" messages refer to the fact
8358         // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
8359         // should have fired on the corresponding cases, and canonicalized the
8360         // check to trivially_true or trivially_false.
8361 
8362       case ICmpInst::ICMP_UGE:
8363         assert(!RA.isMinValue() && "Should have been caught earlier!");
8364         Pred = ICmpInst::ICMP_UGT;
8365         RHS = getConstant(RA - 1);
8366         Changed = true;
8367         break;
8368       case ICmpInst::ICMP_ULE:
8369         assert(!RA.isMaxValue() && "Should have been caught earlier!");
8370         Pred = ICmpInst::ICMP_ULT;
8371         RHS = getConstant(RA + 1);
8372         Changed = true;
8373         break;
8374       case ICmpInst::ICMP_SGE:
8375         assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
8376         Pred = ICmpInst::ICMP_SGT;
8377         RHS = getConstant(RA - 1);
8378         Changed = true;
8379         break;
8380       case ICmpInst::ICMP_SLE:
8381         assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
8382         Pred = ICmpInst::ICMP_SLT;
8383         RHS = getConstant(RA + 1);
8384         Changed = true;
8385         break;
8386       }
8387     }
8388   }
8389 
8390   // Check for obvious equality.
8391   if (HasSameValue(LHS, RHS)) {
8392     if (ICmpInst::isTrueWhenEqual(Pred))
8393       goto trivially_true;
8394     if (ICmpInst::isFalseWhenEqual(Pred))
8395       goto trivially_false;
8396   }
8397 
8398   // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
8399   // adding or subtracting 1 from one of the operands.
8400   switch (Pred) {
8401   case ICmpInst::ICMP_SLE:
8402     if (!getSignedRangeMax(RHS).isMaxSignedValue()) {
8403       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
8404                        SCEV::FlagNSW);
8405       Pred = ICmpInst::ICMP_SLT;
8406       Changed = true;
8407     } else if (!getSignedRangeMin(LHS).isMinSignedValue()) {
8408       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
8409                        SCEV::FlagNSW);
8410       Pred = ICmpInst::ICMP_SLT;
8411       Changed = true;
8412     }
8413     break;
8414   case ICmpInst::ICMP_SGE:
8415     if (!getSignedRangeMin(RHS).isMinSignedValue()) {
8416       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
8417                        SCEV::FlagNSW);
8418       Pred = ICmpInst::ICMP_SGT;
8419       Changed = true;
8420     } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) {
8421       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
8422                        SCEV::FlagNSW);
8423       Pred = ICmpInst::ICMP_SGT;
8424       Changed = true;
8425     }
8426     break;
8427   case ICmpInst::ICMP_ULE:
8428     if (!getUnsignedRangeMax(RHS).isMaxValue()) {
8429       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
8430                        SCEV::FlagNUW);
8431       Pred = ICmpInst::ICMP_ULT;
8432       Changed = true;
8433     } else if (!getUnsignedRangeMin(LHS).isMinValue()) {
8434       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
8435       Pred = ICmpInst::ICMP_ULT;
8436       Changed = true;
8437     }
8438     break;
8439   case ICmpInst::ICMP_UGE:
8440     if (!getUnsignedRangeMin(RHS).isMinValue()) {
8441       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
8442       Pred = ICmpInst::ICMP_UGT;
8443       Changed = true;
8444     } else if (!getUnsignedRangeMax(LHS).isMaxValue()) {
8445       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
8446                        SCEV::FlagNUW);
8447       Pred = ICmpInst::ICMP_UGT;
8448       Changed = true;
8449     }
8450     break;
8451   default:
8452     break;
8453   }
8454 
8455   // TODO: More simplifications are possible here.
8456 
8457   // Recursively simplify until we either hit a recursion limit or nothing
8458   // changes.
8459   if (Changed)
8460     return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
8461 
8462   return Changed;
8463 
8464 trivially_true:
8465   // Return 0 == 0.
8466   LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
8467   Pred = ICmpInst::ICMP_EQ;
8468   return true;
8469 
8470 trivially_false:
8471   // Return 0 != 0.
8472   LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
8473   Pred = ICmpInst::ICMP_NE;
8474   return true;
8475 }
8476 
8477 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
8478   return getSignedRangeMax(S).isNegative();
8479 }
8480 
8481 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
8482   return getSignedRangeMin(S).isStrictlyPositive();
8483 }
8484 
8485 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
8486   return !getSignedRangeMin(S).isNegative();
8487 }
8488 
8489 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
8490   return !getSignedRangeMax(S).isStrictlyPositive();
8491 }
8492 
8493 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
8494   return isKnownNegative(S) || isKnownPositive(S);
8495 }
8496 
8497 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
8498                                        const SCEV *LHS, const SCEV *RHS) {
8499   // Canonicalize the inputs first.
8500   (void)SimplifyICmpOperands(Pred, LHS, RHS);
8501 
8502   // If LHS or RHS is an addrec, check to see if the condition is true in
8503   // every iteration of the loop.
8504   // If LHS and RHS are both addrec, both conditions must be true in
8505   // every iteration of the loop.
8506   const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
8507   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
8508   bool LeftGuarded = false;
8509   bool RightGuarded = false;
8510   if (LAR) {
8511     const Loop *L = LAR->getLoop();
8512     if (isLoopEntryGuardedByCond(L, Pred, LAR->getStart(), RHS) &&
8513         isLoopBackedgeGuardedByCond(L, Pred, LAR->getPostIncExpr(*this), RHS)) {
8514       if (!RAR) return true;
8515       LeftGuarded = true;
8516     }
8517   }
8518   if (RAR) {
8519     const Loop *L = RAR->getLoop();
8520     if (isLoopEntryGuardedByCond(L, Pred, LHS, RAR->getStart()) &&
8521         isLoopBackedgeGuardedByCond(L, Pred, LHS, RAR->getPostIncExpr(*this))) {
8522       if (!LAR) return true;
8523       RightGuarded = true;
8524     }
8525   }
8526   if (LeftGuarded && RightGuarded)
8527     return true;
8528 
8529   if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
8530     return true;
8531 
8532   // Otherwise see what can be done with known constant ranges.
8533   return isKnownPredicateViaConstantRanges(Pred, LHS, RHS);
8534 }
8535 
8536 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS,
8537                                            ICmpInst::Predicate Pred,
8538                                            bool &Increasing) {
8539   bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing);
8540 
8541 #ifndef NDEBUG
8542   // Verify an invariant: inverting the predicate should turn a monotonically
8543   // increasing change to a monotonically decreasing one, and vice versa.
8544   bool IncreasingSwapped;
8545   bool ResultSwapped = isMonotonicPredicateImpl(
8546       LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped);
8547 
8548   assert(Result == ResultSwapped && "should be able to analyze both!");
8549   if (ResultSwapped)
8550     assert(Increasing == !IncreasingSwapped &&
8551            "monotonicity should flip as we flip the predicate");
8552 #endif
8553 
8554   return Result;
8555 }
8556 
8557 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS,
8558                                                ICmpInst::Predicate Pred,
8559                                                bool &Increasing) {
8560 
8561   // A zero step value for LHS means the induction variable is essentially a
8562   // loop invariant value. We don't really depend on the predicate actually
8563   // flipping from false to true (for increasing predicates, and the other way
8564   // around for decreasing predicates), all we care about is that *if* the
8565   // predicate changes then it only changes from false to true.
8566   //
8567   // A zero step value in itself is not very useful, but there may be places
8568   // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
8569   // as general as possible.
8570 
8571   switch (Pred) {
8572   default:
8573     return false; // Conservative answer
8574 
8575   case ICmpInst::ICMP_UGT:
8576   case ICmpInst::ICMP_UGE:
8577   case ICmpInst::ICMP_ULT:
8578   case ICmpInst::ICMP_ULE:
8579     if (!LHS->hasNoUnsignedWrap())
8580       return false;
8581 
8582     Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE;
8583     return true;
8584 
8585   case ICmpInst::ICMP_SGT:
8586   case ICmpInst::ICMP_SGE:
8587   case ICmpInst::ICMP_SLT:
8588   case ICmpInst::ICMP_SLE: {
8589     if (!LHS->hasNoSignedWrap())
8590       return false;
8591 
8592     const SCEV *Step = LHS->getStepRecurrence(*this);
8593 
8594     if (isKnownNonNegative(Step)) {
8595       Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE;
8596       return true;
8597     }
8598 
8599     if (isKnownNonPositive(Step)) {
8600       Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE;
8601       return true;
8602     }
8603 
8604     return false;
8605   }
8606 
8607   }
8608 
8609   llvm_unreachable("switch has default clause!");
8610 }
8611 
8612 bool ScalarEvolution::isLoopInvariantPredicate(
8613     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
8614     ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS,
8615     const SCEV *&InvariantRHS) {
8616 
8617   // If there is a loop-invariant, force it into the RHS, otherwise bail out.
8618   if (!isLoopInvariant(RHS, L)) {
8619     if (!isLoopInvariant(LHS, L))
8620       return false;
8621 
8622     std::swap(LHS, RHS);
8623     Pred = ICmpInst::getSwappedPredicate(Pred);
8624   }
8625 
8626   const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
8627   if (!ArLHS || ArLHS->getLoop() != L)
8628     return false;
8629 
8630   bool Increasing;
8631   if (!isMonotonicPredicate(ArLHS, Pred, Increasing))
8632     return false;
8633 
8634   // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
8635   // true as the loop iterates, and the backedge is control dependent on
8636   // "ArLHS `Pred` RHS" == true then we can reason as follows:
8637   //
8638   //   * if the predicate was false in the first iteration then the predicate
8639   //     is never evaluated again, since the loop exits without taking the
8640   //     backedge.
8641   //   * if the predicate was true in the first iteration then it will
8642   //     continue to be true for all future iterations since it is
8643   //     monotonically increasing.
8644   //
8645   // For both the above possibilities, we can replace the loop varying
8646   // predicate with its value on the first iteration of the loop (which is
8647   // loop invariant).
8648   //
8649   // A similar reasoning applies for a monotonically decreasing predicate, by
8650   // replacing true with false and false with true in the above two bullets.
8651 
8652   auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
8653 
8654   if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
8655     return false;
8656 
8657   InvariantPred = Pred;
8658   InvariantLHS = ArLHS->getStart();
8659   InvariantRHS = RHS;
8660   return true;
8661 }
8662 
8663 bool ScalarEvolution::isKnownPredicateViaConstantRanges(
8664     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
8665   if (HasSameValue(LHS, RHS))
8666     return ICmpInst::isTrueWhenEqual(Pred);
8667 
8668   // This code is split out from isKnownPredicate because it is called from
8669   // within isLoopEntryGuardedByCond.
8670 
8671   auto CheckRanges =
8672       [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) {
8673     return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS)
8674         .contains(RangeLHS);
8675   };
8676 
8677   // The check at the top of the function catches the case where the values are
8678   // known to be equal.
8679   if (Pred == CmpInst::ICMP_EQ)
8680     return false;
8681 
8682   if (Pred == CmpInst::ICMP_NE)
8683     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) ||
8684            CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) ||
8685            isKnownNonZero(getMinusSCEV(LHS, RHS));
8686 
8687   if (CmpInst::isSigned(Pred))
8688     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS));
8689 
8690   return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS));
8691 }
8692 
8693 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
8694                                                     const SCEV *LHS,
8695                                                     const SCEV *RHS) {
8696   // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer.
8697   // Return Y via OutY.
8698   auto MatchBinaryAddToConst =
8699       [this](const SCEV *Result, const SCEV *X, APInt &OutY,
8700              SCEV::NoWrapFlags ExpectedFlags) {
8701     const SCEV *NonConstOp, *ConstOp;
8702     SCEV::NoWrapFlags FlagsPresent;
8703 
8704     if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) ||
8705         !isa<SCEVConstant>(ConstOp) || NonConstOp != X)
8706       return false;
8707 
8708     OutY = cast<SCEVConstant>(ConstOp)->getAPInt();
8709     return (FlagsPresent & ExpectedFlags) == ExpectedFlags;
8710   };
8711 
8712   APInt C;
8713 
8714   switch (Pred) {
8715   default:
8716     break;
8717 
8718   case ICmpInst::ICMP_SGE:
8719     std::swap(LHS, RHS);
8720     LLVM_FALLTHROUGH;
8721   case ICmpInst::ICMP_SLE:
8722     // X s<= (X + C)<nsw> if C >= 0
8723     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative())
8724       return true;
8725 
8726     // (X + C)<nsw> s<= X if C <= 0
8727     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) &&
8728         !C.isStrictlyPositive())
8729       return true;
8730     break;
8731 
8732   case ICmpInst::ICMP_SGT:
8733     std::swap(LHS, RHS);
8734     LLVM_FALLTHROUGH;
8735   case ICmpInst::ICMP_SLT:
8736     // X s< (X + C)<nsw> if C > 0
8737     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) &&
8738         C.isStrictlyPositive())
8739       return true;
8740 
8741     // (X + C)<nsw> s< X if C < 0
8742     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative())
8743       return true;
8744     break;
8745   }
8746 
8747   return false;
8748 }
8749 
8750 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
8751                                                    const SCEV *LHS,
8752                                                    const SCEV *RHS) {
8753   if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
8754     return false;
8755 
8756   // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
8757   // the stack can result in exponential time complexity.
8758   SaveAndRestore<bool> Restore(ProvingSplitPredicate, true);
8759 
8760   // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
8761   //
8762   // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
8763   // isKnownPredicate.  isKnownPredicate is more powerful, but also more
8764   // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
8765   // interesting cases seen in practice.  We can consider "upgrading" L >= 0 to
8766   // use isKnownPredicate later if needed.
8767   return isKnownNonNegative(RHS) &&
8768          isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
8769          isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
8770 }
8771 
8772 bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB,
8773                                         ICmpInst::Predicate Pred,
8774                                         const SCEV *LHS, const SCEV *RHS) {
8775   // No need to even try if we know the module has no guards.
8776   if (!HasGuards)
8777     return false;
8778 
8779   return any_of(*BB, [&](Instruction &I) {
8780     using namespace llvm::PatternMatch;
8781 
8782     Value *Condition;
8783     return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
8784                          m_Value(Condition))) &&
8785            isImpliedCond(Pred, LHS, RHS, Condition, false);
8786   });
8787 }
8788 
8789 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
8790 /// protected by a conditional between LHS and RHS.  This is used to
8791 /// to eliminate casts.
8792 bool
8793 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
8794                                              ICmpInst::Predicate Pred,
8795                                              const SCEV *LHS, const SCEV *RHS) {
8796   // Interpret a null as meaning no loop, where there is obviously no guard
8797   // (interprocedural conditions notwithstanding).
8798   if (!L) return true;
8799 
8800   if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS))
8801     return true;
8802 
8803   BasicBlock *Latch = L->getLoopLatch();
8804   if (!Latch)
8805     return false;
8806 
8807   BranchInst *LoopContinuePredicate =
8808     dyn_cast<BranchInst>(Latch->getTerminator());
8809   if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
8810       isImpliedCond(Pred, LHS, RHS,
8811                     LoopContinuePredicate->getCondition(),
8812                     LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
8813     return true;
8814 
8815   // We don't want more than one activation of the following loops on the stack
8816   // -- that can lead to O(n!) time complexity.
8817   if (WalkingBEDominatingConds)
8818     return false;
8819 
8820   SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true);
8821 
8822   // See if we can exploit a trip count to prove the predicate.
8823   const auto &BETakenInfo = getBackedgeTakenInfo(L);
8824   const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
8825   if (LatchBECount != getCouldNotCompute()) {
8826     // We know that Latch branches back to the loop header exactly
8827     // LatchBECount times.  This means the backdege condition at Latch is
8828     // equivalent to  "{0,+,1} u< LatchBECount".
8829     Type *Ty = LatchBECount->getType();
8830     auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
8831     const SCEV *LoopCounter =
8832       getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
8833     if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
8834                       LatchBECount))
8835       return true;
8836   }
8837 
8838   // Check conditions due to any @llvm.assume intrinsics.
8839   for (auto &AssumeVH : AC.assumptions()) {
8840     if (!AssumeVH)
8841       continue;
8842     auto *CI = cast<CallInst>(AssumeVH);
8843     if (!DT.dominates(CI, Latch->getTerminator()))
8844       continue;
8845 
8846     if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
8847       return true;
8848   }
8849 
8850   // If the loop is not reachable from the entry block, we risk running into an
8851   // infinite loop as we walk up into the dom tree.  These loops do not matter
8852   // anyway, so we just return a conservative answer when we see them.
8853   if (!DT.isReachableFromEntry(L->getHeader()))
8854     return false;
8855 
8856   if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
8857     return true;
8858 
8859   for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
8860        DTN != HeaderDTN; DTN = DTN->getIDom()) {
8861     assert(DTN && "should reach the loop header before reaching the root!");
8862 
8863     BasicBlock *BB = DTN->getBlock();
8864     if (isImpliedViaGuard(BB, Pred, LHS, RHS))
8865       return true;
8866 
8867     BasicBlock *PBB = BB->getSinglePredecessor();
8868     if (!PBB)
8869       continue;
8870 
8871     BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
8872     if (!ContinuePredicate || !ContinuePredicate->isConditional())
8873       continue;
8874 
8875     Value *Condition = ContinuePredicate->getCondition();
8876 
8877     // If we have an edge `E` within the loop body that dominates the only
8878     // latch, the condition guarding `E` also guards the backedge.  This
8879     // reasoning works only for loops with a single latch.
8880 
8881     BasicBlockEdge DominatingEdge(PBB, BB);
8882     if (DominatingEdge.isSingleEdge()) {
8883       // We're constructively (and conservatively) enumerating edges within the
8884       // loop body that dominate the latch.  The dominator tree better agree
8885       // with us on this:
8886       assert(DT.dominates(DominatingEdge, Latch) && "should be!");
8887 
8888       if (isImpliedCond(Pred, LHS, RHS, Condition,
8889                         BB != ContinuePredicate->getSuccessor(0)))
8890         return true;
8891     }
8892   }
8893 
8894   return false;
8895 }
8896 
8897 bool
8898 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
8899                                           ICmpInst::Predicate Pred,
8900                                           const SCEV *LHS, const SCEV *RHS) {
8901   // Interpret a null as meaning no loop, where there is obviously no guard
8902   // (interprocedural conditions notwithstanding).
8903   if (!L) return false;
8904 
8905   if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS))
8906     return true;
8907 
8908   // Starting at the loop predecessor, climb up the predecessor chain, as long
8909   // as there are predecessors that can be found that have unique successors
8910   // leading to the original header.
8911   for (std::pair<BasicBlock *, BasicBlock *>
8912          Pair(L->getLoopPredecessor(), L->getHeader());
8913        Pair.first;
8914        Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
8915 
8916     if (isImpliedViaGuard(Pair.first, Pred, LHS, RHS))
8917       return true;
8918 
8919     BranchInst *LoopEntryPredicate =
8920       dyn_cast<BranchInst>(Pair.first->getTerminator());
8921     if (!LoopEntryPredicate ||
8922         LoopEntryPredicate->isUnconditional())
8923       continue;
8924 
8925     if (isImpliedCond(Pred, LHS, RHS,
8926                       LoopEntryPredicate->getCondition(),
8927                       LoopEntryPredicate->getSuccessor(0) != Pair.second))
8928       return true;
8929   }
8930 
8931   // Check conditions due to any @llvm.assume intrinsics.
8932   for (auto &AssumeVH : AC.assumptions()) {
8933     if (!AssumeVH)
8934       continue;
8935     auto *CI = cast<CallInst>(AssumeVH);
8936     if (!DT.dominates(CI, L->getHeader()))
8937       continue;
8938 
8939     if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
8940       return true;
8941   }
8942 
8943   return false;
8944 }
8945 
8946 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
8947                                     const SCEV *LHS, const SCEV *RHS,
8948                                     Value *FoundCondValue,
8949                                     bool Inverse) {
8950   if (!PendingLoopPredicates.insert(FoundCondValue).second)
8951     return false;
8952 
8953   auto ClearOnExit =
8954       make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
8955 
8956   // Recursively handle And and Or conditions.
8957   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
8958     if (BO->getOpcode() == Instruction::And) {
8959       if (!Inverse)
8960         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
8961                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
8962     } else if (BO->getOpcode() == Instruction::Or) {
8963       if (Inverse)
8964         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
8965                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
8966     }
8967   }
8968 
8969   ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
8970   if (!ICI) return false;
8971 
8972   // Now that we found a conditional branch that dominates the loop or controls
8973   // the loop latch. Check to see if it is the comparison we are looking for.
8974   ICmpInst::Predicate FoundPred;
8975   if (Inverse)
8976     FoundPred = ICI->getInversePredicate();
8977   else
8978     FoundPred = ICI->getPredicate();
8979 
8980   const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
8981   const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
8982 
8983   return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS);
8984 }
8985 
8986 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
8987                                     const SCEV *RHS,
8988                                     ICmpInst::Predicate FoundPred,
8989                                     const SCEV *FoundLHS,
8990                                     const SCEV *FoundRHS) {
8991   // Balance the types.
8992   if (getTypeSizeInBits(LHS->getType()) <
8993       getTypeSizeInBits(FoundLHS->getType())) {
8994     if (CmpInst::isSigned(Pred)) {
8995       LHS = getSignExtendExpr(LHS, FoundLHS->getType());
8996       RHS = getSignExtendExpr(RHS, FoundLHS->getType());
8997     } else {
8998       LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
8999       RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
9000     }
9001   } else if (getTypeSizeInBits(LHS->getType()) >
9002       getTypeSizeInBits(FoundLHS->getType())) {
9003     if (CmpInst::isSigned(FoundPred)) {
9004       FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
9005       FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
9006     } else {
9007       FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
9008       FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
9009     }
9010   }
9011 
9012   // Canonicalize the query to match the way instcombine will have
9013   // canonicalized the comparison.
9014   if (SimplifyICmpOperands(Pred, LHS, RHS))
9015     if (LHS == RHS)
9016       return CmpInst::isTrueWhenEqual(Pred);
9017   if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
9018     if (FoundLHS == FoundRHS)
9019       return CmpInst::isFalseWhenEqual(FoundPred);
9020 
9021   // Check to see if we can make the LHS or RHS match.
9022   if (LHS == FoundRHS || RHS == FoundLHS) {
9023     if (isa<SCEVConstant>(RHS)) {
9024       std::swap(FoundLHS, FoundRHS);
9025       FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
9026     } else {
9027       std::swap(LHS, RHS);
9028       Pred = ICmpInst::getSwappedPredicate(Pred);
9029     }
9030   }
9031 
9032   // Check whether the found predicate is the same as the desired predicate.
9033   if (FoundPred == Pred)
9034     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
9035 
9036   // Check whether swapping the found predicate makes it the same as the
9037   // desired predicate.
9038   if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
9039     if (isa<SCEVConstant>(RHS))
9040       return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
9041     else
9042       return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
9043                                    RHS, LHS, FoundLHS, FoundRHS);
9044   }
9045 
9046   // Unsigned comparison is the same as signed comparison when both the operands
9047   // are non-negative.
9048   if (CmpInst::isUnsigned(FoundPred) &&
9049       CmpInst::getSignedPredicate(FoundPred) == Pred &&
9050       isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS))
9051     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
9052 
9053   // Check if we can make progress by sharpening ranges.
9054   if (FoundPred == ICmpInst::ICMP_NE &&
9055       (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
9056 
9057     const SCEVConstant *C = nullptr;
9058     const SCEV *V = nullptr;
9059 
9060     if (isa<SCEVConstant>(FoundLHS)) {
9061       C = cast<SCEVConstant>(FoundLHS);
9062       V = FoundRHS;
9063     } else {
9064       C = cast<SCEVConstant>(FoundRHS);
9065       V = FoundLHS;
9066     }
9067 
9068     // The guarding predicate tells us that C != V. If the known range
9069     // of V is [C, t), we can sharpen the range to [C + 1, t).  The
9070     // range we consider has to correspond to same signedness as the
9071     // predicate we're interested in folding.
9072 
9073     APInt Min = ICmpInst::isSigned(Pred) ?
9074         getSignedRangeMin(V) : getUnsignedRangeMin(V);
9075 
9076     if (Min == C->getAPInt()) {
9077       // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
9078       // This is true even if (Min + 1) wraps around -- in case of
9079       // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
9080 
9081       APInt SharperMin = Min + 1;
9082 
9083       switch (Pred) {
9084         case ICmpInst::ICMP_SGE:
9085         case ICmpInst::ICMP_UGE:
9086           // We know V `Pred` SharperMin.  If this implies LHS `Pred`
9087           // RHS, we're done.
9088           if (isImpliedCondOperands(Pred, LHS, RHS, V,
9089                                     getConstant(SharperMin)))
9090             return true;
9091           LLVM_FALLTHROUGH;
9092 
9093         case ICmpInst::ICMP_SGT:
9094         case ICmpInst::ICMP_UGT:
9095           // We know from the range information that (V `Pred` Min ||
9096           // V == Min).  We know from the guarding condition that !(V
9097           // == Min).  This gives us
9098           //
9099           //       V `Pred` Min || V == Min && !(V == Min)
9100           //   =>  V `Pred` Min
9101           //
9102           // If V `Pred` Min implies LHS `Pred` RHS, we're done.
9103 
9104           if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min)))
9105             return true;
9106           LLVM_FALLTHROUGH;
9107 
9108         default:
9109           // No change
9110           break;
9111       }
9112     }
9113   }
9114 
9115   // Check whether the actual condition is beyond sufficient.
9116   if (FoundPred == ICmpInst::ICMP_EQ)
9117     if (ICmpInst::isTrueWhenEqual(Pred))
9118       if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
9119         return true;
9120   if (Pred == ICmpInst::ICMP_NE)
9121     if (!ICmpInst::isTrueWhenEqual(FoundPred))
9122       if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
9123         return true;
9124 
9125   // Otherwise assume the worst.
9126   return false;
9127 }
9128 
9129 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
9130                                      const SCEV *&L, const SCEV *&R,
9131                                      SCEV::NoWrapFlags &Flags) {
9132   const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
9133   if (!AE || AE->getNumOperands() != 2)
9134     return false;
9135 
9136   L = AE->getOperand(0);
9137   R = AE->getOperand(1);
9138   Flags = AE->getNoWrapFlags();
9139   return true;
9140 }
9141 
9142 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More,
9143                                                            const SCEV *Less) {
9144   // We avoid subtracting expressions here because this function is usually
9145   // fairly deep in the call stack (i.e. is called many times).
9146 
9147   if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
9148     const auto *LAR = cast<SCEVAddRecExpr>(Less);
9149     const auto *MAR = cast<SCEVAddRecExpr>(More);
9150 
9151     if (LAR->getLoop() != MAR->getLoop())
9152       return None;
9153 
9154     // We look at affine expressions only; not for correctness but to keep
9155     // getStepRecurrence cheap.
9156     if (!LAR->isAffine() || !MAR->isAffine())
9157       return None;
9158 
9159     if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
9160       return None;
9161 
9162     Less = LAR->getStart();
9163     More = MAR->getStart();
9164 
9165     // fall through
9166   }
9167 
9168   if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
9169     const auto &M = cast<SCEVConstant>(More)->getAPInt();
9170     const auto &L = cast<SCEVConstant>(Less)->getAPInt();
9171     return M - L;
9172   }
9173 
9174   const SCEV *L, *R;
9175   SCEV::NoWrapFlags Flags;
9176   if (splitBinaryAdd(Less, L, R, Flags))
9177     if (const auto *LC = dyn_cast<SCEVConstant>(L))
9178       if (R == More)
9179         return -(LC->getAPInt());
9180 
9181   if (splitBinaryAdd(More, L, R, Flags))
9182     if (const auto *LC = dyn_cast<SCEVConstant>(L))
9183       if (R == Less)
9184         return LC->getAPInt();
9185 
9186   return None;
9187 }
9188 
9189 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
9190     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
9191     const SCEV *FoundLHS, const SCEV *FoundRHS) {
9192   if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
9193     return false;
9194 
9195   const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
9196   if (!AddRecLHS)
9197     return false;
9198 
9199   const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
9200   if (!AddRecFoundLHS)
9201     return false;
9202 
9203   // We'd like to let SCEV reason about control dependencies, so we constrain
9204   // both the inequalities to be about add recurrences on the same loop.  This
9205   // way we can use isLoopEntryGuardedByCond later.
9206 
9207   const Loop *L = AddRecFoundLHS->getLoop();
9208   if (L != AddRecLHS->getLoop())
9209     return false;
9210 
9211   //  FoundLHS u< FoundRHS u< -C =>  (FoundLHS + C) u< (FoundRHS + C) ... (1)
9212   //
9213   //  FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
9214   //                                                                  ... (2)
9215   //
9216   // Informal proof for (2), assuming (1) [*]:
9217   //
9218   // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
9219   //
9220   // Then
9221   //
9222   //       FoundLHS s< FoundRHS s< INT_MIN - C
9223   // <=>  (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C   [ using (3) ]
9224   // <=>  (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
9225   // <=>  (FoundLHS + INT_MIN + C + INT_MIN) s<
9226   //                        (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
9227   // <=>  FoundLHS + C s< FoundRHS + C
9228   //
9229   // [*]: (1) can be proved by ruling out overflow.
9230   //
9231   // [**]: This can be proved by analyzing all the four possibilities:
9232   //    (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
9233   //    (A s>= 0, B s>= 0).
9234   //
9235   // Note:
9236   // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
9237   // will not sign underflow.  For instance, say FoundLHS = (i8 -128), FoundRHS
9238   // = (i8 -127) and C = (i8 -100).  Then INT_MIN - C = (i8 -28), and FoundRHS
9239   // s< (INT_MIN - C).  Lack of sign overflow / underflow in "FoundRHS + C" is
9240   // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
9241   // C)".
9242 
9243   Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
9244   Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
9245   if (!LDiff || !RDiff || *LDiff != *RDiff)
9246     return false;
9247 
9248   if (LDiff->isMinValue())
9249     return true;
9250 
9251   APInt FoundRHSLimit;
9252 
9253   if (Pred == CmpInst::ICMP_ULT) {
9254     FoundRHSLimit = -(*RDiff);
9255   } else {
9256     assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
9257     FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
9258   }
9259 
9260   // Try to prove (1) or (2), as needed.
9261   return isLoopEntryGuardedByCond(L, Pred, FoundRHS,
9262                                   getConstant(FoundRHSLimit));
9263 }
9264 
9265 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
9266                                             const SCEV *LHS, const SCEV *RHS,
9267                                             const SCEV *FoundLHS,
9268                                             const SCEV *FoundRHS) {
9269   if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
9270     return true;
9271 
9272   if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
9273     return true;
9274 
9275   return isImpliedCondOperandsHelper(Pred, LHS, RHS,
9276                                      FoundLHS, FoundRHS) ||
9277          // ~x < ~y --> x > y
9278          isImpliedCondOperandsHelper(Pred, LHS, RHS,
9279                                      getNotSCEV(FoundRHS),
9280                                      getNotSCEV(FoundLHS));
9281 }
9282 
9283 /// If Expr computes ~A, return A else return nullptr
9284 static const SCEV *MatchNotExpr(const SCEV *Expr) {
9285   const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
9286   if (!Add || Add->getNumOperands() != 2 ||
9287       !Add->getOperand(0)->isAllOnesValue())
9288     return nullptr;
9289 
9290   const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
9291   if (!AddRHS || AddRHS->getNumOperands() != 2 ||
9292       !AddRHS->getOperand(0)->isAllOnesValue())
9293     return nullptr;
9294 
9295   return AddRHS->getOperand(1);
9296 }
9297 
9298 /// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values?
9299 template<typename MaxExprType>
9300 static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr,
9301                               const SCEV *Candidate) {
9302   const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr);
9303   if (!MaxExpr) return false;
9304 
9305   return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end();
9306 }
9307 
9308 /// Is MaybeMinExpr an SMin or UMin of Candidate and some other values?
9309 template<typename MaxExprType>
9310 static bool IsMinConsistingOf(ScalarEvolution &SE,
9311                               const SCEV *MaybeMinExpr,
9312                               const SCEV *Candidate) {
9313   const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr);
9314   if (!MaybeMaxExpr)
9315     return false;
9316 
9317   return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate));
9318 }
9319 
9320 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
9321                                            ICmpInst::Predicate Pred,
9322                                            const SCEV *LHS, const SCEV *RHS) {
9323   // If both sides are affine addrecs for the same loop, with equal
9324   // steps, and we know the recurrences don't wrap, then we only
9325   // need to check the predicate on the starting values.
9326 
9327   if (!ICmpInst::isRelational(Pred))
9328     return false;
9329 
9330   const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
9331   if (!LAR)
9332     return false;
9333   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
9334   if (!RAR)
9335     return false;
9336   if (LAR->getLoop() != RAR->getLoop())
9337     return false;
9338   if (!LAR->isAffine() || !RAR->isAffine())
9339     return false;
9340 
9341   if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
9342     return false;
9343 
9344   SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
9345                          SCEV::FlagNSW : SCEV::FlagNUW;
9346   if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
9347     return false;
9348 
9349   return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
9350 }
9351 
9352 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
9353 /// expression?
9354 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
9355                                         ICmpInst::Predicate Pred,
9356                                         const SCEV *LHS, const SCEV *RHS) {
9357   switch (Pred) {
9358   default:
9359     return false;
9360 
9361   case ICmpInst::ICMP_SGE:
9362     std::swap(LHS, RHS);
9363     LLVM_FALLTHROUGH;
9364   case ICmpInst::ICMP_SLE:
9365     return
9366       // min(A, ...) <= A
9367       IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) ||
9368       // A <= max(A, ...)
9369       IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
9370 
9371   case ICmpInst::ICMP_UGE:
9372     std::swap(LHS, RHS);
9373     LLVM_FALLTHROUGH;
9374   case ICmpInst::ICMP_ULE:
9375     return
9376       // min(A, ...) <= A
9377       IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) ||
9378       // A <= max(A, ...)
9379       IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
9380   }
9381 
9382   llvm_unreachable("covered switch fell through?!");
9383 }
9384 
9385 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred,
9386                                              const SCEV *LHS, const SCEV *RHS,
9387                                              const SCEV *FoundLHS,
9388                                              const SCEV *FoundRHS,
9389                                              unsigned Depth) {
9390   assert(getTypeSizeInBits(LHS->getType()) ==
9391              getTypeSizeInBits(RHS->getType()) &&
9392          "LHS and RHS have different sizes?");
9393   assert(getTypeSizeInBits(FoundLHS->getType()) ==
9394              getTypeSizeInBits(FoundRHS->getType()) &&
9395          "FoundLHS and FoundRHS have different sizes?");
9396   // We want to avoid hurting the compile time with analysis of too big trees.
9397   if (Depth > MaxSCEVOperationsImplicationDepth)
9398     return false;
9399   // We only want to work with ICMP_SGT comparison so far.
9400   // TODO: Extend to ICMP_UGT?
9401   if (Pred == ICmpInst::ICMP_SLT) {
9402     Pred = ICmpInst::ICMP_SGT;
9403     std::swap(LHS, RHS);
9404     std::swap(FoundLHS, FoundRHS);
9405   }
9406   if (Pred != ICmpInst::ICMP_SGT)
9407     return false;
9408 
9409   auto GetOpFromSExt = [&](const SCEV *S) {
9410     if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
9411       return Ext->getOperand();
9412     // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
9413     // the constant in some cases.
9414     return S;
9415   };
9416 
9417   // Acquire values from extensions.
9418   auto *OrigFoundLHS = FoundLHS;
9419   LHS = GetOpFromSExt(LHS);
9420   FoundLHS = GetOpFromSExt(FoundLHS);
9421 
9422   // Is the SGT predicate can be proved trivially or using the found context.
9423   auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
9424     return isKnownViaSimpleReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
9425            isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
9426                                   FoundRHS, Depth + 1);
9427   };
9428 
9429   if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
9430     // We want to avoid creation of any new non-constant SCEV. Since we are
9431     // going to compare the operands to RHS, we should be certain that we don't
9432     // need any size extensions for this. So let's decline all cases when the
9433     // sizes of types of LHS and RHS do not match.
9434     // TODO: Maybe try to get RHS from sext to catch more cases?
9435     if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType()))
9436       return false;
9437 
9438     // Should not overflow.
9439     if (!LHSAddExpr->hasNoSignedWrap())
9440       return false;
9441 
9442     auto *LL = LHSAddExpr->getOperand(0);
9443     auto *LR = LHSAddExpr->getOperand(1);
9444     auto *MinusOne = getNegativeSCEV(getOne(RHS->getType()));
9445 
9446     // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
9447     auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
9448       return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
9449     };
9450     // Try to prove the following rule:
9451     // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
9452     // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
9453     if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
9454       return true;
9455   } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
9456     Value *LL, *LR;
9457     // FIXME: Once we have SDiv implemented, we can get rid of this matching.
9458 
9459     using namespace llvm::PatternMatch;
9460 
9461     if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
9462       // Rules for division.
9463       // We are going to perform some comparisons with Denominator and its
9464       // derivative expressions. In general case, creating a SCEV for it may
9465       // lead to a complex analysis of the entire graph, and in particular it
9466       // can request trip count recalculation for the same loop. This would
9467       // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
9468       // this, we only want to create SCEVs that are constants in this section.
9469       // So we bail if Denominator is not a constant.
9470       if (!isa<ConstantInt>(LR))
9471         return false;
9472 
9473       auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
9474 
9475       // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
9476       // then a SCEV for the numerator already exists and matches with FoundLHS.
9477       auto *Numerator = getExistingSCEV(LL);
9478       if (!Numerator || Numerator->getType() != FoundLHS->getType())
9479         return false;
9480 
9481       // Make sure that the numerator matches with FoundLHS and the denominator
9482       // is positive.
9483       if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
9484         return false;
9485 
9486       auto *DTy = Denominator->getType();
9487       auto *FRHSTy = FoundRHS->getType();
9488       if (DTy->isPointerTy() != FRHSTy->isPointerTy())
9489         // One of types is a pointer and another one is not. We cannot extend
9490         // them properly to a wider type, so let us just reject this case.
9491         // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
9492         // to avoid this check.
9493         return false;
9494 
9495       // Given that:
9496       // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
9497       auto *WTy = getWiderType(DTy, FRHSTy);
9498       auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
9499       auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
9500 
9501       // Try to prove the following rule:
9502       // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
9503       // For example, given that FoundLHS > 2. It means that FoundLHS is at
9504       // least 3. If we divide it by Denominator < 4, we will have at least 1.
9505       auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
9506       if (isKnownNonPositive(RHS) &&
9507           IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
9508         return true;
9509 
9510       // Try to prove the following rule:
9511       // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
9512       // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
9513       // If we divide it by Denominator > 2, then:
9514       // 1. If FoundLHS is negative, then the result is 0.
9515       // 2. If FoundLHS is non-negative, then the result is non-negative.
9516       // Anyways, the result is non-negative.
9517       auto *MinusOne = getNegativeSCEV(getOne(WTy));
9518       auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
9519       if (isKnownNegative(RHS) &&
9520           IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
9521         return true;
9522     }
9523   }
9524 
9525   return false;
9526 }
9527 
9528 bool
9529 ScalarEvolution::isKnownViaSimpleReasoning(ICmpInst::Predicate Pred,
9530                                            const SCEV *LHS, const SCEV *RHS) {
9531   return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
9532          IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
9533          IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
9534          isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
9535 }
9536 
9537 bool
9538 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
9539                                              const SCEV *LHS, const SCEV *RHS,
9540                                              const SCEV *FoundLHS,
9541                                              const SCEV *FoundRHS) {
9542   switch (Pred) {
9543   default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
9544   case ICmpInst::ICMP_EQ:
9545   case ICmpInst::ICMP_NE:
9546     if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
9547       return true;
9548     break;
9549   case ICmpInst::ICMP_SLT:
9550   case ICmpInst::ICMP_SLE:
9551     if (isKnownViaSimpleReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
9552         isKnownViaSimpleReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS))
9553       return true;
9554     break;
9555   case ICmpInst::ICMP_SGT:
9556   case ICmpInst::ICMP_SGE:
9557     if (isKnownViaSimpleReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
9558         isKnownViaSimpleReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS))
9559       return true;
9560     break;
9561   case ICmpInst::ICMP_ULT:
9562   case ICmpInst::ICMP_ULE:
9563     if (isKnownViaSimpleReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
9564         isKnownViaSimpleReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS))
9565       return true;
9566     break;
9567   case ICmpInst::ICMP_UGT:
9568   case ICmpInst::ICMP_UGE:
9569     if (isKnownViaSimpleReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
9570         isKnownViaSimpleReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS))
9571       return true;
9572     break;
9573   }
9574 
9575   // Maybe it can be proved via operations?
9576   if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
9577     return true;
9578 
9579   return false;
9580 }
9581 
9582 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
9583                                                      const SCEV *LHS,
9584                                                      const SCEV *RHS,
9585                                                      const SCEV *FoundLHS,
9586                                                      const SCEV *FoundRHS) {
9587   if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
9588     // The restriction on `FoundRHS` be lifted easily -- it exists only to
9589     // reduce the compile time impact of this optimization.
9590     return false;
9591 
9592   Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
9593   if (!Addend)
9594     return false;
9595 
9596   const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
9597 
9598   // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
9599   // antecedent "`FoundLHS` `Pred` `FoundRHS`".
9600   ConstantRange FoundLHSRange =
9601       ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS);
9602 
9603   // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
9604   ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
9605 
9606   // We can also compute the range of values for `LHS` that satisfy the
9607   // consequent, "`LHS` `Pred` `RHS`":
9608   const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
9609   ConstantRange SatisfyingLHSRange =
9610       ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS);
9611 
9612   // The antecedent implies the consequent if every value of `LHS` that
9613   // satisfies the antecedent also satisfies the consequent.
9614   return SatisfyingLHSRange.contains(LHSRange);
9615 }
9616 
9617 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
9618                                          bool IsSigned, bool NoWrap) {
9619   assert(isKnownPositive(Stride) && "Positive stride expected!");
9620 
9621   if (NoWrap) return false;
9622 
9623   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
9624   const SCEV *One = getOne(Stride->getType());
9625 
9626   if (IsSigned) {
9627     APInt MaxRHS = getSignedRangeMax(RHS);
9628     APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
9629     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
9630 
9631     // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
9632     return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS);
9633   }
9634 
9635   APInt MaxRHS = getUnsignedRangeMax(RHS);
9636   APInt MaxValue = APInt::getMaxValue(BitWidth);
9637   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
9638 
9639   // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
9640   return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS);
9641 }
9642 
9643 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
9644                                          bool IsSigned, bool NoWrap) {
9645   if (NoWrap) return false;
9646 
9647   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
9648   const SCEV *One = getOne(Stride->getType());
9649 
9650   if (IsSigned) {
9651     APInt MinRHS = getSignedRangeMin(RHS);
9652     APInt MinValue = APInt::getSignedMinValue(BitWidth);
9653     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
9654 
9655     // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
9656     return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS);
9657   }
9658 
9659   APInt MinRHS = getUnsignedRangeMin(RHS);
9660   APInt MinValue = APInt::getMinValue(BitWidth);
9661   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
9662 
9663   // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
9664   return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS);
9665 }
9666 
9667 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step,
9668                                             bool Equality) {
9669   const SCEV *One = getOne(Step->getType());
9670   Delta = Equality ? getAddExpr(Delta, Step)
9671                    : getAddExpr(Delta, getMinusSCEV(Step, One));
9672   return getUDivExpr(Delta, Step);
9673 }
9674 
9675 ScalarEvolution::ExitLimit
9676 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
9677                                   const Loop *L, bool IsSigned,
9678                                   bool ControlsExit, bool AllowPredicates) {
9679   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
9680   // We handle only IV < Invariant
9681   if (!isLoopInvariant(RHS, L))
9682     return getCouldNotCompute();
9683 
9684   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
9685   bool PredicatedIV = false;
9686 
9687   if (!IV && AllowPredicates) {
9688     // Try to make this an AddRec using runtime tests, in the first X
9689     // iterations of this loop, where X is the SCEV expression found by the
9690     // algorithm below.
9691     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
9692     PredicatedIV = true;
9693   }
9694 
9695   // Avoid weird loops
9696   if (!IV || IV->getLoop() != L || !IV->isAffine())
9697     return getCouldNotCompute();
9698 
9699   bool NoWrap = ControlsExit &&
9700                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
9701 
9702   const SCEV *Stride = IV->getStepRecurrence(*this);
9703 
9704   bool PositiveStride = isKnownPositive(Stride);
9705 
9706   // Avoid negative or zero stride values.
9707   if (!PositiveStride) {
9708     // We can compute the correct backedge taken count for loops with unknown
9709     // strides if we can prove that the loop is not an infinite loop with side
9710     // effects. Here's the loop structure we are trying to handle -
9711     //
9712     // i = start
9713     // do {
9714     //   A[i] = i;
9715     //   i += s;
9716     // } while (i < end);
9717     //
9718     // The backedge taken count for such loops is evaluated as -
9719     // (max(end, start + stride) - start - 1) /u stride
9720     //
9721     // The additional preconditions that we need to check to prove correctness
9722     // of the above formula is as follows -
9723     //
9724     // a) IV is either nuw or nsw depending upon signedness (indicated by the
9725     //    NoWrap flag).
9726     // b) loop is single exit with no side effects.
9727     //
9728     //
9729     // Precondition a) implies that if the stride is negative, this is a single
9730     // trip loop. The backedge taken count formula reduces to zero in this case.
9731     //
9732     // Precondition b) implies that the unknown stride cannot be zero otherwise
9733     // we have UB.
9734     //
9735     // The positive stride case is the same as isKnownPositive(Stride) returning
9736     // true (original behavior of the function).
9737     //
9738     // We want to make sure that the stride is truly unknown as there are edge
9739     // cases where ScalarEvolution propagates no wrap flags to the
9740     // post-increment/decrement IV even though the increment/decrement operation
9741     // itself is wrapping. The computed backedge taken count may be wrong in
9742     // such cases. This is prevented by checking that the stride is not known to
9743     // be either positive or non-positive. For example, no wrap flags are
9744     // propagated to the post-increment IV of this loop with a trip count of 2 -
9745     //
9746     // unsigned char i;
9747     // for(i=127; i<128; i+=129)
9748     //   A[i] = i;
9749     //
9750     if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) ||
9751         !loopHasNoSideEffects(L))
9752       return getCouldNotCompute();
9753   } else if (!Stride->isOne() &&
9754              doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap))
9755     // Avoid proven overflow cases: this will ensure that the backedge taken
9756     // count will not generate any unsigned overflow. Relaxed no-overflow
9757     // conditions exploit NoWrapFlags, allowing to optimize in presence of
9758     // undefined behaviors like the case of C language.
9759     return getCouldNotCompute();
9760 
9761   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT
9762                                       : ICmpInst::ICMP_ULT;
9763   const SCEV *Start = IV->getStart();
9764   const SCEV *End = RHS;
9765   // If the backedge is taken at least once, then it will be taken
9766   // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start
9767   // is the LHS value of the less-than comparison the first time it is evaluated
9768   // and End is the RHS.
9769   const SCEV *BECountIfBackedgeTaken =
9770     computeBECount(getMinusSCEV(End, Start), Stride, false);
9771   // If the loop entry is guarded by the result of the backedge test of the
9772   // first loop iteration, then we know the backedge will be taken at least
9773   // once and so the backedge taken count is as above. If not then we use the
9774   // expression (max(End,Start)-Start)/Stride to describe the backedge count,
9775   // as if the backedge is taken at least once max(End,Start) is End and so the
9776   // result is as above, and if not max(End,Start) is Start so we get a backedge
9777   // count of zero.
9778   const SCEV *BECount;
9779   if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS))
9780     BECount = BECountIfBackedgeTaken;
9781   else {
9782     End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
9783     BECount = computeBECount(getMinusSCEV(End, Start), Stride, false);
9784   }
9785 
9786   const SCEV *MaxBECount;
9787   bool MaxOrZero = false;
9788   if (isa<SCEVConstant>(BECount))
9789     MaxBECount = BECount;
9790   else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) {
9791     // If we know exactly how many times the backedge will be taken if it's
9792     // taken at least once, then the backedge count will either be that or
9793     // zero.
9794     MaxBECount = BECountIfBackedgeTaken;
9795     MaxOrZero = true;
9796   } else {
9797     // Calculate the maximum backedge count based on the range of values
9798     // permitted by Start, End, and Stride.
9799     APInt MinStart = IsSigned ? getSignedRangeMin(Start)
9800                               : getUnsignedRangeMin(Start);
9801 
9802     unsigned BitWidth = getTypeSizeInBits(LHS->getType());
9803 
9804     APInt StrideForMaxBECount;
9805 
9806     if (PositiveStride)
9807       StrideForMaxBECount =
9808         IsSigned ? getSignedRangeMin(Stride)
9809                  : getUnsignedRangeMin(Stride);
9810     else
9811       // Using a stride of 1 is safe when computing max backedge taken count for
9812       // a loop with unknown stride.
9813       StrideForMaxBECount = APInt(BitWidth, 1, IsSigned);
9814 
9815     APInt Limit =
9816       IsSigned ? APInt::getSignedMaxValue(BitWidth) - (StrideForMaxBECount - 1)
9817                : APInt::getMaxValue(BitWidth) - (StrideForMaxBECount - 1);
9818 
9819     // Although End can be a MAX expression we estimate MaxEnd considering only
9820     // the case End = RHS. This is safe because in the other case (End - Start)
9821     // is zero, leading to a zero maximum backedge taken count.
9822     APInt MaxEnd =
9823       IsSigned ? APIntOps::smin(getSignedRangeMax(RHS), Limit)
9824                : APIntOps::umin(getUnsignedRangeMax(RHS), Limit);
9825 
9826     MaxBECount = computeBECount(getConstant(MaxEnd - MinStart),
9827                                 getConstant(StrideForMaxBECount), false);
9828   }
9829 
9830   if (isa<SCEVCouldNotCompute>(MaxBECount) &&
9831       !isa<SCEVCouldNotCompute>(BECount))
9832     MaxBECount = getConstant(getUnsignedRangeMax(BECount));
9833 
9834   return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates);
9835 }
9836 
9837 ScalarEvolution::ExitLimit
9838 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
9839                                      const Loop *L, bool IsSigned,
9840                                      bool ControlsExit, bool AllowPredicates) {
9841   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
9842   // We handle only IV > Invariant
9843   if (!isLoopInvariant(RHS, L))
9844     return getCouldNotCompute();
9845 
9846   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
9847   if (!IV && AllowPredicates)
9848     // Try to make this an AddRec using runtime tests, in the first X
9849     // iterations of this loop, where X is the SCEV expression found by the
9850     // algorithm below.
9851     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
9852 
9853   // Avoid weird loops
9854   if (!IV || IV->getLoop() != L || !IV->isAffine())
9855     return getCouldNotCompute();
9856 
9857   bool NoWrap = ControlsExit &&
9858                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
9859 
9860   const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
9861 
9862   // Avoid negative or zero stride values
9863   if (!isKnownPositive(Stride))
9864     return getCouldNotCompute();
9865 
9866   // Avoid proven overflow cases: this will ensure that the backedge taken count
9867   // will not generate any unsigned overflow. Relaxed no-overflow conditions
9868   // exploit NoWrapFlags, allowing to optimize in presence of undefined
9869   // behaviors like the case of C language.
9870   if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap))
9871     return getCouldNotCompute();
9872 
9873   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT
9874                                       : ICmpInst::ICMP_UGT;
9875 
9876   const SCEV *Start = IV->getStart();
9877   const SCEV *End = RHS;
9878   if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS))
9879     End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
9880 
9881   const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false);
9882 
9883   APInt MaxStart = IsSigned ? getSignedRangeMax(Start)
9884                             : getUnsignedRangeMax(Start);
9885 
9886   APInt MinStride = IsSigned ? getSignedRangeMin(Stride)
9887                              : getUnsignedRangeMin(Stride);
9888 
9889   unsigned BitWidth = getTypeSizeInBits(LHS->getType());
9890   APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
9891                          : APInt::getMinValue(BitWidth) + (MinStride - 1);
9892 
9893   // Although End can be a MIN expression we estimate MinEnd considering only
9894   // the case End = RHS. This is safe because in the other case (Start - End)
9895   // is zero, leading to a zero maximum backedge taken count.
9896   APInt MinEnd =
9897     IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit)
9898              : APIntOps::umax(getUnsignedRangeMin(RHS), Limit);
9899 
9900 
9901   const SCEV *MaxBECount = getCouldNotCompute();
9902   if (isa<SCEVConstant>(BECount))
9903     MaxBECount = BECount;
9904   else
9905     MaxBECount = computeBECount(getConstant(MaxStart - MinEnd),
9906                                 getConstant(MinStride), false);
9907 
9908   if (isa<SCEVCouldNotCompute>(MaxBECount))
9909     MaxBECount = BECount;
9910 
9911   return ExitLimit(BECount, MaxBECount, false, Predicates);
9912 }
9913 
9914 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range,
9915                                                     ScalarEvolution &SE) const {
9916   if (Range.isFullSet())  // Infinite loop.
9917     return SE.getCouldNotCompute();
9918 
9919   // If the start is a non-zero constant, shift the range to simplify things.
9920   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
9921     if (!SC->getValue()->isZero()) {
9922       SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
9923       Operands[0] = SE.getZero(SC->getType());
9924       const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
9925                                              getNoWrapFlags(FlagNW));
9926       if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
9927         return ShiftedAddRec->getNumIterationsInRange(
9928             Range.subtract(SC->getAPInt()), SE);
9929       // This is strange and shouldn't happen.
9930       return SE.getCouldNotCompute();
9931     }
9932 
9933   // The only time we can solve this is when we have all constant indices.
9934   // Otherwise, we cannot determine the overflow conditions.
9935   if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
9936     return SE.getCouldNotCompute();
9937 
9938   // Okay at this point we know that all elements of the chrec are constants and
9939   // that the start element is zero.
9940 
9941   // First check to see if the range contains zero.  If not, the first
9942   // iteration exits.
9943   unsigned BitWidth = SE.getTypeSizeInBits(getType());
9944   if (!Range.contains(APInt(BitWidth, 0)))
9945     return SE.getZero(getType());
9946 
9947   if (isAffine()) {
9948     // If this is an affine expression then we have this situation:
9949     //   Solve {0,+,A} in Range  ===  Ax in Range
9950 
9951     // We know that zero is in the range.  If A is positive then we know that
9952     // the upper value of the range must be the first possible exit value.
9953     // If A is negative then the lower of the range is the last possible loop
9954     // value.  Also note that we already checked for a full range.
9955     APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
9956     APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower();
9957 
9958     // The exit value should be (End+A)/A.
9959     APInt ExitVal = (End + A).udiv(A);
9960     ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
9961 
9962     // Evaluate at the exit value.  If we really did fall out of the valid
9963     // range, then we computed our trip count, otherwise wrap around or other
9964     // things must have happened.
9965     ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
9966     if (Range.contains(Val->getValue()))
9967       return SE.getCouldNotCompute();  // Something strange happened
9968 
9969     // Ensure that the previous value is in the range.  This is a sanity check.
9970     assert(Range.contains(
9971            EvaluateConstantChrecAtConstant(this,
9972            ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&
9973            "Linear scev computation is off in a bad way!");
9974     return SE.getConstant(ExitValue);
9975   } else if (isQuadratic()) {
9976     // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
9977     // quadratic equation to solve it.  To do this, we must frame our problem in
9978     // terms of figuring out when zero is crossed, instead of when
9979     // Range.getUpper() is crossed.
9980     SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
9981     NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
9982     const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(), FlagAnyWrap);
9983 
9984     // Next, solve the constructed addrec
9985     if (auto Roots =
9986             SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE)) {
9987       const SCEVConstant *R1 = Roots->first;
9988       const SCEVConstant *R2 = Roots->second;
9989       // Pick the smallest positive root value.
9990       if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
9991               ICmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
9992         if (!CB->getZExtValue())
9993           std::swap(R1, R2); // R1 is the minimum root now.
9994 
9995         // Make sure the root is not off by one.  The returned iteration should
9996         // not be in the range, but the previous one should be.  When solving
9997         // for "X*X < 5", for example, we should not return a root of 2.
9998         ConstantInt *R1Val =
9999             EvaluateConstantChrecAtConstant(this, R1->getValue(), SE);
10000         if (Range.contains(R1Val->getValue())) {
10001           // The next iteration must be out of the range...
10002           ConstantInt *NextVal =
10003               ConstantInt::get(SE.getContext(), R1->getAPInt() + 1);
10004 
10005           R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
10006           if (!Range.contains(R1Val->getValue()))
10007             return SE.getConstant(NextVal);
10008           return SE.getCouldNotCompute(); // Something strange happened
10009         }
10010 
10011         // If R1 was not in the range, then it is a good return value.  Make
10012         // sure that R1-1 WAS in the range though, just in case.
10013         ConstantInt *NextVal =
10014             ConstantInt::get(SE.getContext(), R1->getAPInt() - 1);
10015         R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
10016         if (Range.contains(R1Val->getValue()))
10017           return R1;
10018         return SE.getCouldNotCompute(); // Something strange happened
10019       }
10020     }
10021   }
10022 
10023   return SE.getCouldNotCompute();
10024 }
10025 
10026 // Return true when S contains at least an undef value.
10027 static inline bool containsUndefs(const SCEV *S) {
10028   return SCEVExprContains(S, [](const SCEV *S) {
10029     if (const auto *SU = dyn_cast<SCEVUnknown>(S))
10030       return isa<UndefValue>(SU->getValue());
10031     else if (const auto *SC = dyn_cast<SCEVConstant>(S))
10032       return isa<UndefValue>(SC->getValue());
10033     return false;
10034   });
10035 }
10036 
10037 namespace {
10038 
10039 // Collect all steps of SCEV expressions.
10040 struct SCEVCollectStrides {
10041   ScalarEvolution &SE;
10042   SmallVectorImpl<const SCEV *> &Strides;
10043 
10044   SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S)
10045       : SE(SE), Strides(S) {}
10046 
10047   bool follow(const SCEV *S) {
10048     if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
10049       Strides.push_back(AR->getStepRecurrence(SE));
10050     return true;
10051   }
10052 
10053   bool isDone() const { return false; }
10054 };
10055 
10056 // Collect all SCEVUnknown and SCEVMulExpr expressions.
10057 struct SCEVCollectTerms {
10058   SmallVectorImpl<const SCEV *> &Terms;
10059 
10060   SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) : Terms(T) {}
10061 
10062   bool follow(const SCEV *S) {
10063     if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) ||
10064         isa<SCEVSignExtendExpr>(S)) {
10065       if (!containsUndefs(S))
10066         Terms.push_back(S);
10067 
10068       // Stop recursion: once we collected a term, do not walk its operands.
10069       return false;
10070     }
10071 
10072     // Keep looking.
10073     return true;
10074   }
10075 
10076   bool isDone() const { return false; }
10077 };
10078 
10079 // Check if a SCEV contains an AddRecExpr.
10080 struct SCEVHasAddRec {
10081   bool &ContainsAddRec;
10082 
10083   SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) {
10084     ContainsAddRec = false;
10085   }
10086 
10087   bool follow(const SCEV *S) {
10088     if (isa<SCEVAddRecExpr>(S)) {
10089       ContainsAddRec = true;
10090 
10091       // Stop recursion: once we collected a term, do not walk its operands.
10092       return false;
10093     }
10094 
10095     // Keep looking.
10096     return true;
10097   }
10098 
10099   bool isDone() const { return false; }
10100 };
10101 
10102 // Find factors that are multiplied with an expression that (possibly as a
10103 // subexpression) contains an AddRecExpr. In the expression:
10104 //
10105 //  8 * (100 +  %p * %q * (%a + {0, +, 1}_loop))
10106 //
10107 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)"
10108 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size
10109 // parameters as they form a product with an induction variable.
10110 //
10111 // This collector expects all array size parameters to be in the same MulExpr.
10112 // It might be necessary to later add support for collecting parameters that are
10113 // spread over different nested MulExpr.
10114 struct SCEVCollectAddRecMultiplies {
10115   SmallVectorImpl<const SCEV *> &Terms;
10116   ScalarEvolution &SE;
10117 
10118   SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE)
10119       : Terms(T), SE(SE) {}
10120 
10121   bool follow(const SCEV *S) {
10122     if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) {
10123       bool HasAddRec = false;
10124       SmallVector<const SCEV *, 0> Operands;
10125       for (auto Op : Mul->operands()) {
10126         const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op);
10127         if (Unknown && !isa<CallInst>(Unknown->getValue())) {
10128           Operands.push_back(Op);
10129         } else if (Unknown) {
10130           HasAddRec = true;
10131         } else {
10132           bool ContainsAddRec;
10133           SCEVHasAddRec ContiansAddRec(ContainsAddRec);
10134           visitAll(Op, ContiansAddRec);
10135           HasAddRec |= ContainsAddRec;
10136         }
10137       }
10138       if (Operands.size() == 0)
10139         return true;
10140 
10141       if (!HasAddRec)
10142         return false;
10143 
10144       Terms.push_back(SE.getMulExpr(Operands));
10145       // Stop recursion: once we collected a term, do not walk its operands.
10146       return false;
10147     }
10148 
10149     // Keep looking.
10150     return true;
10151   }
10152 
10153   bool isDone() const { return false; }
10154 };
10155 
10156 } // end anonymous namespace
10157 
10158 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in
10159 /// two places:
10160 ///   1) The strides of AddRec expressions.
10161 ///   2) Unknowns that are multiplied with AddRec expressions.
10162 void ScalarEvolution::collectParametricTerms(const SCEV *Expr,
10163     SmallVectorImpl<const SCEV *> &Terms) {
10164   SmallVector<const SCEV *, 4> Strides;
10165   SCEVCollectStrides StrideCollector(*this, Strides);
10166   visitAll(Expr, StrideCollector);
10167 
10168   DEBUG({
10169       dbgs() << "Strides:\n";
10170       for (const SCEV *S : Strides)
10171         dbgs() << *S << "\n";
10172     });
10173 
10174   for (const SCEV *S : Strides) {
10175     SCEVCollectTerms TermCollector(Terms);
10176     visitAll(S, TermCollector);
10177   }
10178 
10179   DEBUG({
10180       dbgs() << "Terms:\n";
10181       for (const SCEV *T : Terms)
10182         dbgs() << *T << "\n";
10183     });
10184 
10185   SCEVCollectAddRecMultiplies MulCollector(Terms, *this);
10186   visitAll(Expr, MulCollector);
10187 }
10188 
10189 static bool findArrayDimensionsRec(ScalarEvolution &SE,
10190                                    SmallVectorImpl<const SCEV *> &Terms,
10191                                    SmallVectorImpl<const SCEV *> &Sizes) {
10192   int Last = Terms.size() - 1;
10193   const SCEV *Step = Terms[Last];
10194 
10195   // End of recursion.
10196   if (Last == 0) {
10197     if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) {
10198       SmallVector<const SCEV *, 2> Qs;
10199       for (const SCEV *Op : M->operands())
10200         if (!isa<SCEVConstant>(Op))
10201           Qs.push_back(Op);
10202 
10203       Step = SE.getMulExpr(Qs);
10204     }
10205 
10206     Sizes.push_back(Step);
10207     return true;
10208   }
10209 
10210   for (const SCEV *&Term : Terms) {
10211     // Normalize the terms before the next call to findArrayDimensionsRec.
10212     const SCEV *Q, *R;
10213     SCEVDivision::divide(SE, Term, Step, &Q, &R);
10214 
10215     // Bail out when GCD does not evenly divide one of the terms.
10216     if (!R->isZero())
10217       return false;
10218 
10219     Term = Q;
10220   }
10221 
10222   // Remove all SCEVConstants.
10223   Terms.erase(
10224       remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }),
10225       Terms.end());
10226 
10227   if (Terms.size() > 0)
10228     if (!findArrayDimensionsRec(SE, Terms, Sizes))
10229       return false;
10230 
10231   Sizes.push_back(Step);
10232   return true;
10233 }
10234 
10235 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter.
10236 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) {
10237   for (const SCEV *T : Terms)
10238     if (SCEVExprContains(T, isa<SCEVUnknown, const SCEV *>))
10239       return true;
10240   return false;
10241 }
10242 
10243 // Return the number of product terms in S.
10244 static inline int numberOfTerms(const SCEV *S) {
10245   if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S))
10246     return Expr->getNumOperands();
10247   return 1;
10248 }
10249 
10250 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) {
10251   if (isa<SCEVConstant>(T))
10252     return nullptr;
10253 
10254   if (isa<SCEVUnknown>(T))
10255     return T;
10256 
10257   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) {
10258     SmallVector<const SCEV *, 2> Factors;
10259     for (const SCEV *Op : M->operands())
10260       if (!isa<SCEVConstant>(Op))
10261         Factors.push_back(Op);
10262 
10263     return SE.getMulExpr(Factors);
10264   }
10265 
10266   return T;
10267 }
10268 
10269 /// Return the size of an element read or written by Inst.
10270 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
10271   Type *Ty;
10272   if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
10273     Ty = Store->getValueOperand()->getType();
10274   else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
10275     Ty = Load->getType();
10276   else
10277     return nullptr;
10278 
10279   Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
10280   return getSizeOfExpr(ETy, Ty);
10281 }
10282 
10283 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
10284                                           SmallVectorImpl<const SCEV *> &Sizes,
10285                                           const SCEV *ElementSize) {
10286   if (Terms.size() < 1 || !ElementSize)
10287     return;
10288 
10289   // Early return when Terms do not contain parameters: we do not delinearize
10290   // non parametric SCEVs.
10291   if (!containsParameters(Terms))
10292     return;
10293 
10294   DEBUG({
10295       dbgs() << "Terms:\n";
10296       for (const SCEV *T : Terms)
10297         dbgs() << *T << "\n";
10298     });
10299 
10300   // Remove duplicates.
10301   array_pod_sort(Terms.begin(), Terms.end());
10302   Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end());
10303 
10304   // Put larger terms first.
10305   std::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) {
10306     return numberOfTerms(LHS) > numberOfTerms(RHS);
10307   });
10308 
10309   // Try to divide all terms by the element size. If term is not divisible by
10310   // element size, proceed with the original term.
10311   for (const SCEV *&Term : Terms) {
10312     const SCEV *Q, *R;
10313     SCEVDivision::divide(*this, Term, ElementSize, &Q, &R);
10314     if (!Q->isZero())
10315       Term = Q;
10316   }
10317 
10318   SmallVector<const SCEV *, 4> NewTerms;
10319 
10320   // Remove constant factors.
10321   for (const SCEV *T : Terms)
10322     if (const SCEV *NewT = removeConstantFactors(*this, T))
10323       NewTerms.push_back(NewT);
10324 
10325   DEBUG({
10326       dbgs() << "Terms after sorting:\n";
10327       for (const SCEV *T : NewTerms)
10328         dbgs() << *T << "\n";
10329     });
10330 
10331   if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) {
10332     Sizes.clear();
10333     return;
10334   }
10335 
10336   // The last element to be pushed into Sizes is the size of an element.
10337   Sizes.push_back(ElementSize);
10338 
10339   DEBUG({
10340       dbgs() << "Sizes:\n";
10341       for (const SCEV *S : Sizes)
10342         dbgs() << *S << "\n";
10343     });
10344 }
10345 
10346 void ScalarEvolution::computeAccessFunctions(
10347     const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts,
10348     SmallVectorImpl<const SCEV *> &Sizes) {
10349   // Early exit in case this SCEV is not an affine multivariate function.
10350   if (Sizes.empty())
10351     return;
10352 
10353   if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr))
10354     if (!AR->isAffine())
10355       return;
10356 
10357   const SCEV *Res = Expr;
10358   int Last = Sizes.size() - 1;
10359   for (int i = Last; i >= 0; i--) {
10360     const SCEV *Q, *R;
10361     SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R);
10362 
10363     DEBUG({
10364         dbgs() << "Res: " << *Res << "\n";
10365         dbgs() << "Sizes[i]: " << *Sizes[i] << "\n";
10366         dbgs() << "Res divided by Sizes[i]:\n";
10367         dbgs() << "Quotient: " << *Q << "\n";
10368         dbgs() << "Remainder: " << *R << "\n";
10369       });
10370 
10371     Res = Q;
10372 
10373     // Do not record the last subscript corresponding to the size of elements in
10374     // the array.
10375     if (i == Last) {
10376 
10377       // Bail out if the remainder is too complex.
10378       if (isa<SCEVAddRecExpr>(R)) {
10379         Subscripts.clear();
10380         Sizes.clear();
10381         return;
10382       }
10383 
10384       continue;
10385     }
10386 
10387     // Record the access function for the current subscript.
10388     Subscripts.push_back(R);
10389   }
10390 
10391   // Also push in last position the remainder of the last division: it will be
10392   // the access function of the innermost dimension.
10393   Subscripts.push_back(Res);
10394 
10395   std::reverse(Subscripts.begin(), Subscripts.end());
10396 
10397   DEBUG({
10398       dbgs() << "Subscripts:\n";
10399       for (const SCEV *S : Subscripts)
10400         dbgs() << *S << "\n";
10401     });
10402 }
10403 
10404 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and
10405 /// sizes of an array access. Returns the remainder of the delinearization that
10406 /// is the offset start of the array.  The SCEV->delinearize algorithm computes
10407 /// the multiples of SCEV coefficients: that is a pattern matching of sub
10408 /// expressions in the stride and base of a SCEV corresponding to the
10409 /// computation of a GCD (greatest common divisor) of base and stride.  When
10410 /// SCEV->delinearize fails, it returns the SCEV unchanged.
10411 ///
10412 /// For example: when analyzing the memory access A[i][j][k] in this loop nest
10413 ///
10414 ///  void foo(long n, long m, long o, double A[n][m][o]) {
10415 ///
10416 ///    for (long i = 0; i < n; i++)
10417 ///      for (long j = 0; j < m; j++)
10418 ///        for (long k = 0; k < o; k++)
10419 ///          A[i][j][k] = 1.0;
10420 ///  }
10421 ///
10422 /// the delinearization input is the following AddRec SCEV:
10423 ///
10424 ///  AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k>
10425 ///
10426 /// From this SCEV, we are able to say that the base offset of the access is %A
10427 /// because it appears as an offset that does not divide any of the strides in
10428 /// the loops:
10429 ///
10430 ///  CHECK: Base offset: %A
10431 ///
10432 /// and then SCEV->delinearize determines the size of some of the dimensions of
10433 /// the array as these are the multiples by which the strides are happening:
10434 ///
10435 ///  CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes.
10436 ///
10437 /// Note that the outermost dimension remains of UnknownSize because there are
10438 /// no strides that would help identifying the size of the last dimension: when
10439 /// the array has been statically allocated, one could compute the size of that
10440 /// dimension by dividing the overall size of the array by the size of the known
10441 /// dimensions: %m * %o * 8.
10442 ///
10443 /// Finally delinearize provides the access functions for the array reference
10444 /// that does correspond to A[i][j][k] of the above C testcase:
10445 ///
10446 ///  CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>]
10447 ///
10448 /// The testcases are checking the output of a function pass:
10449 /// DelinearizationPass that walks through all loads and stores of a function
10450 /// asking for the SCEV of the memory access with respect to all enclosing
10451 /// loops, calling SCEV->delinearize on that and printing the results.
10452 void ScalarEvolution::delinearize(const SCEV *Expr,
10453                                  SmallVectorImpl<const SCEV *> &Subscripts,
10454                                  SmallVectorImpl<const SCEV *> &Sizes,
10455                                  const SCEV *ElementSize) {
10456   // First step: collect parametric terms.
10457   SmallVector<const SCEV *, 4> Terms;
10458   collectParametricTerms(Expr, Terms);
10459 
10460   if (Terms.empty())
10461     return;
10462 
10463   // Second step: find subscript sizes.
10464   findArrayDimensions(Terms, Sizes, ElementSize);
10465 
10466   if (Sizes.empty())
10467     return;
10468 
10469   // Third step: compute the access functions for each subscript.
10470   computeAccessFunctions(Expr, Subscripts, Sizes);
10471 
10472   if (Subscripts.empty())
10473     return;
10474 
10475   DEBUG({
10476       dbgs() << "succeeded to delinearize " << *Expr << "\n";
10477       dbgs() << "ArrayDecl[UnknownSize]";
10478       for (const SCEV *S : Sizes)
10479         dbgs() << "[" << *S << "]";
10480 
10481       dbgs() << "\nArrayRef";
10482       for (const SCEV *S : Subscripts)
10483         dbgs() << "[" << *S << "]";
10484       dbgs() << "\n";
10485     });
10486 }
10487 
10488 //===----------------------------------------------------------------------===//
10489 //                   SCEVCallbackVH Class Implementation
10490 //===----------------------------------------------------------------------===//
10491 
10492 void ScalarEvolution::SCEVCallbackVH::deleted() {
10493   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
10494   if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
10495     SE->ConstantEvolutionLoopExitValue.erase(PN);
10496   SE->eraseValueFromMap(getValPtr());
10497   // this now dangles!
10498 }
10499 
10500 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
10501   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
10502 
10503   // Forget all the expressions associated with users of the old value,
10504   // so that future queries will recompute the expressions using the new
10505   // value.
10506   Value *Old = getValPtr();
10507   SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end());
10508   SmallPtrSet<User *, 8> Visited;
10509   while (!Worklist.empty()) {
10510     User *U = Worklist.pop_back_val();
10511     // Deleting the Old value will cause this to dangle. Postpone
10512     // that until everything else is done.
10513     if (U == Old)
10514       continue;
10515     if (!Visited.insert(U).second)
10516       continue;
10517     if (PHINode *PN = dyn_cast<PHINode>(U))
10518       SE->ConstantEvolutionLoopExitValue.erase(PN);
10519     SE->eraseValueFromMap(U);
10520     Worklist.insert(Worklist.end(), U->user_begin(), U->user_end());
10521   }
10522   // Delete the Old value.
10523   if (PHINode *PN = dyn_cast<PHINode>(Old))
10524     SE->ConstantEvolutionLoopExitValue.erase(PN);
10525   SE->eraseValueFromMap(Old);
10526   // this now dangles!
10527 }
10528 
10529 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
10530   : CallbackVH(V), SE(se) {}
10531 
10532 //===----------------------------------------------------------------------===//
10533 //                   ScalarEvolution Class Implementation
10534 //===----------------------------------------------------------------------===//
10535 
10536 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
10537                                  AssumptionCache &AC, DominatorTree &DT,
10538                                  LoopInfo &LI)
10539     : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
10540       CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64),
10541       LoopDispositions(64), BlockDispositions(64) {
10542   // To use guards for proving predicates, we need to scan every instruction in
10543   // relevant basic blocks, and not just terminators.  Doing this is a waste of
10544   // time if the IR does not actually contain any calls to
10545   // @llvm.experimental.guard, so do a quick check and remember this beforehand.
10546   //
10547   // This pessimizes the case where a pass that preserves ScalarEvolution wants
10548   // to _add_ guards to the module when there weren't any before, and wants
10549   // ScalarEvolution to optimize based on those guards.  For now we prefer to be
10550   // efficient in lieu of being smart in that rather obscure case.
10551 
10552   auto *GuardDecl = F.getParent()->getFunction(
10553       Intrinsic::getName(Intrinsic::experimental_guard));
10554   HasGuards = GuardDecl && !GuardDecl->use_empty();
10555 }
10556 
10557 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
10558     : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT),
10559       LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
10560       ValueExprMap(std::move(Arg.ValueExprMap)),
10561       PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
10562       MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)),
10563       BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
10564       PredicatedBackedgeTakenCounts(
10565           std::move(Arg.PredicatedBackedgeTakenCounts)),
10566       ExitLimits(std::move(Arg.ExitLimits)),
10567       ConstantEvolutionLoopExitValue(
10568           std::move(Arg.ConstantEvolutionLoopExitValue)),
10569       ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
10570       LoopDispositions(std::move(Arg.LoopDispositions)),
10571       LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
10572       BlockDispositions(std::move(Arg.BlockDispositions)),
10573       UnsignedRanges(std::move(Arg.UnsignedRanges)),
10574       SignedRanges(std::move(Arg.SignedRanges)),
10575       UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
10576       UniquePreds(std::move(Arg.UniquePreds)),
10577       SCEVAllocator(std::move(Arg.SCEVAllocator)),
10578       PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)),
10579       FirstUnknown(Arg.FirstUnknown) {
10580   Arg.FirstUnknown = nullptr;
10581 }
10582 
10583 ScalarEvolution::~ScalarEvolution() {
10584   // Iterate through all the SCEVUnknown instances and call their
10585   // destructors, so that they release their references to their values.
10586   for (SCEVUnknown *U = FirstUnknown; U;) {
10587     SCEVUnknown *Tmp = U;
10588     U = U->Next;
10589     Tmp->~SCEVUnknown();
10590   }
10591   FirstUnknown = nullptr;
10592 
10593   ExprValueMap.clear();
10594   ValueExprMap.clear();
10595   HasRecMap.clear();
10596 
10597   // Free any extra memory created for ExitNotTakenInfo in the unlikely event
10598   // that a loop had multiple computable exits.
10599   for (auto &BTCI : BackedgeTakenCounts)
10600     BTCI.second.clear();
10601   for (auto &BTCI : PredicatedBackedgeTakenCounts)
10602     BTCI.second.clear();
10603 
10604   assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
10605   assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
10606   assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
10607 }
10608 
10609 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
10610   return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
10611 }
10612 
10613 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
10614                           const Loop *L) {
10615   // Print all inner loops first
10616   for (Loop *I : *L)
10617     PrintLoopInfo(OS, SE, I);
10618 
10619   OS << "Loop ";
10620   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
10621   OS << ": ";
10622 
10623   SmallVector<BasicBlock *, 8> ExitBlocks;
10624   L->getExitBlocks(ExitBlocks);
10625   if (ExitBlocks.size() != 1)
10626     OS << "<multiple exits> ";
10627 
10628   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
10629     OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
10630   } else {
10631     OS << "Unpredictable backedge-taken count. ";
10632   }
10633 
10634   OS << "\n"
10635         "Loop ";
10636   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
10637   OS << ": ";
10638 
10639   if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
10640     OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
10641     if (SE->isBackedgeTakenCountMaxOrZero(L))
10642       OS << ", actual taken count either this or zero.";
10643   } else {
10644     OS << "Unpredictable max backedge-taken count. ";
10645   }
10646 
10647   OS << "\n"
10648         "Loop ";
10649   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
10650   OS << ": ";
10651 
10652   SCEVUnionPredicate Pred;
10653   auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred);
10654   if (!isa<SCEVCouldNotCompute>(PBT)) {
10655     OS << "Predicated backedge-taken count is " << *PBT << "\n";
10656     OS << " Predicates:\n";
10657     Pred.print(OS, 4);
10658   } else {
10659     OS << "Unpredictable predicated backedge-taken count. ";
10660   }
10661   OS << "\n";
10662 
10663   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
10664     OS << "Loop ";
10665     L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
10666     OS << ": ";
10667     OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
10668   }
10669 }
10670 
10671 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) {
10672   switch (LD) {
10673   case ScalarEvolution::LoopVariant:
10674     return "Variant";
10675   case ScalarEvolution::LoopInvariant:
10676     return "Invariant";
10677   case ScalarEvolution::LoopComputable:
10678     return "Computable";
10679   }
10680   llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!");
10681 }
10682 
10683 void ScalarEvolution::print(raw_ostream &OS) const {
10684   // ScalarEvolution's implementation of the print method is to print
10685   // out SCEV values of all instructions that are interesting. Doing
10686   // this potentially causes it to create new SCEV objects though,
10687   // which technically conflicts with the const qualifier. This isn't
10688   // observable from outside the class though, so casting away the
10689   // const isn't dangerous.
10690   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
10691 
10692   OS << "Classifying expressions for: ";
10693   F.printAsOperand(OS, /*PrintType=*/false);
10694   OS << "\n";
10695   for (Instruction &I : instructions(F))
10696     if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
10697       OS << I << '\n';
10698       OS << "  -->  ";
10699       const SCEV *SV = SE.getSCEV(&I);
10700       SV->print(OS);
10701       if (!isa<SCEVCouldNotCompute>(SV)) {
10702         OS << " U: ";
10703         SE.getUnsignedRange(SV).print(OS);
10704         OS << " S: ";
10705         SE.getSignedRange(SV).print(OS);
10706       }
10707 
10708       const Loop *L = LI.getLoopFor(I.getParent());
10709 
10710       const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
10711       if (AtUse != SV) {
10712         OS << "  -->  ";
10713         AtUse->print(OS);
10714         if (!isa<SCEVCouldNotCompute>(AtUse)) {
10715           OS << " U: ";
10716           SE.getUnsignedRange(AtUse).print(OS);
10717           OS << " S: ";
10718           SE.getSignedRange(AtUse).print(OS);
10719         }
10720       }
10721 
10722       if (L) {
10723         OS << "\t\t" "Exits: ";
10724         const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
10725         if (!SE.isLoopInvariant(ExitValue, L)) {
10726           OS << "<<Unknown>>";
10727         } else {
10728           OS << *ExitValue;
10729         }
10730 
10731         bool First = true;
10732         for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
10733           if (First) {
10734             OS << "\t\t" "LoopDispositions: { ";
10735             First = false;
10736           } else {
10737             OS << ", ";
10738           }
10739 
10740           Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
10741           OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter));
10742         }
10743 
10744         for (auto *InnerL : depth_first(L)) {
10745           if (InnerL == L)
10746             continue;
10747           if (First) {
10748             OS << "\t\t" "LoopDispositions: { ";
10749             First = false;
10750           } else {
10751             OS << ", ";
10752           }
10753 
10754           InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
10755           OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL));
10756         }
10757 
10758         OS << " }";
10759       }
10760 
10761       OS << "\n";
10762     }
10763 
10764   OS << "Determining loop execution counts for: ";
10765   F.printAsOperand(OS, /*PrintType=*/false);
10766   OS << "\n";
10767   for (Loop *I : LI)
10768     PrintLoopInfo(OS, &SE, I);
10769 }
10770 
10771 ScalarEvolution::LoopDisposition
10772 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
10773   auto &Values = LoopDispositions[S];
10774   for (auto &V : Values) {
10775     if (V.getPointer() == L)
10776       return V.getInt();
10777   }
10778   Values.emplace_back(L, LoopVariant);
10779   LoopDisposition D = computeLoopDisposition(S, L);
10780   auto &Values2 = LoopDispositions[S];
10781   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
10782     if (V.getPointer() == L) {
10783       V.setInt(D);
10784       break;
10785     }
10786   }
10787   return D;
10788 }
10789 
10790 ScalarEvolution::LoopDisposition
10791 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
10792   switch (static_cast<SCEVTypes>(S->getSCEVType())) {
10793   case scConstant:
10794     return LoopInvariant;
10795   case scTruncate:
10796   case scZeroExtend:
10797   case scSignExtend:
10798     return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
10799   case scAddRecExpr: {
10800     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
10801 
10802     // If L is the addrec's loop, it's computable.
10803     if (AR->getLoop() == L)
10804       return LoopComputable;
10805 
10806     // Add recurrences are never invariant in the function-body (null loop).
10807     if (!L)
10808       return LoopVariant;
10809 
10810     // This recurrence is variant w.r.t. L if L contains AR's loop.
10811     if (L->contains(AR->getLoop()))
10812       return LoopVariant;
10813 
10814     // This recurrence is invariant w.r.t. L if AR's loop contains L.
10815     if (AR->getLoop()->contains(L))
10816       return LoopInvariant;
10817 
10818     // This recurrence is variant w.r.t. L if any of its operands
10819     // are variant.
10820     for (auto *Op : AR->operands())
10821       if (!isLoopInvariant(Op, L))
10822         return LoopVariant;
10823 
10824     // Otherwise it's loop-invariant.
10825     return LoopInvariant;
10826   }
10827   case scAddExpr:
10828   case scMulExpr:
10829   case scUMaxExpr:
10830   case scSMaxExpr: {
10831     bool HasVarying = false;
10832     for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) {
10833       LoopDisposition D = getLoopDisposition(Op, L);
10834       if (D == LoopVariant)
10835         return LoopVariant;
10836       if (D == LoopComputable)
10837         HasVarying = true;
10838     }
10839     return HasVarying ? LoopComputable : LoopInvariant;
10840   }
10841   case scUDivExpr: {
10842     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
10843     LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
10844     if (LD == LoopVariant)
10845       return LoopVariant;
10846     LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
10847     if (RD == LoopVariant)
10848       return LoopVariant;
10849     return (LD == LoopInvariant && RD == LoopInvariant) ?
10850            LoopInvariant : LoopComputable;
10851   }
10852   case scUnknown:
10853     // All non-instruction values are loop invariant.  All instructions are loop
10854     // invariant if they are not contained in the specified loop.
10855     // Instructions are never considered invariant in the function body
10856     // (null loop) because they are defined within the "loop".
10857     if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
10858       return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
10859     return LoopInvariant;
10860   case scCouldNotCompute:
10861     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
10862   }
10863   llvm_unreachable("Unknown SCEV kind!");
10864 }
10865 
10866 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
10867   return getLoopDisposition(S, L) == LoopInvariant;
10868 }
10869 
10870 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
10871   return getLoopDisposition(S, L) == LoopComputable;
10872 }
10873 
10874 ScalarEvolution::BlockDisposition
10875 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
10876   auto &Values = BlockDispositions[S];
10877   for (auto &V : Values) {
10878     if (V.getPointer() == BB)
10879       return V.getInt();
10880   }
10881   Values.emplace_back(BB, DoesNotDominateBlock);
10882   BlockDisposition D = computeBlockDisposition(S, BB);
10883   auto &Values2 = BlockDispositions[S];
10884   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
10885     if (V.getPointer() == BB) {
10886       V.setInt(D);
10887       break;
10888     }
10889   }
10890   return D;
10891 }
10892 
10893 ScalarEvolution::BlockDisposition
10894 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
10895   switch (static_cast<SCEVTypes>(S->getSCEVType())) {
10896   case scConstant:
10897     return ProperlyDominatesBlock;
10898   case scTruncate:
10899   case scZeroExtend:
10900   case scSignExtend:
10901     return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
10902   case scAddRecExpr: {
10903     // This uses a "dominates" query instead of "properly dominates" query
10904     // to test for proper dominance too, because the instruction which
10905     // produces the addrec's value is a PHI, and a PHI effectively properly
10906     // dominates its entire containing block.
10907     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
10908     if (!DT.dominates(AR->getLoop()->getHeader(), BB))
10909       return DoesNotDominateBlock;
10910 
10911     // Fall through into SCEVNAryExpr handling.
10912     LLVM_FALLTHROUGH;
10913   }
10914   case scAddExpr:
10915   case scMulExpr:
10916   case scUMaxExpr:
10917   case scSMaxExpr: {
10918     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
10919     bool Proper = true;
10920     for (const SCEV *NAryOp : NAry->operands()) {
10921       BlockDisposition D = getBlockDisposition(NAryOp, BB);
10922       if (D == DoesNotDominateBlock)
10923         return DoesNotDominateBlock;
10924       if (D == DominatesBlock)
10925         Proper = false;
10926     }
10927     return Proper ? ProperlyDominatesBlock : DominatesBlock;
10928   }
10929   case scUDivExpr: {
10930     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
10931     const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
10932     BlockDisposition LD = getBlockDisposition(LHS, BB);
10933     if (LD == DoesNotDominateBlock)
10934       return DoesNotDominateBlock;
10935     BlockDisposition RD = getBlockDisposition(RHS, BB);
10936     if (RD == DoesNotDominateBlock)
10937       return DoesNotDominateBlock;
10938     return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
10939       ProperlyDominatesBlock : DominatesBlock;
10940   }
10941   case scUnknown:
10942     if (Instruction *I =
10943           dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
10944       if (I->getParent() == BB)
10945         return DominatesBlock;
10946       if (DT.properlyDominates(I->getParent(), BB))
10947         return ProperlyDominatesBlock;
10948       return DoesNotDominateBlock;
10949     }
10950     return ProperlyDominatesBlock;
10951   case scCouldNotCompute:
10952     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
10953   }
10954   llvm_unreachable("Unknown SCEV kind!");
10955 }
10956 
10957 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
10958   return getBlockDisposition(S, BB) >= DominatesBlock;
10959 }
10960 
10961 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
10962   return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
10963 }
10964 
10965 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
10966   return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; });
10967 }
10968 
10969 bool ScalarEvolution::ExitLimit::hasOperand(const SCEV *S) const {
10970   auto IsS = [&](const SCEV *X) { return S == X; };
10971   auto ContainsS = [&](const SCEV *X) {
10972     return !isa<SCEVCouldNotCompute>(X) && SCEVExprContains(X, IsS);
10973   };
10974   return ContainsS(ExactNotTaken) || ContainsS(MaxNotTaken);
10975 }
10976 
10977 void
10978 ScalarEvolution::forgetMemoizedResults(const SCEV *S, bool EraseExitLimit) {
10979   ValuesAtScopes.erase(S);
10980   LoopDispositions.erase(S);
10981   BlockDispositions.erase(S);
10982   UnsignedRanges.erase(S);
10983   SignedRanges.erase(S);
10984   ExprValueMap.erase(S);
10985   HasRecMap.erase(S);
10986   MinTrailingZerosCache.erase(S);
10987 
10988   for (auto I = PredicatedSCEVRewrites.begin();
10989        I != PredicatedSCEVRewrites.end();) {
10990     std::pair<const SCEV *, const Loop *> Entry = I->first;
10991     if (Entry.first == S)
10992       PredicatedSCEVRewrites.erase(I++);
10993     else
10994       ++I;
10995   }
10996 
10997   auto RemoveSCEVFromBackedgeMap =
10998       [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
10999         for (auto I = Map.begin(), E = Map.end(); I != E;) {
11000           BackedgeTakenInfo &BEInfo = I->second;
11001           if (BEInfo.hasOperand(S, this)) {
11002             BEInfo.clear();
11003             Map.erase(I++);
11004           } else
11005             ++I;
11006         }
11007       };
11008 
11009   RemoveSCEVFromBackedgeMap(BackedgeTakenCounts);
11010   RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts);
11011 
11012   // TODO: There is a suspicion that we only need to do it when there is a
11013   // SCEVUnknown somewhere inside S. Need to check this.
11014   if (EraseExitLimit)
11015     for (auto I = ExitLimits.begin(), E = ExitLimits.end(); I != E; ++I)
11016       if (I->second.hasOperand(S))
11017         ExitLimits.erase(I);
11018 }
11019 
11020 void ScalarEvolution::verify() const {
11021   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
11022   ScalarEvolution SE2(F, TLI, AC, DT, LI);
11023 
11024   SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end());
11025 
11026   // Map's SCEV expressions from one ScalarEvolution "universe" to another.
11027   struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> {
11028     SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {}
11029 
11030     const SCEV *visitConstant(const SCEVConstant *Constant) {
11031       return SE.getConstant(Constant->getAPInt());
11032     }
11033 
11034     const SCEV *visitUnknown(const SCEVUnknown *Expr) {
11035       return SE.getUnknown(Expr->getValue());
11036     }
11037 
11038     const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
11039       return SE.getCouldNotCompute();
11040     }
11041   };
11042 
11043   SCEVMapper SCM(SE2);
11044 
11045   while (!LoopStack.empty()) {
11046     auto *L = LoopStack.pop_back_val();
11047     LoopStack.insert(LoopStack.end(), L->begin(), L->end());
11048 
11049     auto *CurBECount = SCM.visit(
11050         const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L));
11051     auto *NewBECount = SE2.getBackedgeTakenCount(L);
11052 
11053     if (CurBECount == SE2.getCouldNotCompute() ||
11054         NewBECount == SE2.getCouldNotCompute()) {
11055       // NB! This situation is legal, but is very suspicious -- whatever pass
11056       // change the loop to make a trip count go from could not compute to
11057       // computable or vice-versa *should have* invalidated SCEV.  However, we
11058       // choose not to assert here (for now) since we don't want false
11059       // positives.
11060       continue;
11061     }
11062 
11063     if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) {
11064       // SCEV treats "undef" as an unknown but consistent value (i.e. it does
11065       // not propagate undef aggressively).  This means we can (and do) fail
11066       // verification in cases where a transform makes the trip count of a loop
11067       // go from "undef" to "undef+1" (say).  The transform is fine, since in
11068       // both cases the loop iterates "undef" times, but SCEV thinks we
11069       // increased the trip count of the loop by 1 incorrectly.
11070       continue;
11071     }
11072 
11073     if (SE.getTypeSizeInBits(CurBECount->getType()) >
11074         SE.getTypeSizeInBits(NewBECount->getType()))
11075       NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType());
11076     else if (SE.getTypeSizeInBits(CurBECount->getType()) <
11077              SE.getTypeSizeInBits(NewBECount->getType()))
11078       CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType());
11079 
11080     auto *ConstantDelta =
11081         dyn_cast<SCEVConstant>(SE2.getMinusSCEV(CurBECount, NewBECount));
11082 
11083     if (ConstantDelta && ConstantDelta->getAPInt() != 0) {
11084       dbgs() << "Trip Count Changed!\n";
11085       dbgs() << "Old: " << *CurBECount << "\n";
11086       dbgs() << "New: " << *NewBECount << "\n";
11087       dbgs() << "Delta: " << *ConstantDelta << "\n";
11088       std::abort();
11089     }
11090   }
11091 }
11092 
11093 bool ScalarEvolution::invalidate(
11094     Function &F, const PreservedAnalyses &PA,
11095     FunctionAnalysisManager::Invalidator &Inv) {
11096   // Invalidate the ScalarEvolution object whenever it isn't preserved or one
11097   // of its dependencies is invalidated.
11098   auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
11099   return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
11100          Inv.invalidate<AssumptionAnalysis>(F, PA) ||
11101          Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
11102          Inv.invalidate<LoopAnalysis>(F, PA);
11103 }
11104 
11105 AnalysisKey ScalarEvolutionAnalysis::Key;
11106 
11107 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
11108                                              FunctionAnalysisManager &AM) {
11109   return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F),
11110                          AM.getResult<AssumptionAnalysis>(F),
11111                          AM.getResult<DominatorTreeAnalysis>(F),
11112                          AM.getResult<LoopAnalysis>(F));
11113 }
11114 
11115 PreservedAnalyses
11116 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
11117   AM.getResult<ScalarEvolutionAnalysis>(F).print(OS);
11118   return PreservedAnalyses::all();
11119 }
11120 
11121 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
11122                       "Scalar Evolution Analysis", false, true)
11123 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
11124 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
11125 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
11126 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
11127 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
11128                     "Scalar Evolution Analysis", false, true)
11129 
11130 char ScalarEvolutionWrapperPass::ID = 0;
11131 
11132 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
11133   initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
11134 }
11135 
11136 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
11137   SE.reset(new ScalarEvolution(
11138       F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
11139       getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
11140       getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
11141       getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
11142   return false;
11143 }
11144 
11145 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
11146 
11147 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
11148   SE->print(OS);
11149 }
11150 
11151 void ScalarEvolutionWrapperPass::verifyAnalysis() const {
11152   if (!VerifySCEV)
11153     return;
11154 
11155   SE->verify();
11156 }
11157 
11158 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
11159   AU.setPreservesAll();
11160   AU.addRequiredTransitive<AssumptionCacheTracker>();
11161   AU.addRequiredTransitive<LoopInfoWrapperPass>();
11162   AU.addRequiredTransitive<DominatorTreeWrapperPass>();
11163   AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
11164 }
11165 
11166 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS,
11167                                                         const SCEV *RHS) {
11168   FoldingSetNodeID ID;
11169   assert(LHS->getType() == RHS->getType() &&
11170          "Type mismatch between LHS and RHS");
11171   // Unique this node based on the arguments
11172   ID.AddInteger(SCEVPredicate::P_Equal);
11173   ID.AddPointer(LHS);
11174   ID.AddPointer(RHS);
11175   void *IP = nullptr;
11176   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
11177     return S;
11178   SCEVEqualPredicate *Eq = new (SCEVAllocator)
11179       SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS);
11180   UniquePreds.InsertNode(Eq, IP);
11181   return Eq;
11182 }
11183 
11184 const SCEVPredicate *ScalarEvolution::getWrapPredicate(
11185     const SCEVAddRecExpr *AR,
11186     SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
11187   FoldingSetNodeID ID;
11188   // Unique this node based on the arguments
11189   ID.AddInteger(SCEVPredicate::P_Wrap);
11190   ID.AddPointer(AR);
11191   ID.AddInteger(AddedFlags);
11192   void *IP = nullptr;
11193   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
11194     return S;
11195   auto *OF = new (SCEVAllocator)
11196       SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
11197   UniquePreds.InsertNode(OF, IP);
11198   return OF;
11199 }
11200 
11201 namespace {
11202 
11203 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
11204 public:
11205   SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE,
11206                         SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
11207                         SCEVUnionPredicate *Pred)
11208       : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
11209 
11210   /// Rewrites \p S in the context of a loop L and the SCEV predication
11211   /// infrastructure.
11212   ///
11213   /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
11214   /// equivalences present in \p Pred.
11215   ///
11216   /// If \p NewPreds is non-null, rewrite is free to add further predicates to
11217   /// \p NewPreds such that the result will be an AddRecExpr.
11218   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
11219                              SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
11220                              SCEVUnionPredicate *Pred) {
11221     SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
11222     return Rewriter.visit(S);
11223   }
11224 
11225   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
11226     if (Pred) {
11227       auto ExprPreds = Pred->getPredicatesForExpr(Expr);
11228       for (auto *Pred : ExprPreds)
11229         if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred))
11230           if (IPred->getLHS() == Expr)
11231             return IPred->getRHS();
11232     }
11233     return convertToAddRecWithPreds(Expr);
11234   }
11235 
11236   const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
11237     const SCEV *Operand = visit(Expr->getOperand());
11238     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
11239     if (AR && AR->getLoop() == L && AR->isAffine()) {
11240       // This couldn't be folded because the operand didn't have the nuw
11241       // flag. Add the nusw flag as an assumption that we could make.
11242       const SCEV *Step = AR->getStepRecurrence(SE);
11243       Type *Ty = Expr->getType();
11244       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
11245         return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
11246                                 SE.getSignExtendExpr(Step, Ty), L,
11247                                 AR->getNoWrapFlags());
11248     }
11249     return SE.getZeroExtendExpr(Operand, Expr->getType());
11250   }
11251 
11252   const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
11253     const SCEV *Operand = visit(Expr->getOperand());
11254     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
11255     if (AR && AR->getLoop() == L && AR->isAffine()) {
11256       // This couldn't be folded because the operand didn't have the nsw
11257       // flag. Add the nssw flag as an assumption that we could make.
11258       const SCEV *Step = AR->getStepRecurrence(SE);
11259       Type *Ty = Expr->getType();
11260       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
11261         return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
11262                                 SE.getSignExtendExpr(Step, Ty), L,
11263                                 AR->getNoWrapFlags());
11264     }
11265     return SE.getSignExtendExpr(Operand, Expr->getType());
11266   }
11267 
11268 private:
11269   bool addOverflowAssumption(const SCEVPredicate *P) {
11270     if (!NewPreds) {
11271       // Check if we've already made this assumption.
11272       return Pred && Pred->implies(P);
11273     }
11274     NewPreds->insert(P);
11275     return true;
11276   }
11277 
11278   bool addOverflowAssumption(const SCEVAddRecExpr *AR,
11279                              SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
11280     auto *A = SE.getWrapPredicate(AR, AddedFlags);
11281     return addOverflowAssumption(A);
11282   }
11283 
11284   // If \p Expr represents a PHINode, we try to see if it can be represented
11285   // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible
11286   // to add this predicate as a runtime overflow check, we return the AddRec.
11287   // If \p Expr does not meet these conditions (is not a PHI node, or we
11288   // couldn't create an AddRec for it, or couldn't add the predicate), we just
11289   // return \p Expr.
11290   const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) {
11291     if (!isa<PHINode>(Expr->getValue()))
11292       return Expr;
11293     Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
11294     PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr);
11295     if (!PredicatedRewrite)
11296       return Expr;
11297     for (auto *P : PredicatedRewrite->second){
11298       if (!addOverflowAssumption(P))
11299         return Expr;
11300     }
11301     return PredicatedRewrite->first;
11302   }
11303 
11304   SmallPtrSetImpl<const SCEVPredicate *> *NewPreds;
11305   SCEVUnionPredicate *Pred;
11306   const Loop *L;
11307 };
11308 
11309 } // end anonymous namespace
11310 
11311 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
11312                                                    SCEVUnionPredicate &Preds) {
11313   return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
11314 }
11315 
11316 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates(
11317     const SCEV *S, const Loop *L,
11318     SmallPtrSetImpl<const SCEVPredicate *> &Preds) {
11319   SmallPtrSet<const SCEVPredicate *, 4> TransformPreds;
11320   S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
11321   auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
11322 
11323   if (!AddRec)
11324     return nullptr;
11325 
11326   // Since the transformation was successful, we can now transfer the SCEV
11327   // predicates.
11328   for (auto *P : TransformPreds)
11329     Preds.insert(P);
11330 
11331   return AddRec;
11332 }
11333 
11334 /// SCEV predicates
11335 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
11336                              SCEVPredicateKind Kind)
11337     : FastID(ID), Kind(Kind) {}
11338 
11339 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID,
11340                                        const SCEV *LHS, const SCEV *RHS)
11341     : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {
11342   assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match");
11343   assert(LHS != RHS && "LHS and RHS are the same SCEV");
11344 }
11345 
11346 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const {
11347   const auto *Op = dyn_cast<SCEVEqualPredicate>(N);
11348 
11349   if (!Op)
11350     return false;
11351 
11352   return Op->LHS == LHS && Op->RHS == RHS;
11353 }
11354 
11355 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; }
11356 
11357 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; }
11358 
11359 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const {
11360   OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
11361 }
11362 
11363 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
11364                                      const SCEVAddRecExpr *AR,
11365                                      IncrementWrapFlags Flags)
11366     : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
11367 
11368 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; }
11369 
11370 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const {
11371   const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
11372 
11373   return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags;
11374 }
11375 
11376 bool SCEVWrapPredicate::isAlwaysTrue() const {
11377   SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
11378   IncrementWrapFlags IFlags = Flags;
11379 
11380   if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
11381     IFlags = clearFlags(IFlags, IncrementNSSW);
11382 
11383   return IFlags == IncrementAnyWrap;
11384 }
11385 
11386 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
11387   OS.indent(Depth) << *getExpr() << " Added Flags: ";
11388   if (SCEVWrapPredicate::IncrementNUSW & getFlags())
11389     OS << "<nusw>";
11390   if (SCEVWrapPredicate::IncrementNSSW & getFlags())
11391     OS << "<nssw>";
11392   OS << "\n";
11393 }
11394 
11395 SCEVWrapPredicate::IncrementWrapFlags
11396 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR,
11397                                    ScalarEvolution &SE) {
11398   IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
11399   SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
11400 
11401   // We can safely transfer the NSW flag as NSSW.
11402   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
11403     ImpliedFlags = IncrementNSSW;
11404 
11405   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
11406     // If the increment is positive, the SCEV NUW flag will also imply the
11407     // WrapPredicate NUSW flag.
11408     if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
11409       if (Step->getValue()->getValue().isNonNegative())
11410         ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
11411   }
11412 
11413   return ImpliedFlags;
11414 }
11415 
11416 /// Union predicates don't get cached so create a dummy set ID for it.
11417 SCEVUnionPredicate::SCEVUnionPredicate()
11418     : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {}
11419 
11420 bool SCEVUnionPredicate::isAlwaysTrue() const {
11421   return all_of(Preds,
11422                 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
11423 }
11424 
11425 ArrayRef<const SCEVPredicate *>
11426 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) {
11427   auto I = SCEVToPreds.find(Expr);
11428   if (I == SCEVToPreds.end())
11429     return ArrayRef<const SCEVPredicate *>();
11430   return I->second;
11431 }
11432 
11433 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
11434   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
11435     return all_of(Set->Preds,
11436                   [this](const SCEVPredicate *I) { return this->implies(I); });
11437 
11438   auto ScevPredsIt = SCEVToPreds.find(N->getExpr());
11439   if (ScevPredsIt == SCEVToPreds.end())
11440     return false;
11441   auto &SCEVPreds = ScevPredsIt->second;
11442 
11443   return any_of(SCEVPreds,
11444                 [N](const SCEVPredicate *I) { return I->implies(N); });
11445 }
11446 
11447 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; }
11448 
11449 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
11450   for (auto Pred : Preds)
11451     Pred->print(OS, Depth);
11452 }
11453 
11454 void SCEVUnionPredicate::add(const SCEVPredicate *N) {
11455   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
11456     for (auto Pred : Set->Preds)
11457       add(Pred);
11458     return;
11459   }
11460 
11461   if (implies(N))
11462     return;
11463 
11464   const SCEV *Key = N->getExpr();
11465   assert(Key && "Only SCEVUnionPredicate doesn't have an "
11466                 " associated expression!");
11467 
11468   SCEVToPreds[Key].push_back(N);
11469   Preds.push_back(N);
11470 }
11471 
11472 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
11473                                                      Loop &L)
11474     : SE(SE), L(L) {}
11475 
11476 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
11477   const SCEV *Expr = SE.getSCEV(V);
11478   RewriteEntry &Entry = RewriteMap[Expr];
11479 
11480   // If we already have an entry and the version matches, return it.
11481   if (Entry.second && Generation == Entry.first)
11482     return Entry.second;
11483 
11484   // We found an entry but it's stale. Rewrite the stale entry
11485   // according to the current predicate.
11486   if (Entry.second)
11487     Expr = Entry.second;
11488 
11489   const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds);
11490   Entry = {Generation, NewSCEV};
11491 
11492   return NewSCEV;
11493 }
11494 
11495 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() {
11496   if (!BackedgeCount) {
11497     SCEVUnionPredicate BackedgePred;
11498     BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred);
11499     addPredicate(BackedgePred);
11500   }
11501   return BackedgeCount;
11502 }
11503 
11504 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
11505   if (Preds.implies(&Pred))
11506     return;
11507   Preds.add(&Pred);
11508   updateGeneration();
11509 }
11510 
11511 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const {
11512   return Preds;
11513 }
11514 
11515 void PredicatedScalarEvolution::updateGeneration() {
11516   // If the generation number wrapped recompute everything.
11517   if (++Generation == 0) {
11518     for (auto &II : RewriteMap) {
11519       const SCEV *Rewritten = II.second.second;
11520       II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)};
11521     }
11522   }
11523 }
11524 
11525 void PredicatedScalarEvolution::setNoOverflow(
11526     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
11527   const SCEV *Expr = getSCEV(V);
11528   const auto *AR = cast<SCEVAddRecExpr>(Expr);
11529 
11530   auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE);
11531 
11532   // Clear the statically implied flags.
11533   Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags);
11534   addPredicate(*SE.getWrapPredicate(AR, Flags));
11535 
11536   auto II = FlagsMap.insert({V, Flags});
11537   if (!II.second)
11538     II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second);
11539 }
11540 
11541 bool PredicatedScalarEvolution::hasNoOverflow(
11542     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
11543   const SCEV *Expr = getSCEV(V);
11544   const auto *AR = cast<SCEVAddRecExpr>(Expr);
11545 
11546   Flags = SCEVWrapPredicate::clearFlags(
11547       Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
11548 
11549   auto II = FlagsMap.find(V);
11550 
11551   if (II != FlagsMap.end())
11552     Flags = SCEVWrapPredicate::clearFlags(Flags, II->second);
11553 
11554   return Flags == SCEVWrapPredicate::IncrementAnyWrap;
11555 }
11556 
11557 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) {
11558   const SCEV *Expr = this->getSCEV(V);
11559   SmallPtrSet<const SCEVPredicate *, 4> NewPreds;
11560   auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
11561 
11562   if (!New)
11563     return nullptr;
11564 
11565   for (auto *P : NewPreds)
11566     Preds.add(P);
11567 
11568   updateGeneration();
11569   RewriteMap[SE.getSCEV(V)] = {Generation, New};
11570   return New;
11571 }
11572 
11573 PredicatedScalarEvolution::PredicatedScalarEvolution(
11574     const PredicatedScalarEvolution &Init)
11575     : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds),
11576       Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
11577   for (const auto &I : Init.FlagsMap)
11578     FlagsMap.insert(I);
11579 }
11580 
11581 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const {
11582   // For each block.
11583   for (auto *BB : L.getBlocks())
11584     for (auto &I : *BB) {
11585       if (!SE.isSCEVable(I.getType()))
11586         continue;
11587 
11588       auto *Expr = SE.getSCEV(&I);
11589       auto II = RewriteMap.find(Expr);
11590 
11591       if (II == RewriteMap.end())
11592         continue;
11593 
11594       // Don't print things that are not interesting.
11595       if (II->second.second == Expr)
11596         continue;
11597 
11598       OS.indent(Depth) << "[PSE]" << I << ":\n";
11599       OS.indent(Depth + 2) << *Expr << "\n";
11600       OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
11601     }
11602 }
11603