xref: /llvm-project/llvm/lib/Analysis/ScalarEvolution.cpp (revision 63a3de057eeae94e8c6c68b53b370f5a1611b0fa)
1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains the implementation of the scalar evolution analysis
11 // engine, which is used primarily to analyze expressions involving induction
12 // variables in loops.
13 //
14 // There are several aspects to this library.  First is the representation of
15 // scalar expressions, which are represented as subclasses of the SCEV class.
16 // These classes are used to represent certain types of subexpressions that we
17 // can handle. We only create one SCEV of a particular shape, so
18 // pointer-comparisons for equality are legal.
19 //
20 // One important aspect of the SCEV objects is that they are never cyclic, even
21 // if there is a cycle in the dataflow for an expression (ie, a PHI node).  If
22 // the PHI node is one of the idioms that we can represent (e.g., a polynomial
23 // recurrence) then we represent it directly as a recurrence node, otherwise we
24 // represent it as a SCEVUnknown node.
25 //
26 // In addition to being able to represent expressions of various types, we also
27 // have folders that are used to build the *canonical* representation for a
28 // particular expression.  These folders are capable of using a variety of
29 // rewrite rules to simplify the expressions.
30 //
31 // Once the folders are defined, we can implement the more interesting
32 // higher-level code, such as the code that recognizes PHI nodes of various
33 // types, computes the execution count of a loop, etc.
34 //
35 // TODO: We should use these routines and value representations to implement
36 // dependence analysis!
37 //
38 //===----------------------------------------------------------------------===//
39 //
40 // There are several good references for the techniques used in this analysis.
41 //
42 //  Chains of recurrences -- a method to expedite the evaluation
43 //  of closed-form functions
44 //  Olaf Bachmann, Paul S. Wang, Eugene V. Zima
45 //
46 //  On computational properties of chains of recurrences
47 //  Eugene V. Zima
48 //
49 //  Symbolic Evaluation of Chains of Recurrences for Loop Optimization
50 //  Robert A. van Engelen
51 //
52 //  Efficient Symbolic Analysis for Optimizing Compilers
53 //  Robert A. van Engelen
54 //
55 //  Using the chains of recurrences algebra for data dependence testing and
56 //  induction variable substitution
57 //  MS Thesis, Johnie Birch
58 //
59 //===----------------------------------------------------------------------===//
60 
61 #include "llvm/Analysis/ScalarEvolution.h"
62 #include "llvm/ADT/APInt.h"
63 #include "llvm/ADT/ArrayRef.h"
64 #include "llvm/ADT/DenseMap.h"
65 #include "llvm/ADT/DepthFirstIterator.h"
66 #include "llvm/ADT/EquivalenceClasses.h"
67 #include "llvm/ADT/FoldingSet.h"
68 #include "llvm/ADT/None.h"
69 #include "llvm/ADT/Optional.h"
70 #include "llvm/ADT/STLExtras.h"
71 #include "llvm/ADT/ScopeExit.h"
72 #include "llvm/ADT/Sequence.h"
73 #include "llvm/ADT/SetVector.h"
74 #include "llvm/ADT/SmallPtrSet.h"
75 #include "llvm/ADT/SmallSet.h"
76 #include "llvm/ADT/SmallVector.h"
77 #include "llvm/ADT/Statistic.h"
78 #include "llvm/ADT/StringRef.h"
79 #include "llvm/Analysis/AssumptionCache.h"
80 #include "llvm/Analysis/ConstantFolding.h"
81 #include "llvm/Analysis/InstructionSimplify.h"
82 #include "llvm/Analysis/LoopInfo.h"
83 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
84 #include "llvm/Analysis/TargetLibraryInfo.h"
85 #include "llvm/Analysis/ValueTracking.h"
86 #include "llvm/IR/Argument.h"
87 #include "llvm/IR/BasicBlock.h"
88 #include "llvm/IR/CFG.h"
89 #include "llvm/IR/CallSite.h"
90 #include "llvm/IR/Constant.h"
91 #include "llvm/IR/ConstantRange.h"
92 #include "llvm/IR/Constants.h"
93 #include "llvm/IR/DataLayout.h"
94 #include "llvm/IR/DerivedTypes.h"
95 #include "llvm/IR/Dominators.h"
96 #include "llvm/IR/Function.h"
97 #include "llvm/IR/GlobalAlias.h"
98 #include "llvm/IR/GlobalValue.h"
99 #include "llvm/IR/GlobalVariable.h"
100 #include "llvm/IR/InstIterator.h"
101 #include "llvm/IR/InstrTypes.h"
102 #include "llvm/IR/Instruction.h"
103 #include "llvm/IR/Instructions.h"
104 #include "llvm/IR/IntrinsicInst.h"
105 #include "llvm/IR/Intrinsics.h"
106 #include "llvm/IR/LLVMContext.h"
107 #include "llvm/IR/Metadata.h"
108 #include "llvm/IR/Operator.h"
109 #include "llvm/IR/PatternMatch.h"
110 #include "llvm/IR/Type.h"
111 #include "llvm/IR/Use.h"
112 #include "llvm/IR/User.h"
113 #include "llvm/IR/Value.h"
114 #include "llvm/Pass.h"
115 #include "llvm/Support/Casting.h"
116 #include "llvm/Support/CommandLine.h"
117 #include "llvm/Support/Compiler.h"
118 #include "llvm/Support/Debug.h"
119 #include "llvm/Support/ErrorHandling.h"
120 #include "llvm/Support/KnownBits.h"
121 #include "llvm/Support/SaveAndRestore.h"
122 #include "llvm/Support/raw_ostream.h"
123 #include <algorithm>
124 #include <cassert>
125 #include <climits>
126 #include <cstddef>
127 #include <cstdint>
128 #include <cstdlib>
129 #include <map>
130 #include <memory>
131 #include <tuple>
132 #include <utility>
133 #include <vector>
134 
135 using namespace llvm;
136 
137 #define DEBUG_TYPE "scalar-evolution"
138 
139 STATISTIC(NumArrayLenItCounts,
140           "Number of trip counts computed with array length");
141 STATISTIC(NumTripCountsComputed,
142           "Number of loops with predictable loop counts");
143 STATISTIC(NumTripCountsNotComputed,
144           "Number of loops without predictable loop counts");
145 STATISTIC(NumBruteForceTripCountsComputed,
146           "Number of loops with trip counts computed by force");
147 
148 static cl::opt<unsigned>
149 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
150                         cl::desc("Maximum number of iterations SCEV will "
151                                  "symbolically execute a constant "
152                                  "derived loop"),
153                         cl::init(100));
154 
155 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean.
156 static cl::opt<bool> VerifySCEV(
157     "verify-scev", cl::Hidden,
158     cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
159 static cl::opt<bool>
160     VerifySCEVMap("verify-scev-maps", cl::Hidden,
161                   cl::desc("Verify no dangling value in ScalarEvolution's "
162                            "ExprValueMap (slow)"));
163 
164 static cl::opt<unsigned> MulOpsInlineThreshold(
165     "scev-mulops-inline-threshold", cl::Hidden,
166     cl::desc("Threshold for inlining multiplication operands into a SCEV"),
167     cl::init(32));
168 
169 static cl::opt<unsigned> AddOpsInlineThreshold(
170     "scev-addops-inline-threshold", cl::Hidden,
171     cl::desc("Threshold for inlining addition operands into a SCEV"),
172     cl::init(500));
173 
174 static cl::opt<unsigned> MaxSCEVCompareDepth(
175     "scalar-evolution-max-scev-compare-depth", cl::Hidden,
176     cl::desc("Maximum depth of recursive SCEV complexity comparisons"),
177     cl::init(32));
178 
179 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth(
180     "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden,
181     cl::desc("Maximum depth of recursive SCEV operations implication analysis"),
182     cl::init(2));
183 
184 static cl::opt<unsigned> MaxValueCompareDepth(
185     "scalar-evolution-max-value-compare-depth", cl::Hidden,
186     cl::desc("Maximum depth of recursive value complexity comparisons"),
187     cl::init(2));
188 
189 static cl::opt<unsigned>
190     MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden,
191                   cl::desc("Maximum depth of recursive arithmetics"),
192                   cl::init(32));
193 
194 static cl::opt<unsigned> MaxConstantEvolvingDepth(
195     "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
196     cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
197 
198 static cl::opt<unsigned>
199     MaxExtDepth("scalar-evolution-max-ext-depth", cl::Hidden,
200                 cl::desc("Maximum depth of recursive SExt/ZExt"),
201                 cl::init(8));
202 
203 static cl::opt<unsigned>
204     MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden,
205                   cl::desc("Max coefficients in AddRec during evolving"),
206                   cl::init(16));
207 
208 //===----------------------------------------------------------------------===//
209 //                           SCEV class definitions
210 //===----------------------------------------------------------------------===//
211 
212 //===----------------------------------------------------------------------===//
213 // Implementation of the SCEV class.
214 //
215 
216 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
217 LLVM_DUMP_METHOD void SCEV::dump() const {
218   print(dbgs());
219   dbgs() << '\n';
220 }
221 #endif
222 
223 void SCEV::print(raw_ostream &OS) const {
224   switch (static_cast<SCEVTypes>(getSCEVType())) {
225   case scConstant:
226     cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
227     return;
228   case scTruncate: {
229     const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
230     const SCEV *Op = Trunc->getOperand();
231     OS << "(trunc " << *Op->getType() << " " << *Op << " to "
232        << *Trunc->getType() << ")";
233     return;
234   }
235   case scZeroExtend: {
236     const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
237     const SCEV *Op = ZExt->getOperand();
238     OS << "(zext " << *Op->getType() << " " << *Op << " to "
239        << *ZExt->getType() << ")";
240     return;
241   }
242   case scSignExtend: {
243     const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
244     const SCEV *Op = SExt->getOperand();
245     OS << "(sext " << *Op->getType() << " " << *Op << " to "
246        << *SExt->getType() << ")";
247     return;
248   }
249   case scAddRecExpr: {
250     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
251     OS << "{" << *AR->getOperand(0);
252     for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
253       OS << ",+," << *AR->getOperand(i);
254     OS << "}<";
255     if (AR->hasNoUnsignedWrap())
256       OS << "nuw><";
257     if (AR->hasNoSignedWrap())
258       OS << "nsw><";
259     if (AR->hasNoSelfWrap() &&
260         !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
261       OS << "nw><";
262     AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
263     OS << ">";
264     return;
265   }
266   case scAddExpr:
267   case scMulExpr:
268   case scUMaxExpr:
269   case scSMaxExpr: {
270     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
271     const char *OpStr = nullptr;
272     switch (NAry->getSCEVType()) {
273     case scAddExpr: OpStr = " + "; break;
274     case scMulExpr: OpStr = " * "; break;
275     case scUMaxExpr: OpStr = " umax "; break;
276     case scSMaxExpr: OpStr = " smax "; break;
277     }
278     OS << "(";
279     for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
280          I != E; ++I) {
281       OS << **I;
282       if (std::next(I) != E)
283         OS << OpStr;
284     }
285     OS << ")";
286     switch (NAry->getSCEVType()) {
287     case scAddExpr:
288     case scMulExpr:
289       if (NAry->hasNoUnsignedWrap())
290         OS << "<nuw>";
291       if (NAry->hasNoSignedWrap())
292         OS << "<nsw>";
293     }
294     return;
295   }
296   case scUDivExpr: {
297     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
298     OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
299     return;
300   }
301   case scUnknown: {
302     const SCEVUnknown *U = cast<SCEVUnknown>(this);
303     Type *AllocTy;
304     if (U->isSizeOf(AllocTy)) {
305       OS << "sizeof(" << *AllocTy << ")";
306       return;
307     }
308     if (U->isAlignOf(AllocTy)) {
309       OS << "alignof(" << *AllocTy << ")";
310       return;
311     }
312 
313     Type *CTy;
314     Constant *FieldNo;
315     if (U->isOffsetOf(CTy, FieldNo)) {
316       OS << "offsetof(" << *CTy << ", ";
317       FieldNo->printAsOperand(OS, false);
318       OS << ")";
319       return;
320     }
321 
322     // Otherwise just print it normally.
323     U->getValue()->printAsOperand(OS, false);
324     return;
325   }
326   case scCouldNotCompute:
327     OS << "***COULDNOTCOMPUTE***";
328     return;
329   }
330   llvm_unreachable("Unknown SCEV kind!");
331 }
332 
333 Type *SCEV::getType() const {
334   switch (static_cast<SCEVTypes>(getSCEVType())) {
335   case scConstant:
336     return cast<SCEVConstant>(this)->getType();
337   case scTruncate:
338   case scZeroExtend:
339   case scSignExtend:
340     return cast<SCEVCastExpr>(this)->getType();
341   case scAddRecExpr:
342   case scMulExpr:
343   case scUMaxExpr:
344   case scSMaxExpr:
345     return cast<SCEVNAryExpr>(this)->getType();
346   case scAddExpr:
347     return cast<SCEVAddExpr>(this)->getType();
348   case scUDivExpr:
349     return cast<SCEVUDivExpr>(this)->getType();
350   case scUnknown:
351     return cast<SCEVUnknown>(this)->getType();
352   case scCouldNotCompute:
353     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
354   }
355   llvm_unreachable("Unknown SCEV kind!");
356 }
357 
358 bool SCEV::isZero() const {
359   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
360     return SC->getValue()->isZero();
361   return false;
362 }
363 
364 bool SCEV::isOne() const {
365   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
366     return SC->getValue()->isOne();
367   return false;
368 }
369 
370 bool SCEV::isAllOnesValue() const {
371   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
372     return SC->getValue()->isMinusOne();
373   return false;
374 }
375 
376 bool SCEV::isNonConstantNegative() const {
377   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
378   if (!Mul) return false;
379 
380   // If there is a constant factor, it will be first.
381   const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
382   if (!SC) return false;
383 
384   // Return true if the value is negative, this matches things like (-42 * V).
385   return SC->getAPInt().isNegative();
386 }
387 
388 SCEVCouldNotCompute::SCEVCouldNotCompute() :
389   SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {}
390 
391 bool SCEVCouldNotCompute::classof(const SCEV *S) {
392   return S->getSCEVType() == scCouldNotCompute;
393 }
394 
395 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
396   FoldingSetNodeID ID;
397   ID.AddInteger(scConstant);
398   ID.AddPointer(V);
399   void *IP = nullptr;
400   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
401   SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
402   UniqueSCEVs.InsertNode(S, IP);
403   return S;
404 }
405 
406 const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
407   return getConstant(ConstantInt::get(getContext(), Val));
408 }
409 
410 const SCEV *
411 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
412   IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
413   return getConstant(ConstantInt::get(ITy, V, isSigned));
414 }
415 
416 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
417                            unsigned SCEVTy, const SCEV *op, Type *ty)
418   : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
419 
420 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
421                                    const SCEV *op, Type *ty)
422   : SCEVCastExpr(ID, scTruncate, op, ty) {
423   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
424          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
425          "Cannot truncate non-integer value!");
426 }
427 
428 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
429                                        const SCEV *op, Type *ty)
430   : SCEVCastExpr(ID, scZeroExtend, op, ty) {
431   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
432          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
433          "Cannot zero extend non-integer value!");
434 }
435 
436 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
437                                        const SCEV *op, Type *ty)
438   : SCEVCastExpr(ID, scSignExtend, op, ty) {
439   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
440          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
441          "Cannot sign extend non-integer value!");
442 }
443 
444 void SCEVUnknown::deleted() {
445   // Clear this SCEVUnknown from various maps.
446   SE->forgetMemoizedResults(this);
447 
448   // Remove this SCEVUnknown from the uniquing map.
449   SE->UniqueSCEVs.RemoveNode(this);
450 
451   // Release the value.
452   setValPtr(nullptr);
453 }
454 
455 void SCEVUnknown::allUsesReplacedWith(Value *New) {
456   // Remove this SCEVUnknown from the uniquing map.
457   SE->UniqueSCEVs.RemoveNode(this);
458 
459   // Update this SCEVUnknown to point to the new value. This is needed
460   // because there may still be outstanding SCEVs which still point to
461   // this SCEVUnknown.
462   setValPtr(New);
463 }
464 
465 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
466   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
467     if (VCE->getOpcode() == Instruction::PtrToInt)
468       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
469         if (CE->getOpcode() == Instruction::GetElementPtr &&
470             CE->getOperand(0)->isNullValue() &&
471             CE->getNumOperands() == 2)
472           if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
473             if (CI->isOne()) {
474               AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
475                                  ->getElementType();
476               return true;
477             }
478 
479   return false;
480 }
481 
482 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
483   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
484     if (VCE->getOpcode() == Instruction::PtrToInt)
485       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
486         if (CE->getOpcode() == Instruction::GetElementPtr &&
487             CE->getOperand(0)->isNullValue()) {
488           Type *Ty =
489             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
490           if (StructType *STy = dyn_cast<StructType>(Ty))
491             if (!STy->isPacked() &&
492                 CE->getNumOperands() == 3 &&
493                 CE->getOperand(1)->isNullValue()) {
494               if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
495                 if (CI->isOne() &&
496                     STy->getNumElements() == 2 &&
497                     STy->getElementType(0)->isIntegerTy(1)) {
498                   AllocTy = STy->getElementType(1);
499                   return true;
500                 }
501             }
502         }
503 
504   return false;
505 }
506 
507 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
508   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
509     if (VCE->getOpcode() == Instruction::PtrToInt)
510       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
511         if (CE->getOpcode() == Instruction::GetElementPtr &&
512             CE->getNumOperands() == 3 &&
513             CE->getOperand(0)->isNullValue() &&
514             CE->getOperand(1)->isNullValue()) {
515           Type *Ty =
516             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
517           // Ignore vector types here so that ScalarEvolutionExpander doesn't
518           // emit getelementptrs that index into vectors.
519           if (Ty->isStructTy() || Ty->isArrayTy()) {
520             CTy = Ty;
521             FieldNo = CE->getOperand(2);
522             return true;
523           }
524         }
525 
526   return false;
527 }
528 
529 //===----------------------------------------------------------------------===//
530 //                               SCEV Utilities
531 //===----------------------------------------------------------------------===//
532 
533 /// Compare the two values \p LV and \p RV in terms of their "complexity" where
534 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order
535 /// operands in SCEV expressions.  \p EqCache is a set of pairs of values that
536 /// have been previously deemed to be "equally complex" by this routine.  It is
537 /// intended to avoid exponential time complexity in cases like:
538 ///
539 ///   %a = f(%x, %y)
540 ///   %b = f(%a, %a)
541 ///   %c = f(%b, %b)
542 ///
543 ///   %d = f(%x, %y)
544 ///   %e = f(%d, %d)
545 ///   %f = f(%e, %e)
546 ///
547 ///   CompareValueComplexity(%f, %c)
548 ///
549 /// Since we do not continue running this routine on expression trees once we
550 /// have seen unequal values, there is no need to track them in the cache.
551 static int
552 CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue,
553                        const LoopInfo *const LI, Value *LV, Value *RV,
554                        unsigned Depth) {
555   if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV))
556     return 0;
557 
558   // Order pointer values after integer values. This helps SCEVExpander form
559   // GEPs.
560   bool LIsPointer = LV->getType()->isPointerTy(),
561        RIsPointer = RV->getType()->isPointerTy();
562   if (LIsPointer != RIsPointer)
563     return (int)LIsPointer - (int)RIsPointer;
564 
565   // Compare getValueID values.
566   unsigned LID = LV->getValueID(), RID = RV->getValueID();
567   if (LID != RID)
568     return (int)LID - (int)RID;
569 
570   // Sort arguments by their position.
571   if (const auto *LA = dyn_cast<Argument>(LV)) {
572     const auto *RA = cast<Argument>(RV);
573     unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
574     return (int)LArgNo - (int)RArgNo;
575   }
576 
577   if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
578     const auto *RGV = cast<GlobalValue>(RV);
579 
580     const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
581       auto LT = GV->getLinkage();
582       return !(GlobalValue::isPrivateLinkage(LT) ||
583                GlobalValue::isInternalLinkage(LT));
584     };
585 
586     // Use the names to distinguish the two values, but only if the
587     // names are semantically important.
588     if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
589       return LGV->getName().compare(RGV->getName());
590   }
591 
592   // For instructions, compare their loop depth, and their operand count.  This
593   // is pretty loose.
594   if (const auto *LInst = dyn_cast<Instruction>(LV)) {
595     const auto *RInst = cast<Instruction>(RV);
596 
597     // Compare loop depths.
598     const BasicBlock *LParent = LInst->getParent(),
599                      *RParent = RInst->getParent();
600     if (LParent != RParent) {
601       unsigned LDepth = LI->getLoopDepth(LParent),
602                RDepth = LI->getLoopDepth(RParent);
603       if (LDepth != RDepth)
604         return (int)LDepth - (int)RDepth;
605     }
606 
607     // Compare the number of operands.
608     unsigned LNumOps = LInst->getNumOperands(),
609              RNumOps = RInst->getNumOperands();
610     if (LNumOps != RNumOps)
611       return (int)LNumOps - (int)RNumOps;
612 
613     for (unsigned Idx : seq(0u, LNumOps)) {
614       int Result =
615           CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx),
616                                  RInst->getOperand(Idx), Depth + 1);
617       if (Result != 0)
618         return Result;
619     }
620   }
621 
622   EqCacheValue.unionSets(LV, RV);
623   return 0;
624 }
625 
626 // Return negative, zero, or positive, if LHS is less than, equal to, or greater
627 // than RHS, respectively. A three-way result allows recursive comparisons to be
628 // more efficient.
629 static int CompareSCEVComplexity(
630     EquivalenceClasses<const SCEV *> &EqCacheSCEV,
631     EquivalenceClasses<const Value *> &EqCacheValue,
632     const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS,
633     DominatorTree &DT, unsigned Depth = 0) {
634   // Fast-path: SCEVs are uniqued so we can do a quick equality check.
635   if (LHS == RHS)
636     return 0;
637 
638   // Primarily, sort the SCEVs by their getSCEVType().
639   unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
640   if (LType != RType)
641     return (int)LType - (int)RType;
642 
643   if (Depth > MaxSCEVCompareDepth || EqCacheSCEV.isEquivalent(LHS, RHS))
644     return 0;
645   // Aside from the getSCEVType() ordering, the particular ordering
646   // isn't very important except that it's beneficial to be consistent,
647   // so that (a + b) and (b + a) don't end up as different expressions.
648   switch (static_cast<SCEVTypes>(LType)) {
649   case scUnknown: {
650     const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
651     const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
652 
653     int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(),
654                                    RU->getValue(), Depth + 1);
655     if (X == 0)
656       EqCacheSCEV.unionSets(LHS, RHS);
657     return X;
658   }
659 
660   case scConstant: {
661     const SCEVConstant *LC = cast<SCEVConstant>(LHS);
662     const SCEVConstant *RC = cast<SCEVConstant>(RHS);
663 
664     // Compare constant values.
665     const APInt &LA = LC->getAPInt();
666     const APInt &RA = RC->getAPInt();
667     unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
668     if (LBitWidth != RBitWidth)
669       return (int)LBitWidth - (int)RBitWidth;
670     return LA.ult(RA) ? -1 : 1;
671   }
672 
673   case scAddRecExpr: {
674     const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
675     const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
676 
677     // There is always a dominance between two recs that are used by one SCEV,
678     // so we can safely sort recs by loop header dominance. We require such
679     // order in getAddExpr.
680     const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
681     if (LLoop != RLoop) {
682       const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
683       assert(LHead != RHead && "Two loops share the same header?");
684       if (DT.dominates(LHead, RHead))
685         return 1;
686       else
687         assert(DT.dominates(RHead, LHead) &&
688                "No dominance between recurrences used by one SCEV?");
689       return -1;
690     }
691 
692     // Addrec complexity grows with operand count.
693     unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
694     if (LNumOps != RNumOps)
695       return (int)LNumOps - (int)RNumOps;
696 
697     // Compare NoWrap flags.
698     if (LA->getNoWrapFlags() != RA->getNoWrapFlags())
699       return (int)LA->getNoWrapFlags() - (int)RA->getNoWrapFlags();
700 
701     // Lexicographically compare.
702     for (unsigned i = 0; i != LNumOps; ++i) {
703       int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
704                                     LA->getOperand(i), RA->getOperand(i), DT,
705                                     Depth + 1);
706       if (X != 0)
707         return X;
708     }
709     EqCacheSCEV.unionSets(LHS, RHS);
710     return 0;
711   }
712 
713   case scAddExpr:
714   case scMulExpr:
715   case scSMaxExpr:
716   case scUMaxExpr: {
717     const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
718     const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
719 
720     // Lexicographically compare n-ary expressions.
721     unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
722     if (LNumOps != RNumOps)
723       return (int)LNumOps - (int)RNumOps;
724 
725     // Compare NoWrap flags.
726     if (LC->getNoWrapFlags() != RC->getNoWrapFlags())
727       return (int)LC->getNoWrapFlags() - (int)RC->getNoWrapFlags();
728 
729     for (unsigned i = 0; i != LNumOps; ++i) {
730       int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
731                                     LC->getOperand(i), RC->getOperand(i), DT,
732                                     Depth + 1);
733       if (X != 0)
734         return X;
735     }
736     EqCacheSCEV.unionSets(LHS, RHS);
737     return 0;
738   }
739 
740   case scUDivExpr: {
741     const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
742     const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
743 
744     // Lexicographically compare udiv expressions.
745     int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(),
746                                   RC->getLHS(), DT, Depth + 1);
747     if (X != 0)
748       return X;
749     X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(),
750                               RC->getRHS(), DT, Depth + 1);
751     if (X == 0)
752       EqCacheSCEV.unionSets(LHS, RHS);
753     return X;
754   }
755 
756   case scTruncate:
757   case scZeroExtend:
758   case scSignExtend: {
759     const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
760     const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
761 
762     // Compare cast expressions by operand.
763     int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
764                                   LC->getOperand(), RC->getOperand(), DT,
765                                   Depth + 1);
766     if (X == 0)
767       EqCacheSCEV.unionSets(LHS, RHS);
768     return X;
769   }
770 
771   case scCouldNotCompute:
772     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
773   }
774   llvm_unreachable("Unknown SCEV kind!");
775 }
776 
777 /// Given a list of SCEV objects, order them by their complexity, and group
778 /// objects of the same complexity together by value.  When this routine is
779 /// finished, we know that any duplicates in the vector are consecutive and that
780 /// complexity is monotonically increasing.
781 ///
782 /// Note that we go take special precautions to ensure that we get deterministic
783 /// results from this routine.  In other words, we don't want the results of
784 /// this to depend on where the addresses of various SCEV objects happened to
785 /// land in memory.
786 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
787                               LoopInfo *LI, DominatorTree &DT) {
788   if (Ops.size() < 2) return;  // Noop
789 
790   EquivalenceClasses<const SCEV *> EqCacheSCEV;
791   EquivalenceClasses<const Value *> EqCacheValue;
792   if (Ops.size() == 2) {
793     // This is the common case, which also happens to be trivially simple.
794     // Special case it.
795     const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
796     if (CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, RHS, LHS, DT) < 0)
797       std::swap(LHS, RHS);
798     return;
799   }
800 
801   // Do the rough sort by complexity.
802   std::stable_sort(Ops.begin(), Ops.end(),
803                    [&](const SCEV *LHS, const SCEV *RHS) {
804                      return CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
805                                                   LHS, RHS, DT) < 0;
806                    });
807 
808   // Now that we are sorted by complexity, group elements of the same
809   // complexity.  Note that this is, at worst, N^2, but the vector is likely to
810   // be extremely short in practice.  Note that we take this approach because we
811   // do not want to depend on the addresses of the objects we are grouping.
812   for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
813     const SCEV *S = Ops[i];
814     unsigned Complexity = S->getSCEVType();
815 
816     // If there are any objects of the same complexity and same value as this
817     // one, group them.
818     for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
819       if (Ops[j] == S) { // Found a duplicate.
820         // Move it to immediately after i'th element.
821         std::swap(Ops[i+1], Ops[j]);
822         ++i;   // no need to rescan it.
823         if (i == e-2) return;  // Done!
824       }
825     }
826   }
827 }
828 
829 // Returns the size of the SCEV S.
830 static inline int sizeOfSCEV(const SCEV *S) {
831   struct FindSCEVSize {
832     int Size = 0;
833 
834     FindSCEVSize() = default;
835 
836     bool follow(const SCEV *S) {
837       ++Size;
838       // Keep looking at all operands of S.
839       return true;
840     }
841 
842     bool isDone() const {
843       return false;
844     }
845   };
846 
847   FindSCEVSize F;
848   SCEVTraversal<FindSCEVSize> ST(F);
849   ST.visitAll(S);
850   return F.Size;
851 }
852 
853 namespace {
854 
855 struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> {
856 public:
857   // Computes the Quotient and Remainder of the division of Numerator by
858   // Denominator.
859   static void divide(ScalarEvolution &SE, const SCEV *Numerator,
860                      const SCEV *Denominator, const SCEV **Quotient,
861                      const SCEV **Remainder) {
862     assert(Numerator && Denominator && "Uninitialized SCEV");
863 
864     SCEVDivision D(SE, Numerator, Denominator);
865 
866     // Check for the trivial case here to avoid having to check for it in the
867     // rest of the code.
868     if (Numerator == Denominator) {
869       *Quotient = D.One;
870       *Remainder = D.Zero;
871       return;
872     }
873 
874     if (Numerator->isZero()) {
875       *Quotient = D.Zero;
876       *Remainder = D.Zero;
877       return;
878     }
879 
880     // A simple case when N/1. The quotient is N.
881     if (Denominator->isOne()) {
882       *Quotient = Numerator;
883       *Remainder = D.Zero;
884       return;
885     }
886 
887     // Split the Denominator when it is a product.
888     if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) {
889       const SCEV *Q, *R;
890       *Quotient = Numerator;
891       for (const SCEV *Op : T->operands()) {
892         divide(SE, *Quotient, Op, &Q, &R);
893         *Quotient = Q;
894 
895         // Bail out when the Numerator is not divisible by one of the terms of
896         // the Denominator.
897         if (!R->isZero()) {
898           *Quotient = D.Zero;
899           *Remainder = Numerator;
900           return;
901         }
902       }
903       *Remainder = D.Zero;
904       return;
905     }
906 
907     D.visit(Numerator);
908     *Quotient = D.Quotient;
909     *Remainder = D.Remainder;
910   }
911 
912   // Except in the trivial case described above, we do not know how to divide
913   // Expr by Denominator for the following functions with empty implementation.
914   void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {}
915   void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {}
916   void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {}
917   void visitUDivExpr(const SCEVUDivExpr *Numerator) {}
918   void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {}
919   void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {}
920   void visitUnknown(const SCEVUnknown *Numerator) {}
921   void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {}
922 
923   void visitConstant(const SCEVConstant *Numerator) {
924     if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) {
925       APInt NumeratorVal = Numerator->getAPInt();
926       APInt DenominatorVal = D->getAPInt();
927       uint32_t NumeratorBW = NumeratorVal.getBitWidth();
928       uint32_t DenominatorBW = DenominatorVal.getBitWidth();
929 
930       if (NumeratorBW > DenominatorBW)
931         DenominatorVal = DenominatorVal.sext(NumeratorBW);
932       else if (NumeratorBW < DenominatorBW)
933         NumeratorVal = NumeratorVal.sext(DenominatorBW);
934 
935       APInt QuotientVal(NumeratorVal.getBitWidth(), 0);
936       APInt RemainderVal(NumeratorVal.getBitWidth(), 0);
937       APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal);
938       Quotient = SE.getConstant(QuotientVal);
939       Remainder = SE.getConstant(RemainderVal);
940       return;
941     }
942   }
943 
944   void visitAddRecExpr(const SCEVAddRecExpr *Numerator) {
945     const SCEV *StartQ, *StartR, *StepQ, *StepR;
946     if (!Numerator->isAffine())
947       return cannotDivide(Numerator);
948     divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR);
949     divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR);
950     // Bail out if the types do not match.
951     Type *Ty = Denominator->getType();
952     if (Ty != StartQ->getType() || Ty != StartR->getType() ||
953         Ty != StepQ->getType() || Ty != StepR->getType())
954       return cannotDivide(Numerator);
955     Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(),
956                                 Numerator->getNoWrapFlags());
957     Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(),
958                                  Numerator->getNoWrapFlags());
959   }
960 
961   void visitAddExpr(const SCEVAddExpr *Numerator) {
962     SmallVector<const SCEV *, 2> Qs, Rs;
963     Type *Ty = Denominator->getType();
964 
965     for (const SCEV *Op : Numerator->operands()) {
966       const SCEV *Q, *R;
967       divide(SE, Op, Denominator, &Q, &R);
968 
969       // Bail out if types do not match.
970       if (Ty != Q->getType() || Ty != R->getType())
971         return cannotDivide(Numerator);
972 
973       Qs.push_back(Q);
974       Rs.push_back(R);
975     }
976 
977     if (Qs.size() == 1) {
978       Quotient = Qs[0];
979       Remainder = Rs[0];
980       return;
981     }
982 
983     Quotient = SE.getAddExpr(Qs);
984     Remainder = SE.getAddExpr(Rs);
985   }
986 
987   void visitMulExpr(const SCEVMulExpr *Numerator) {
988     SmallVector<const SCEV *, 2> Qs;
989     Type *Ty = Denominator->getType();
990 
991     bool FoundDenominatorTerm = false;
992     for (const SCEV *Op : Numerator->operands()) {
993       // Bail out if types do not match.
994       if (Ty != Op->getType())
995         return cannotDivide(Numerator);
996 
997       if (FoundDenominatorTerm) {
998         Qs.push_back(Op);
999         continue;
1000       }
1001 
1002       // Check whether Denominator divides one of the product operands.
1003       const SCEV *Q, *R;
1004       divide(SE, Op, Denominator, &Q, &R);
1005       if (!R->isZero()) {
1006         Qs.push_back(Op);
1007         continue;
1008       }
1009 
1010       // Bail out if types do not match.
1011       if (Ty != Q->getType())
1012         return cannotDivide(Numerator);
1013 
1014       FoundDenominatorTerm = true;
1015       Qs.push_back(Q);
1016     }
1017 
1018     if (FoundDenominatorTerm) {
1019       Remainder = Zero;
1020       if (Qs.size() == 1)
1021         Quotient = Qs[0];
1022       else
1023         Quotient = SE.getMulExpr(Qs);
1024       return;
1025     }
1026 
1027     if (!isa<SCEVUnknown>(Denominator))
1028       return cannotDivide(Numerator);
1029 
1030     // The Remainder is obtained by replacing Denominator by 0 in Numerator.
1031     ValueToValueMap RewriteMap;
1032     RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
1033         cast<SCEVConstant>(Zero)->getValue();
1034     Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
1035 
1036     if (Remainder->isZero()) {
1037       // The Quotient is obtained by replacing Denominator by 1 in Numerator.
1038       RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
1039           cast<SCEVConstant>(One)->getValue();
1040       Quotient =
1041           SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
1042       return;
1043     }
1044 
1045     // Quotient is (Numerator - Remainder) divided by Denominator.
1046     const SCEV *Q, *R;
1047     const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder);
1048     // This SCEV does not seem to simplify: fail the division here.
1049     if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator))
1050       return cannotDivide(Numerator);
1051     divide(SE, Diff, Denominator, &Q, &R);
1052     if (R != Zero)
1053       return cannotDivide(Numerator);
1054     Quotient = Q;
1055   }
1056 
1057 private:
1058   SCEVDivision(ScalarEvolution &S, const SCEV *Numerator,
1059                const SCEV *Denominator)
1060       : SE(S), Denominator(Denominator) {
1061     Zero = SE.getZero(Denominator->getType());
1062     One = SE.getOne(Denominator->getType());
1063 
1064     // We generally do not know how to divide Expr by Denominator. We
1065     // initialize the division to a "cannot divide" state to simplify the rest
1066     // of the code.
1067     cannotDivide(Numerator);
1068   }
1069 
1070   // Convenience function for giving up on the division. We set the quotient to
1071   // be equal to zero and the remainder to be equal to the numerator.
1072   void cannotDivide(const SCEV *Numerator) {
1073     Quotient = Zero;
1074     Remainder = Numerator;
1075   }
1076 
1077   ScalarEvolution &SE;
1078   const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One;
1079 };
1080 
1081 } // end anonymous namespace
1082 
1083 //===----------------------------------------------------------------------===//
1084 //                      Simple SCEV method implementations
1085 //===----------------------------------------------------------------------===//
1086 
1087 /// Compute BC(It, K).  The result has width W.  Assume, K > 0.
1088 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
1089                                        ScalarEvolution &SE,
1090                                        Type *ResultTy) {
1091   // Handle the simplest case efficiently.
1092   if (K == 1)
1093     return SE.getTruncateOrZeroExtend(It, ResultTy);
1094 
1095   // We are using the following formula for BC(It, K):
1096   //
1097   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
1098   //
1099   // Suppose, W is the bitwidth of the return value.  We must be prepared for
1100   // overflow.  Hence, we must assure that the result of our computation is
1101   // equal to the accurate one modulo 2^W.  Unfortunately, division isn't
1102   // safe in modular arithmetic.
1103   //
1104   // However, this code doesn't use exactly that formula; the formula it uses
1105   // is something like the following, where T is the number of factors of 2 in
1106   // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
1107   // exponentiation:
1108   //
1109   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
1110   //
1111   // This formula is trivially equivalent to the previous formula.  However,
1112   // this formula can be implemented much more efficiently.  The trick is that
1113   // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
1114   // arithmetic.  To do exact division in modular arithmetic, all we have
1115   // to do is multiply by the inverse.  Therefore, this step can be done at
1116   // width W.
1117   //
1118   // The next issue is how to safely do the division by 2^T.  The way this
1119   // is done is by doing the multiplication step at a width of at least W + T
1120   // bits.  This way, the bottom W+T bits of the product are accurate. Then,
1121   // when we perform the division by 2^T (which is equivalent to a right shift
1122   // by T), the bottom W bits are accurate.  Extra bits are okay; they'll get
1123   // truncated out after the division by 2^T.
1124   //
1125   // In comparison to just directly using the first formula, this technique
1126   // is much more efficient; using the first formula requires W * K bits,
1127   // but this formula less than W + K bits. Also, the first formula requires
1128   // a division step, whereas this formula only requires multiplies and shifts.
1129   //
1130   // It doesn't matter whether the subtraction step is done in the calculation
1131   // width or the input iteration count's width; if the subtraction overflows,
1132   // the result must be zero anyway.  We prefer here to do it in the width of
1133   // the induction variable because it helps a lot for certain cases; CodeGen
1134   // isn't smart enough to ignore the overflow, which leads to much less
1135   // efficient code if the width of the subtraction is wider than the native
1136   // register width.
1137   //
1138   // (It's possible to not widen at all by pulling out factors of 2 before
1139   // the multiplication; for example, K=2 can be calculated as
1140   // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
1141   // extra arithmetic, so it's not an obvious win, and it gets
1142   // much more complicated for K > 3.)
1143 
1144   // Protection from insane SCEVs; this bound is conservative,
1145   // but it probably doesn't matter.
1146   if (K > 1000)
1147     return SE.getCouldNotCompute();
1148 
1149   unsigned W = SE.getTypeSizeInBits(ResultTy);
1150 
1151   // Calculate K! / 2^T and T; we divide out the factors of two before
1152   // multiplying for calculating K! / 2^T to avoid overflow.
1153   // Other overflow doesn't matter because we only care about the bottom
1154   // W bits of the result.
1155   APInt OddFactorial(W, 1);
1156   unsigned T = 1;
1157   for (unsigned i = 3; i <= K; ++i) {
1158     APInt Mult(W, i);
1159     unsigned TwoFactors = Mult.countTrailingZeros();
1160     T += TwoFactors;
1161     Mult.lshrInPlace(TwoFactors);
1162     OddFactorial *= Mult;
1163   }
1164 
1165   // We need at least W + T bits for the multiplication step
1166   unsigned CalculationBits = W + T;
1167 
1168   // Calculate 2^T, at width T+W.
1169   APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
1170 
1171   // Calculate the multiplicative inverse of K! / 2^T;
1172   // this multiplication factor will perform the exact division by
1173   // K! / 2^T.
1174   APInt Mod = APInt::getSignedMinValue(W+1);
1175   APInt MultiplyFactor = OddFactorial.zext(W+1);
1176   MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
1177   MultiplyFactor = MultiplyFactor.trunc(W);
1178 
1179   // Calculate the product, at width T+W
1180   IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
1181                                                       CalculationBits);
1182   const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
1183   for (unsigned i = 1; i != K; ++i) {
1184     const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
1185     Dividend = SE.getMulExpr(Dividend,
1186                              SE.getTruncateOrZeroExtend(S, CalculationTy));
1187   }
1188 
1189   // Divide by 2^T
1190   const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
1191 
1192   // Truncate the result, and divide by K! / 2^T.
1193 
1194   return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1195                        SE.getTruncateOrZeroExtend(DivResult, ResultTy));
1196 }
1197 
1198 /// Return the value of this chain of recurrences at the specified iteration
1199 /// number.  We can evaluate this recurrence by multiplying each element in the
1200 /// chain by the binomial coefficient corresponding to it.  In other words, we
1201 /// can evaluate {A,+,B,+,C,+,D} as:
1202 ///
1203 ///   A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
1204 ///
1205 /// where BC(It, k) stands for binomial coefficient.
1206 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
1207                                                 ScalarEvolution &SE) const {
1208   const SCEV *Result = getStart();
1209   for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1210     // The computation is correct in the face of overflow provided that the
1211     // multiplication is performed _after_ the evaluation of the binomial
1212     // coefficient.
1213     const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
1214     if (isa<SCEVCouldNotCompute>(Coeff))
1215       return Coeff;
1216 
1217     Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
1218   }
1219   return Result;
1220 }
1221 
1222 //===----------------------------------------------------------------------===//
1223 //                    SCEV Expression folder implementations
1224 //===----------------------------------------------------------------------===//
1225 
1226 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
1227                                              Type *Ty) {
1228   assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1229          "This is not a truncating conversion!");
1230   assert(isSCEVable(Ty) &&
1231          "This is not a conversion to a SCEVable type!");
1232   Ty = getEffectiveSCEVType(Ty);
1233 
1234   FoldingSetNodeID ID;
1235   ID.AddInteger(scTruncate);
1236   ID.AddPointer(Op);
1237   ID.AddPointer(Ty);
1238   void *IP = nullptr;
1239   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1240 
1241   // Fold if the operand is constant.
1242   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1243     return getConstant(
1244       cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1245 
1246   // trunc(trunc(x)) --> trunc(x)
1247   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
1248     return getTruncateExpr(ST->getOperand(), Ty);
1249 
1250   // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1251   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1252     return getTruncateOrSignExtend(SS->getOperand(), Ty);
1253 
1254   // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1255   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1256     return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
1257 
1258   // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can
1259   // eliminate all the truncates, or we replace other casts with truncates.
1260   if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) {
1261     SmallVector<const SCEV *, 4> Operands;
1262     bool hasTrunc = false;
1263     for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) {
1264       const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty);
1265       if (!isa<SCEVCastExpr>(SA->getOperand(i)))
1266         hasTrunc = isa<SCEVTruncateExpr>(S);
1267       Operands.push_back(S);
1268     }
1269     if (!hasTrunc)
1270       return getAddExpr(Operands);
1271     UniqueSCEVs.FindNodeOrInsertPos(ID, IP);  // Mutates IP, returns NULL.
1272   }
1273 
1274   // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can
1275   // eliminate all the truncates, or we replace other casts with truncates.
1276   if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) {
1277     SmallVector<const SCEV *, 4> Operands;
1278     bool hasTrunc = false;
1279     for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) {
1280       const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty);
1281       if (!isa<SCEVCastExpr>(SM->getOperand(i)))
1282         hasTrunc = isa<SCEVTruncateExpr>(S);
1283       Operands.push_back(S);
1284     }
1285     if (!hasTrunc)
1286       return getMulExpr(Operands);
1287     UniqueSCEVs.FindNodeOrInsertPos(ID, IP);  // Mutates IP, returns NULL.
1288   }
1289 
1290   // If the input value is a chrec scev, truncate the chrec's operands.
1291   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1292     SmallVector<const SCEV *, 4> Operands;
1293     for (const SCEV *Op : AddRec->operands())
1294       Operands.push_back(getTruncateExpr(Op, Ty));
1295     return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1296   }
1297 
1298   // The cast wasn't folded; create an explicit cast node. We can reuse
1299   // the existing insert position since if we get here, we won't have
1300   // made any changes which would invalidate it.
1301   SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1302                                                  Op, Ty);
1303   UniqueSCEVs.InsertNode(S, IP);
1304   addToLoopUseLists(S);
1305   return S;
1306 }
1307 
1308 // Get the limit of a recurrence such that incrementing by Step cannot cause
1309 // signed overflow as long as the value of the recurrence within the
1310 // loop does not exceed this limit before incrementing.
1311 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1312                                                  ICmpInst::Predicate *Pred,
1313                                                  ScalarEvolution *SE) {
1314   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1315   if (SE->isKnownPositive(Step)) {
1316     *Pred = ICmpInst::ICMP_SLT;
1317     return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1318                            SE->getSignedRangeMax(Step));
1319   }
1320   if (SE->isKnownNegative(Step)) {
1321     *Pred = ICmpInst::ICMP_SGT;
1322     return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1323                            SE->getSignedRangeMin(Step));
1324   }
1325   return nullptr;
1326 }
1327 
1328 // Get the limit of a recurrence such that incrementing by Step cannot cause
1329 // unsigned overflow as long as the value of the recurrence within the loop does
1330 // not exceed this limit before incrementing.
1331 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1332                                                    ICmpInst::Predicate *Pred,
1333                                                    ScalarEvolution *SE) {
1334   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1335   *Pred = ICmpInst::ICMP_ULT;
1336 
1337   return SE->getConstant(APInt::getMinValue(BitWidth) -
1338                          SE->getUnsignedRangeMax(Step));
1339 }
1340 
1341 namespace {
1342 
1343 struct ExtendOpTraitsBase {
1344   typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *,
1345                                                           unsigned);
1346 };
1347 
1348 // Used to make code generic over signed and unsigned overflow.
1349 template <typename ExtendOp> struct ExtendOpTraits {
1350   // Members present:
1351   //
1352   // static const SCEV::NoWrapFlags WrapType;
1353   //
1354   // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1355   //
1356   // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1357   //                                           ICmpInst::Predicate *Pred,
1358   //                                           ScalarEvolution *SE);
1359 };
1360 
1361 template <>
1362 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1363   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1364 
1365   static const GetExtendExprTy GetExtendExpr;
1366 
1367   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1368                                              ICmpInst::Predicate *Pred,
1369                                              ScalarEvolution *SE) {
1370     return getSignedOverflowLimitForStep(Step, Pred, SE);
1371   }
1372 };
1373 
1374 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1375     SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr;
1376 
1377 template <>
1378 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1379   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1380 
1381   static const GetExtendExprTy GetExtendExpr;
1382 
1383   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1384                                              ICmpInst::Predicate *Pred,
1385                                              ScalarEvolution *SE) {
1386     return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1387   }
1388 };
1389 
1390 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1391     SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr;
1392 
1393 } // end anonymous namespace
1394 
1395 // The recurrence AR has been shown to have no signed/unsigned wrap or something
1396 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1397 // easily prove NSW/NUW for its preincrement or postincrement sibling. This
1398 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1399 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1400 // expression "Step + sext/zext(PreIncAR)" is congruent with
1401 // "sext/zext(PostIncAR)"
1402 template <typename ExtendOpTy>
1403 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1404                                         ScalarEvolution *SE, unsigned Depth) {
1405   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1406   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1407 
1408   const Loop *L = AR->getLoop();
1409   const SCEV *Start = AR->getStart();
1410   const SCEV *Step = AR->getStepRecurrence(*SE);
1411 
1412   // Check for a simple looking step prior to loop entry.
1413   const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1414   if (!SA)
1415     return nullptr;
1416 
1417   // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1418   // subtraction is expensive. For this purpose, perform a quick and dirty
1419   // difference, by checking for Step in the operand list.
1420   SmallVector<const SCEV *, 4> DiffOps;
1421   for (const SCEV *Op : SA->operands())
1422     if (Op != Step)
1423       DiffOps.push_back(Op);
1424 
1425   if (DiffOps.size() == SA->getNumOperands())
1426     return nullptr;
1427 
1428   // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1429   // `Step`:
1430 
1431   // 1. NSW/NUW flags on the step increment.
1432   auto PreStartFlags =
1433     ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
1434   const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1435   const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1436       SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1437 
1438   // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1439   // "S+X does not sign/unsign-overflow".
1440   //
1441 
1442   const SCEV *BECount = SE->getBackedgeTakenCount(L);
1443   if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1444       !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1445     return PreStart;
1446 
1447   // 2. Direct overflow check on the step operation's expression.
1448   unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1449   Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1450   const SCEV *OperandExtendedStart =
1451       SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
1452                      (SE->*GetExtendExpr)(Step, WideTy, Depth));
1453   if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
1454     if (PreAR && AR->getNoWrapFlags(WrapType)) {
1455       // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1456       // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1457       // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`.  Cache this fact.
1458       const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType);
1459     }
1460     return PreStart;
1461   }
1462 
1463   // 3. Loop precondition.
1464   ICmpInst::Predicate Pred;
1465   const SCEV *OverflowLimit =
1466       ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1467 
1468   if (OverflowLimit &&
1469       SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1470     return PreStart;
1471 
1472   return nullptr;
1473 }
1474 
1475 // Get the normalized zero or sign extended expression for this AddRec's Start.
1476 template <typename ExtendOpTy>
1477 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1478                                         ScalarEvolution *SE,
1479                                         unsigned Depth) {
1480   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1481 
1482   const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth);
1483   if (!PreStart)
1484     return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth);
1485 
1486   return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty,
1487                                              Depth),
1488                         (SE->*GetExtendExpr)(PreStart, Ty, Depth));
1489 }
1490 
1491 // Try to prove away overflow by looking at "nearby" add recurrences.  A
1492 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1493 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1494 //
1495 // Formally:
1496 //
1497 //     {S,+,X} == {S-T,+,X} + T
1498 //  => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1499 //
1500 // If ({S-T,+,X} + T) does not overflow  ... (1)
1501 //
1502 //  RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1503 //
1504 // If {S-T,+,X} does not overflow  ... (2)
1505 //
1506 //  RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1507 //      == {Ext(S-T)+Ext(T),+,Ext(X)}
1508 //
1509 // If (S-T)+T does not overflow  ... (3)
1510 //
1511 //  RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1512 //      == {Ext(S),+,Ext(X)} == LHS
1513 //
1514 // Thus, if (1), (2) and (3) are true for some T, then
1515 //   Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1516 //
1517 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1518 // does not overflow" restricted to the 0th iteration.  Therefore we only need
1519 // to check for (1) and (2).
1520 //
1521 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1522 // is `Delta` (defined below).
1523 template <typename ExtendOpTy>
1524 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1525                                                 const SCEV *Step,
1526                                                 const Loop *L) {
1527   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1528 
1529   // We restrict `Start` to a constant to prevent SCEV from spending too much
1530   // time here.  It is correct (but more expensive) to continue with a
1531   // non-constant `Start` and do a general SCEV subtraction to compute
1532   // `PreStart` below.
1533   const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1534   if (!StartC)
1535     return false;
1536 
1537   APInt StartAI = StartC->getAPInt();
1538 
1539   for (unsigned Delta : {-2, -1, 1, 2}) {
1540     const SCEV *PreStart = getConstant(StartAI - Delta);
1541 
1542     FoldingSetNodeID ID;
1543     ID.AddInteger(scAddRecExpr);
1544     ID.AddPointer(PreStart);
1545     ID.AddPointer(Step);
1546     ID.AddPointer(L);
1547     void *IP = nullptr;
1548     const auto *PreAR =
1549       static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1550 
1551     // Give up if we don't already have the add recurrence we need because
1552     // actually constructing an add recurrence is relatively expensive.
1553     if (PreAR && PreAR->getNoWrapFlags(WrapType)) {  // proves (2)
1554       const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1555       ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1556       const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1557           DeltaS, &Pred, this);
1558       if (Limit && isKnownPredicate(Pred, PreAR, Limit))  // proves (1)
1559         return true;
1560     }
1561   }
1562 
1563   return false;
1564 }
1565 
1566 const SCEV *
1567 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1568   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1569          "This is not an extending conversion!");
1570   assert(isSCEVable(Ty) &&
1571          "This is not a conversion to a SCEVable type!");
1572   Ty = getEffectiveSCEVType(Ty);
1573 
1574   // Fold if the operand is constant.
1575   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1576     return getConstant(
1577       cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
1578 
1579   // zext(zext(x)) --> zext(x)
1580   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1581     return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1582 
1583   // Before doing any expensive analysis, check to see if we've already
1584   // computed a SCEV for this Op and Ty.
1585   FoldingSetNodeID ID;
1586   ID.AddInteger(scZeroExtend);
1587   ID.AddPointer(Op);
1588   ID.AddPointer(Ty);
1589   void *IP = nullptr;
1590   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1591   if (Depth > MaxExtDepth) {
1592     SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1593                                                      Op, Ty);
1594     UniqueSCEVs.InsertNode(S, IP);
1595     addToLoopUseLists(S);
1596     return S;
1597   }
1598 
1599   // zext(trunc(x)) --> zext(x) or x or trunc(x)
1600   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1601     // It's possible the bits taken off by the truncate were all zero bits. If
1602     // so, we should be able to simplify this further.
1603     const SCEV *X = ST->getOperand();
1604     ConstantRange CR = getUnsignedRange(X);
1605     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1606     unsigned NewBits = getTypeSizeInBits(Ty);
1607     if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1608             CR.zextOrTrunc(NewBits)))
1609       return getTruncateOrZeroExtend(X, Ty);
1610   }
1611 
1612   // If the input value is a chrec scev, and we can prove that the value
1613   // did not overflow the old, smaller, value, we can zero extend all of the
1614   // operands (often constants).  This allows analysis of something like
1615   // this:  for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1616   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1617     if (AR->isAffine()) {
1618       const SCEV *Start = AR->getStart();
1619       const SCEV *Step = AR->getStepRecurrence(*this);
1620       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1621       const Loop *L = AR->getLoop();
1622 
1623       if (!AR->hasNoUnsignedWrap()) {
1624         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1625         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1626       }
1627 
1628       // If we have special knowledge that this addrec won't overflow,
1629       // we don't need to do any further analysis.
1630       if (AR->hasNoUnsignedWrap())
1631         return getAddRecExpr(
1632             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1633             getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1634 
1635       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1636       // Note that this serves two purposes: It filters out loops that are
1637       // simply not analyzable, and it covers the case where this code is
1638       // being called from within backedge-taken count analysis, such that
1639       // attempting to ask for the backedge-taken count would likely result
1640       // in infinite recursion. In the later case, the analysis code will
1641       // cope with a conservative value, and it will take care to purge
1642       // that value once it has finished.
1643       const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1644       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1645         // Manually compute the final value for AR, checking for
1646         // overflow.
1647 
1648         // Check whether the backedge-taken count can be losslessly casted to
1649         // the addrec's type. The count is always unsigned.
1650         const SCEV *CastedMaxBECount =
1651           getTruncateOrZeroExtend(MaxBECount, Start->getType());
1652         const SCEV *RecastedMaxBECount =
1653           getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1654         if (MaxBECount == RecastedMaxBECount) {
1655           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1656           // Check whether Start+Step*MaxBECount has no unsigned overflow.
1657           const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step,
1658                                         SCEV::FlagAnyWrap, Depth + 1);
1659           const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul,
1660                                                           SCEV::FlagAnyWrap,
1661                                                           Depth + 1),
1662                                                WideTy, Depth + 1);
1663           const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
1664           const SCEV *WideMaxBECount =
1665             getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1666           const SCEV *OperandExtendedAdd =
1667             getAddExpr(WideStart,
1668                        getMulExpr(WideMaxBECount,
1669                                   getZeroExtendExpr(Step, WideTy, Depth + 1),
1670                                   SCEV::FlagAnyWrap, Depth + 1),
1671                        SCEV::FlagAnyWrap, Depth + 1);
1672           if (ZAdd == OperandExtendedAdd) {
1673             // Cache knowledge of AR NUW, which is propagated to this AddRec.
1674             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1675             // Return the expression with the addrec on the outside.
1676             return getAddRecExpr(
1677                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1678                                                          Depth + 1),
1679                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1680                 AR->getNoWrapFlags());
1681           }
1682           // Similar to above, only this time treat the step value as signed.
1683           // This covers loops that count down.
1684           OperandExtendedAdd =
1685             getAddExpr(WideStart,
1686                        getMulExpr(WideMaxBECount,
1687                                   getSignExtendExpr(Step, WideTy, Depth + 1),
1688                                   SCEV::FlagAnyWrap, Depth + 1),
1689                        SCEV::FlagAnyWrap, Depth + 1);
1690           if (ZAdd == OperandExtendedAdd) {
1691             // Cache knowledge of AR NW, which is propagated to this AddRec.
1692             // Negative step causes unsigned wrap, but it still can't self-wrap.
1693             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1694             // Return the expression with the addrec on the outside.
1695             return getAddRecExpr(
1696                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1697                                                          Depth + 1),
1698                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1699                 AR->getNoWrapFlags());
1700           }
1701         }
1702       }
1703 
1704       // Normally, in the cases we can prove no-overflow via a
1705       // backedge guarding condition, we can also compute a backedge
1706       // taken count for the loop.  The exceptions are assumptions and
1707       // guards present in the loop -- SCEV is not great at exploiting
1708       // these to compute max backedge taken counts, but can still use
1709       // these to prove lack of overflow.  Use this fact to avoid
1710       // doing extra work that may not pay off.
1711       if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1712           !AC.assumptions().empty()) {
1713         // If the backedge is guarded by a comparison with the pre-inc
1714         // value the addrec is safe. Also, if the entry is guarded by
1715         // a comparison with the start value and the backedge is
1716         // guarded by a comparison with the post-inc value, the addrec
1717         // is safe.
1718         if (isKnownPositive(Step)) {
1719           const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
1720                                       getUnsignedRangeMax(Step));
1721           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
1722               (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
1723                isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
1724                                            AR->getPostIncExpr(*this), N))) {
1725             // Cache knowledge of AR NUW, which is propagated to this
1726             // AddRec.
1727             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1728             // Return the expression with the addrec on the outside.
1729             return getAddRecExpr(
1730                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1731                                                          Depth + 1),
1732                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1733                 AR->getNoWrapFlags());
1734           }
1735         } else if (isKnownNegative(Step)) {
1736           const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1737                                       getSignedRangeMin(Step));
1738           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1739               (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) &&
1740                isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
1741                                            AR->getPostIncExpr(*this), N))) {
1742             // Cache knowledge of AR NW, which is propagated to this
1743             // AddRec.  Negative step causes unsigned wrap, but it
1744             // still can't self-wrap.
1745             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1746             // Return the expression with the addrec on the outside.
1747             return getAddRecExpr(
1748                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1749                                                          Depth + 1),
1750                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1751                 AR->getNoWrapFlags());
1752           }
1753         }
1754       }
1755 
1756       if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1757         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1758         return getAddRecExpr(
1759             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1760             getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1761       }
1762     }
1763 
1764   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1765     // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1766     if (SA->hasNoUnsignedWrap()) {
1767       // If the addition does not unsign overflow then we can, by definition,
1768       // commute the zero extension with the addition operation.
1769       SmallVector<const SCEV *, 4> Ops;
1770       for (const auto *Op : SA->operands())
1771         Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1772       return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1);
1773     }
1774   }
1775 
1776   // The cast wasn't folded; create an explicit cast node.
1777   // Recompute the insert position, as it may have been invalidated.
1778   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1779   SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1780                                                    Op, Ty);
1781   UniqueSCEVs.InsertNode(S, IP);
1782   addToLoopUseLists(S);
1783   return S;
1784 }
1785 
1786 const SCEV *
1787 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1788   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1789          "This is not an extending conversion!");
1790   assert(isSCEVable(Ty) &&
1791          "This is not a conversion to a SCEVable type!");
1792   Ty = getEffectiveSCEVType(Ty);
1793 
1794   // Fold if the operand is constant.
1795   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1796     return getConstant(
1797       cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
1798 
1799   // sext(sext(x)) --> sext(x)
1800   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1801     return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1);
1802 
1803   // sext(zext(x)) --> zext(x)
1804   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1805     return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1806 
1807   // Before doing any expensive analysis, check to see if we've already
1808   // computed a SCEV for this Op and Ty.
1809   FoldingSetNodeID ID;
1810   ID.AddInteger(scSignExtend);
1811   ID.AddPointer(Op);
1812   ID.AddPointer(Ty);
1813   void *IP = nullptr;
1814   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1815   // Limit recursion depth.
1816   if (Depth > MaxExtDepth) {
1817     SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1818                                                      Op, Ty);
1819     UniqueSCEVs.InsertNode(S, IP);
1820     addToLoopUseLists(S);
1821     return S;
1822   }
1823 
1824   // sext(trunc(x)) --> sext(x) or x or trunc(x)
1825   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1826     // It's possible the bits taken off by the truncate were all sign bits. If
1827     // so, we should be able to simplify this further.
1828     const SCEV *X = ST->getOperand();
1829     ConstantRange CR = getSignedRange(X);
1830     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1831     unsigned NewBits = getTypeSizeInBits(Ty);
1832     if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1833             CR.sextOrTrunc(NewBits)))
1834       return getTruncateOrSignExtend(X, Ty);
1835   }
1836 
1837   // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2
1838   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1839     if (SA->getNumOperands() == 2) {
1840       auto *SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0));
1841       auto *SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1));
1842       if (SMul && SC1) {
1843         if (auto *SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) {
1844           const APInt &C1 = SC1->getAPInt();
1845           const APInt &C2 = SC2->getAPInt();
1846           if (C1.isStrictlyPositive() && C2.isStrictlyPositive() &&
1847               C2.ugt(C1) && C2.isPowerOf2())
1848             return getAddExpr(getSignExtendExpr(SC1, Ty, Depth + 1),
1849                               getSignExtendExpr(SMul, Ty, Depth + 1),
1850                               SCEV::FlagAnyWrap, Depth + 1);
1851         }
1852       }
1853     }
1854 
1855     // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1856     if (SA->hasNoSignedWrap()) {
1857       // If the addition does not sign overflow then we can, by definition,
1858       // commute the sign extension with the addition operation.
1859       SmallVector<const SCEV *, 4> Ops;
1860       for (const auto *Op : SA->operands())
1861         Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1));
1862       return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1);
1863     }
1864   }
1865   // If the input value is a chrec scev, and we can prove that the value
1866   // did not overflow the old, smaller, value, we can sign extend all of the
1867   // operands (often constants).  This allows analysis of something like
1868   // this:  for (signed char X = 0; X < 100; ++X) { int Y = X; }
1869   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1870     if (AR->isAffine()) {
1871       const SCEV *Start = AR->getStart();
1872       const SCEV *Step = AR->getStepRecurrence(*this);
1873       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1874       const Loop *L = AR->getLoop();
1875 
1876       if (!AR->hasNoSignedWrap()) {
1877         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1878         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1879       }
1880 
1881       // If we have special knowledge that this addrec won't overflow,
1882       // we don't need to do any further analysis.
1883       if (AR->hasNoSignedWrap())
1884         return getAddRecExpr(
1885             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
1886             getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW);
1887 
1888       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1889       // Note that this serves two purposes: It filters out loops that are
1890       // simply not analyzable, and it covers the case where this code is
1891       // being called from within backedge-taken count analysis, such that
1892       // attempting to ask for the backedge-taken count would likely result
1893       // in infinite recursion. In the later case, the analysis code will
1894       // cope with a conservative value, and it will take care to purge
1895       // that value once it has finished.
1896       const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1897       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1898         // Manually compute the final value for AR, checking for
1899         // overflow.
1900 
1901         // Check whether the backedge-taken count can be losslessly casted to
1902         // the addrec's type. The count is always unsigned.
1903         const SCEV *CastedMaxBECount =
1904           getTruncateOrZeroExtend(MaxBECount, Start->getType());
1905         const SCEV *RecastedMaxBECount =
1906           getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1907         if (MaxBECount == RecastedMaxBECount) {
1908           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1909           // Check whether Start+Step*MaxBECount has no signed overflow.
1910           const SCEV *SMul = getMulExpr(CastedMaxBECount, Step,
1911                                         SCEV::FlagAnyWrap, Depth + 1);
1912           const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul,
1913                                                           SCEV::FlagAnyWrap,
1914                                                           Depth + 1),
1915                                                WideTy, Depth + 1);
1916           const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
1917           const SCEV *WideMaxBECount =
1918             getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1919           const SCEV *OperandExtendedAdd =
1920             getAddExpr(WideStart,
1921                        getMulExpr(WideMaxBECount,
1922                                   getSignExtendExpr(Step, WideTy, Depth + 1),
1923                                   SCEV::FlagAnyWrap, Depth + 1),
1924                        SCEV::FlagAnyWrap, Depth + 1);
1925           if (SAdd == OperandExtendedAdd) {
1926             // Cache knowledge of AR NSW, which is propagated to this AddRec.
1927             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1928             // Return the expression with the addrec on the outside.
1929             return getAddRecExpr(
1930                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
1931                                                          Depth + 1),
1932                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1933                 AR->getNoWrapFlags());
1934           }
1935           // Similar to above, only this time treat the step value as unsigned.
1936           // This covers loops that count up with an unsigned step.
1937           OperandExtendedAdd =
1938             getAddExpr(WideStart,
1939                        getMulExpr(WideMaxBECount,
1940                                   getZeroExtendExpr(Step, WideTy, Depth + 1),
1941                                   SCEV::FlagAnyWrap, Depth + 1),
1942                        SCEV::FlagAnyWrap, Depth + 1);
1943           if (SAdd == OperandExtendedAdd) {
1944             // If AR wraps around then
1945             //
1946             //    abs(Step) * MaxBECount > unsigned-max(AR->getType())
1947             // => SAdd != OperandExtendedAdd
1948             //
1949             // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
1950             // (SAdd == OperandExtendedAdd => AR is NW)
1951 
1952             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1953 
1954             // Return the expression with the addrec on the outside.
1955             return getAddRecExpr(
1956                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
1957                                                          Depth + 1),
1958                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1959                 AR->getNoWrapFlags());
1960           }
1961         }
1962       }
1963 
1964       // Normally, in the cases we can prove no-overflow via a
1965       // backedge guarding condition, we can also compute a backedge
1966       // taken count for the loop.  The exceptions are assumptions and
1967       // guards present in the loop -- SCEV is not great at exploiting
1968       // these to compute max backedge taken counts, but can still use
1969       // these to prove lack of overflow.  Use this fact to avoid
1970       // doing extra work that may not pay off.
1971 
1972       if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1973           !AC.assumptions().empty()) {
1974         // If the backedge is guarded by a comparison with the pre-inc
1975         // value the addrec is safe. Also, if the entry is guarded by
1976         // a comparison with the start value and the backedge is
1977         // guarded by a comparison with the post-inc value, the addrec
1978         // is safe.
1979         ICmpInst::Predicate Pred;
1980         const SCEV *OverflowLimit =
1981             getSignedOverflowLimitForStep(Step, &Pred, this);
1982         if (OverflowLimit &&
1983             (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
1984              (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) &&
1985               isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this),
1986                                           OverflowLimit)))) {
1987           // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec.
1988           const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1989           return getAddRecExpr(
1990               getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
1991               getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1992         }
1993       }
1994 
1995       // If Start and Step are constants, check if we can apply this
1996       // transformation:
1997       // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2
1998       auto *SC1 = dyn_cast<SCEVConstant>(Start);
1999       auto *SC2 = dyn_cast<SCEVConstant>(Step);
2000       if (SC1 && SC2) {
2001         const APInt &C1 = SC1->getAPInt();
2002         const APInt &C2 = SC2->getAPInt();
2003         if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) &&
2004             C2.isPowerOf2()) {
2005           Start = getSignExtendExpr(Start, Ty, Depth + 1);
2006           const SCEV *NewAR = getAddRecExpr(getZero(AR->getType()), Step, L,
2007                                             AR->getNoWrapFlags());
2008           return getAddExpr(Start, getSignExtendExpr(NewAR, Ty, Depth + 1),
2009                             SCEV::FlagAnyWrap, Depth + 1);
2010         }
2011       }
2012 
2013       if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
2014         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
2015         return getAddRecExpr(
2016             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2017             getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2018       }
2019     }
2020 
2021   // If the input value is provably positive and we could not simplify
2022   // away the sext build a zext instead.
2023   if (isKnownNonNegative(Op))
2024     return getZeroExtendExpr(Op, Ty, Depth + 1);
2025 
2026   // The cast wasn't folded; create an explicit cast node.
2027   // Recompute the insert position, as it may have been invalidated.
2028   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2029   SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
2030                                                    Op, Ty);
2031   UniqueSCEVs.InsertNode(S, IP);
2032   addToLoopUseLists(S);
2033   return S;
2034 }
2035 
2036 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
2037 /// unspecified bits out to the given type.
2038 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
2039                                               Type *Ty) {
2040   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
2041          "This is not an extending conversion!");
2042   assert(isSCEVable(Ty) &&
2043          "This is not a conversion to a SCEVable type!");
2044   Ty = getEffectiveSCEVType(Ty);
2045 
2046   // Sign-extend negative constants.
2047   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
2048     if (SC->getAPInt().isNegative())
2049       return getSignExtendExpr(Op, Ty);
2050 
2051   // Peel off a truncate cast.
2052   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
2053     const SCEV *NewOp = T->getOperand();
2054     if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
2055       return getAnyExtendExpr(NewOp, Ty);
2056     return getTruncateOrNoop(NewOp, Ty);
2057   }
2058 
2059   // Next try a zext cast. If the cast is folded, use it.
2060   const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2061   if (!isa<SCEVZeroExtendExpr>(ZExt))
2062     return ZExt;
2063 
2064   // Next try a sext cast. If the cast is folded, use it.
2065   const SCEV *SExt = getSignExtendExpr(Op, Ty);
2066   if (!isa<SCEVSignExtendExpr>(SExt))
2067     return SExt;
2068 
2069   // Force the cast to be folded into the operands of an addrec.
2070   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2071     SmallVector<const SCEV *, 4> Ops;
2072     for (const SCEV *Op : AR->operands())
2073       Ops.push_back(getAnyExtendExpr(Op, Ty));
2074     return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2075   }
2076 
2077   // If the expression is obviously signed, use the sext cast value.
2078   if (isa<SCEVSMaxExpr>(Op))
2079     return SExt;
2080 
2081   // Absent any other information, use the zext cast value.
2082   return ZExt;
2083 }
2084 
2085 /// Process the given Ops list, which is a list of operands to be added under
2086 /// the given scale, update the given map. This is a helper function for
2087 /// getAddRecExpr. As an example of what it does, given a sequence of operands
2088 /// that would form an add expression like this:
2089 ///
2090 ///    m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2091 ///
2092 /// where A and B are constants, update the map with these values:
2093 ///
2094 ///    (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2095 ///
2096 /// and add 13 + A*B*29 to AccumulatedConstant.
2097 /// This will allow getAddRecExpr to produce this:
2098 ///
2099 ///    13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2100 ///
2101 /// This form often exposes folding opportunities that are hidden in
2102 /// the original operand list.
2103 ///
2104 /// Return true iff it appears that any interesting folding opportunities
2105 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
2106 /// the common case where no interesting opportunities are present, and
2107 /// is also used as a check to avoid infinite recursion.
2108 static bool
2109 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
2110                              SmallVectorImpl<const SCEV *> &NewOps,
2111                              APInt &AccumulatedConstant,
2112                              const SCEV *const *Ops, size_t NumOperands,
2113                              const APInt &Scale,
2114                              ScalarEvolution &SE) {
2115   bool Interesting = false;
2116 
2117   // Iterate over the add operands. They are sorted, with constants first.
2118   unsigned i = 0;
2119   while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2120     ++i;
2121     // Pull a buried constant out to the outside.
2122     if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2123       Interesting = true;
2124     AccumulatedConstant += Scale * C->getAPInt();
2125   }
2126 
2127   // Next comes everything else. We're especially interested in multiplies
2128   // here, but they're in the middle, so just visit the rest with one loop.
2129   for (; i != NumOperands; ++i) {
2130     const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
2131     if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2132       APInt NewScale =
2133           Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2134       if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2135         // A multiplication of a constant with another add; recurse.
2136         const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2137         Interesting |=
2138           CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2139                                        Add->op_begin(), Add->getNumOperands(),
2140                                        NewScale, SE);
2141       } else {
2142         // A multiplication of a constant with some other value. Update
2143         // the map.
2144         SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
2145         const SCEV *Key = SE.getMulExpr(MulOps);
2146         auto Pair = M.insert({Key, NewScale});
2147         if (Pair.second) {
2148           NewOps.push_back(Pair.first->first);
2149         } else {
2150           Pair.first->second += NewScale;
2151           // The map already had an entry for this value, which may indicate
2152           // a folding opportunity.
2153           Interesting = true;
2154         }
2155       }
2156     } else {
2157       // An ordinary operand. Update the map.
2158       std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
2159           M.insert({Ops[i], Scale});
2160       if (Pair.second) {
2161         NewOps.push_back(Pair.first->first);
2162       } else {
2163         Pair.first->second += Scale;
2164         // The map already had an entry for this value, which may indicate
2165         // a folding opportunity.
2166         Interesting = true;
2167       }
2168     }
2169   }
2170 
2171   return Interesting;
2172 }
2173 
2174 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2175 // `OldFlags' as can't-wrap behavior.  Infer a more aggressive set of
2176 // can't-overflow flags for the operation if possible.
2177 static SCEV::NoWrapFlags
2178 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
2179                       const SmallVectorImpl<const SCEV *> &Ops,
2180                       SCEV::NoWrapFlags Flags) {
2181   using namespace std::placeholders;
2182 
2183   using OBO = OverflowingBinaryOperator;
2184 
2185   bool CanAnalyze =
2186       Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
2187   (void)CanAnalyze;
2188   assert(CanAnalyze && "don't call from other places!");
2189 
2190   int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2191   SCEV::NoWrapFlags SignOrUnsignWrap =
2192       ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2193 
2194   // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2195   auto IsKnownNonNegative = [&](const SCEV *S) {
2196     return SE->isKnownNonNegative(S);
2197   };
2198 
2199   if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2200     Flags =
2201         ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
2202 
2203   SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2204 
2205   if (SignOrUnsignWrap != SignOrUnsignMask && Type == scAddExpr &&
2206       Ops.size() == 2 && isa<SCEVConstant>(Ops[0])) {
2207 
2208     // (A + C) --> (A + C)<nsw> if the addition does not sign overflow
2209     // (A + C) --> (A + C)<nuw> if the addition does not unsign overflow
2210 
2211     const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2212     if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2213       auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2214           Instruction::Add, C, OBO::NoSignedWrap);
2215       if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2216         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2217     }
2218     if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2219       auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2220           Instruction::Add, C, OBO::NoUnsignedWrap);
2221       if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2222         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2223     }
2224   }
2225 
2226   return Flags;
2227 }
2228 
2229 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) {
2230   if (!isLoopInvariant(S, L))
2231     return false;
2232   // If a value depends on a SCEVUnknown which is defined after the loop, we
2233   // conservatively assume that we cannot calculate it at the loop's entry.
2234   struct FindDominatedSCEVUnknown {
2235     bool Found = false;
2236     const Loop *L;
2237     DominatorTree &DT;
2238     LoopInfo &LI;
2239 
2240     FindDominatedSCEVUnknown(const Loop *L, DominatorTree &DT, LoopInfo &LI)
2241         : L(L), DT(DT), LI(LI) {}
2242 
2243     bool checkSCEVUnknown(const SCEVUnknown *SU) {
2244       if (auto *I = dyn_cast<Instruction>(SU->getValue())) {
2245         if (DT.dominates(L->getHeader(), I->getParent()))
2246           Found = true;
2247         else
2248           assert(DT.dominates(I->getParent(), L->getHeader()) &&
2249                  "No dominance relationship between SCEV and loop?");
2250       }
2251       return false;
2252     }
2253 
2254     bool follow(const SCEV *S) {
2255       switch (static_cast<SCEVTypes>(S->getSCEVType())) {
2256       case scConstant:
2257         return false;
2258       case scAddRecExpr:
2259       case scTruncate:
2260       case scZeroExtend:
2261       case scSignExtend:
2262       case scAddExpr:
2263       case scMulExpr:
2264       case scUMaxExpr:
2265       case scSMaxExpr:
2266       case scUDivExpr:
2267         return true;
2268       case scUnknown:
2269         return checkSCEVUnknown(cast<SCEVUnknown>(S));
2270       case scCouldNotCompute:
2271         llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
2272       }
2273       return false;
2274     }
2275 
2276     bool isDone() { return Found; }
2277   };
2278 
2279   FindDominatedSCEVUnknown FSU(L, DT, LI);
2280   SCEVTraversal<FindDominatedSCEVUnknown> ST(FSU);
2281   ST.visitAll(S);
2282   return !FSU.Found;
2283 }
2284 
2285 /// Get a canonical add expression, or something simpler if possible.
2286 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2287                                         SCEV::NoWrapFlags Flags,
2288                                         unsigned Depth) {
2289   assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2290          "only nuw or nsw allowed");
2291   assert(!Ops.empty() && "Cannot get empty add!");
2292   if (Ops.size() == 1) return Ops[0];
2293 #ifndef NDEBUG
2294   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2295   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2296     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2297            "SCEVAddExpr operand types don't match!");
2298 #endif
2299 
2300   // Sort by complexity, this groups all similar expression types together.
2301   GroupByComplexity(Ops, &LI, DT);
2302 
2303   Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags);
2304 
2305   // If there are any constants, fold them together.
2306   unsigned Idx = 0;
2307   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2308     ++Idx;
2309     assert(Idx < Ops.size());
2310     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2311       // We found two constants, fold them together!
2312       Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
2313       if (Ops.size() == 2) return Ops[0];
2314       Ops.erase(Ops.begin()+1);  // Erase the folded element
2315       LHSC = cast<SCEVConstant>(Ops[0]);
2316     }
2317 
2318     // If we are left with a constant zero being added, strip it off.
2319     if (LHSC->getValue()->isZero()) {
2320       Ops.erase(Ops.begin());
2321       --Idx;
2322     }
2323 
2324     if (Ops.size() == 1) return Ops[0];
2325   }
2326 
2327   // Limit recursion calls depth.
2328   if (Depth > MaxArithDepth)
2329     return getOrCreateAddExpr(Ops, Flags);
2330 
2331   // Okay, check to see if the same value occurs in the operand list more than
2332   // once.  If so, merge them together into an multiply expression.  Since we
2333   // sorted the list, these values are required to be adjacent.
2334   Type *Ty = Ops[0]->getType();
2335   bool FoundMatch = false;
2336   for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2337     if (Ops[i] == Ops[i+1]) {      //  X + Y + Y  -->  X + Y*2
2338       // Scan ahead to count how many equal operands there are.
2339       unsigned Count = 2;
2340       while (i+Count != e && Ops[i+Count] == Ops[i])
2341         ++Count;
2342       // Merge the values into a multiply.
2343       const SCEV *Scale = getConstant(Ty, Count);
2344       const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1);
2345       if (Ops.size() == Count)
2346         return Mul;
2347       Ops[i] = Mul;
2348       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2349       --i; e -= Count - 1;
2350       FoundMatch = true;
2351     }
2352   if (FoundMatch)
2353     return getAddExpr(Ops, Flags);
2354 
2355   // Check for truncates. If all the operands are truncated from the same
2356   // type, see if factoring out the truncate would permit the result to be
2357   // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
2358   // if the contents of the resulting outer trunc fold to something simple.
2359   auto FindTruncSrcType = [&]() -> Type * {
2360     // We're ultimately looking to fold an addrec of truncs and muls of only
2361     // constants and truncs, so if we find any other types of SCEV
2362     // as operands of the addrec then we bail and return nullptr here.
2363     // Otherwise, we return the type of the operand of a trunc that we find.
2364     if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx]))
2365       return T->getOperand()->getType();
2366     if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2367       const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1);
2368       if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp))
2369         return T->getOperand()->getType();
2370     }
2371     return nullptr;
2372   };
2373   if (auto *SrcType = FindTruncSrcType()) {
2374     SmallVector<const SCEV *, 8> LargeOps;
2375     bool Ok = true;
2376     // Check all the operands to see if they can be represented in the
2377     // source type of the truncate.
2378     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2379       if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2380         if (T->getOperand()->getType() != SrcType) {
2381           Ok = false;
2382           break;
2383         }
2384         LargeOps.push_back(T->getOperand());
2385       } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2386         LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2387       } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
2388         SmallVector<const SCEV *, 8> LargeMulOps;
2389         for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2390           if (const SCEVTruncateExpr *T =
2391                 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2392             if (T->getOperand()->getType() != SrcType) {
2393               Ok = false;
2394               break;
2395             }
2396             LargeMulOps.push_back(T->getOperand());
2397           } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2398             LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2399           } else {
2400             Ok = false;
2401             break;
2402           }
2403         }
2404         if (Ok)
2405           LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1));
2406       } else {
2407         Ok = false;
2408         break;
2409       }
2410     }
2411     if (Ok) {
2412       // Evaluate the expression in the larger type.
2413       const SCEV *Fold = getAddExpr(LargeOps, Flags, Depth + 1);
2414       // If it folds to something simple, use it. Otherwise, don't.
2415       if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2416         return getTruncateExpr(Fold, Ty);
2417     }
2418   }
2419 
2420   // Skip past any other cast SCEVs.
2421   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2422     ++Idx;
2423 
2424   // If there are add operands they would be next.
2425   if (Idx < Ops.size()) {
2426     bool DeletedAdd = false;
2427     while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2428       if (Ops.size() > AddOpsInlineThreshold ||
2429           Add->getNumOperands() > AddOpsInlineThreshold)
2430         break;
2431       // If we have an add, expand the add operands onto the end of the operands
2432       // list.
2433       Ops.erase(Ops.begin()+Idx);
2434       Ops.append(Add->op_begin(), Add->op_end());
2435       DeletedAdd = true;
2436     }
2437 
2438     // If we deleted at least one add, we added operands to the end of the list,
2439     // and they are not necessarily sorted.  Recurse to resort and resimplify
2440     // any operands we just acquired.
2441     if (DeletedAdd)
2442       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2443   }
2444 
2445   // Skip over the add expression until we get to a multiply.
2446   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2447     ++Idx;
2448 
2449   // Check to see if there are any folding opportunities present with
2450   // operands multiplied by constant values.
2451   if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2452     uint64_t BitWidth = getTypeSizeInBits(Ty);
2453     DenseMap<const SCEV *, APInt> M;
2454     SmallVector<const SCEV *, 8> NewOps;
2455     APInt AccumulatedConstant(BitWidth, 0);
2456     if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2457                                      Ops.data(), Ops.size(),
2458                                      APInt(BitWidth, 1), *this)) {
2459       struct APIntCompare {
2460         bool operator()(const APInt &LHS, const APInt &RHS) const {
2461           return LHS.ult(RHS);
2462         }
2463       };
2464 
2465       // Some interesting folding opportunity is present, so its worthwhile to
2466       // re-generate the operands list. Group the operands by constant scale,
2467       // to avoid multiplying by the same constant scale multiple times.
2468       std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
2469       for (const SCEV *NewOp : NewOps)
2470         MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2471       // Re-generate the operands list.
2472       Ops.clear();
2473       if (AccumulatedConstant != 0)
2474         Ops.push_back(getConstant(AccumulatedConstant));
2475       for (auto &MulOp : MulOpLists)
2476         if (MulOp.first != 0)
2477           Ops.push_back(getMulExpr(
2478               getConstant(MulOp.first),
2479               getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1),
2480               SCEV::FlagAnyWrap, Depth + 1));
2481       if (Ops.empty())
2482         return getZero(Ty);
2483       if (Ops.size() == 1)
2484         return Ops[0];
2485       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2486     }
2487   }
2488 
2489   // If we are adding something to a multiply expression, make sure the
2490   // something is not already an operand of the multiply.  If so, merge it into
2491   // the multiply.
2492   for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2493     const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2494     for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2495       const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2496       if (isa<SCEVConstant>(MulOpSCEV))
2497         continue;
2498       for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
2499         if (MulOpSCEV == Ops[AddOp]) {
2500           // Fold W + X + (X * Y * Z)  -->  W + (X * ((Y*Z)+1))
2501           const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
2502           if (Mul->getNumOperands() != 2) {
2503             // If the multiply has more than two operands, we must get the
2504             // Y*Z term.
2505             SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2506                                                 Mul->op_begin()+MulOp);
2507             MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2508             InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2509           }
2510           SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul};
2511           const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2512           const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV,
2513                                             SCEV::FlagAnyWrap, Depth + 1);
2514           if (Ops.size() == 2) return OuterMul;
2515           if (AddOp < Idx) {
2516             Ops.erase(Ops.begin()+AddOp);
2517             Ops.erase(Ops.begin()+Idx-1);
2518           } else {
2519             Ops.erase(Ops.begin()+Idx);
2520             Ops.erase(Ops.begin()+AddOp-1);
2521           }
2522           Ops.push_back(OuterMul);
2523           return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2524         }
2525 
2526       // Check this multiply against other multiplies being added together.
2527       for (unsigned OtherMulIdx = Idx+1;
2528            OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2529            ++OtherMulIdx) {
2530         const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
2531         // If MulOp occurs in OtherMul, we can fold the two multiplies
2532         // together.
2533         for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2534              OMulOp != e; ++OMulOp)
2535           if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2536             // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
2537             const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
2538             if (Mul->getNumOperands() != 2) {
2539               SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2540                                                   Mul->op_begin()+MulOp);
2541               MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2542               InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2543             }
2544             const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
2545             if (OtherMul->getNumOperands() != 2) {
2546               SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
2547                                                   OtherMul->op_begin()+OMulOp);
2548               MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
2549               InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2550             }
2551             SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2};
2552             const SCEV *InnerMulSum =
2553                 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2554             const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum,
2555                                               SCEV::FlagAnyWrap, Depth + 1);
2556             if (Ops.size() == 2) return OuterMul;
2557             Ops.erase(Ops.begin()+Idx);
2558             Ops.erase(Ops.begin()+OtherMulIdx-1);
2559             Ops.push_back(OuterMul);
2560             return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2561           }
2562       }
2563     }
2564   }
2565 
2566   // If there are any add recurrences in the operands list, see if any other
2567   // added values are loop invariant.  If so, we can fold them into the
2568   // recurrence.
2569   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2570     ++Idx;
2571 
2572   // Scan over all recurrences, trying to fold loop invariants into them.
2573   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2574     // Scan all of the other operands to this add and add them to the vector if
2575     // they are loop invariant w.r.t. the recurrence.
2576     SmallVector<const SCEV *, 8> LIOps;
2577     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2578     const Loop *AddRecLoop = AddRec->getLoop();
2579     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2580       if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2581         LIOps.push_back(Ops[i]);
2582         Ops.erase(Ops.begin()+i);
2583         --i; --e;
2584       }
2585 
2586     // If we found some loop invariants, fold them into the recurrence.
2587     if (!LIOps.empty()) {
2588       //  NLI + LI + {Start,+,Step}  -->  NLI + {LI+Start,+,Step}
2589       LIOps.push_back(AddRec->getStart());
2590 
2591       SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2592                                              AddRec->op_end());
2593       // This follows from the fact that the no-wrap flags on the outer add
2594       // expression are applicable on the 0th iteration, when the add recurrence
2595       // will be equal to its start value.
2596       AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1);
2597 
2598       // Build the new addrec. Propagate the NUW and NSW flags if both the
2599       // outer add and the inner addrec are guaranteed to have no overflow.
2600       // Always propagate NW.
2601       Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2602       const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2603 
2604       // If all of the other operands were loop invariant, we are done.
2605       if (Ops.size() == 1) return NewRec;
2606 
2607       // Otherwise, add the folded AddRec by the non-invariant parts.
2608       for (unsigned i = 0;; ++i)
2609         if (Ops[i] == AddRec) {
2610           Ops[i] = NewRec;
2611           break;
2612         }
2613       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2614     }
2615 
2616     // Okay, if there weren't any loop invariants to be folded, check to see if
2617     // there are multiple AddRec's with the same loop induction variable being
2618     // added together.  If so, we can fold them.
2619     for (unsigned OtherIdx = Idx+1;
2620          OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2621          ++OtherIdx) {
2622       // We expect the AddRecExpr's to be sorted in reverse dominance order,
2623       // so that the 1st found AddRecExpr is dominated by all others.
2624       assert(DT.dominates(
2625            cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
2626            AddRec->getLoop()->getHeader()) &&
2627         "AddRecExprs are not sorted in reverse dominance order?");
2628       if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2629         // Other + {A,+,B}<L> + {C,+,D}<L>  -->  Other + {A+C,+,B+D}<L>
2630         SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2631                                                AddRec->op_end());
2632         for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2633              ++OtherIdx) {
2634           const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2635           if (OtherAddRec->getLoop() == AddRecLoop) {
2636             for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2637                  i != e; ++i) {
2638               if (i >= AddRecOps.size()) {
2639                 AddRecOps.append(OtherAddRec->op_begin()+i,
2640                                  OtherAddRec->op_end());
2641                 break;
2642               }
2643               SmallVector<const SCEV *, 2> TwoOps = {
2644                   AddRecOps[i], OtherAddRec->getOperand(i)};
2645               AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2646             }
2647             Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2648           }
2649         }
2650         // Step size has changed, so we cannot guarantee no self-wraparound.
2651         Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2652         return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2653       }
2654     }
2655 
2656     // Otherwise couldn't fold anything into this recurrence.  Move onto the
2657     // next one.
2658   }
2659 
2660   // Okay, it looks like we really DO need an add expr.  Check to see if we
2661   // already have one, otherwise create a new one.
2662   return getOrCreateAddExpr(Ops, Flags);
2663 }
2664 
2665 const SCEV *
2666 ScalarEvolution::getOrCreateAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2667                                     SCEV::NoWrapFlags Flags) {
2668   FoldingSetNodeID ID;
2669   ID.AddInteger(scAddExpr);
2670   for (const SCEV *Op : Ops)
2671     ID.AddPointer(Op);
2672   void *IP = nullptr;
2673   SCEVAddExpr *S =
2674       static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2675   if (!S) {
2676     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2677     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2678     S = new (SCEVAllocator)
2679         SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
2680     UniqueSCEVs.InsertNode(S, IP);
2681     addToLoopUseLists(S);
2682   }
2683   S->setNoWrapFlags(Flags);
2684   return S;
2685 }
2686 
2687 const SCEV *
2688 ScalarEvolution::getOrCreateMulExpr(SmallVectorImpl<const SCEV *> &Ops,
2689                                     SCEV::NoWrapFlags Flags) {
2690   FoldingSetNodeID ID;
2691   ID.AddInteger(scMulExpr);
2692   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2693     ID.AddPointer(Ops[i]);
2694   void *IP = nullptr;
2695   SCEVMulExpr *S =
2696     static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2697   if (!S) {
2698     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2699     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2700     S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2701                                         O, Ops.size());
2702     UniqueSCEVs.InsertNode(S, IP);
2703     addToLoopUseLists(S);
2704   }
2705   S->setNoWrapFlags(Flags);
2706   return S;
2707 }
2708 
2709 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2710   uint64_t k = i*j;
2711   if (j > 1 && k / j != i) Overflow = true;
2712   return k;
2713 }
2714 
2715 /// Compute the result of "n choose k", the binomial coefficient.  If an
2716 /// intermediate computation overflows, Overflow will be set and the return will
2717 /// be garbage. Overflow is not cleared on absence of overflow.
2718 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2719   // We use the multiplicative formula:
2720   //     n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2721   // At each iteration, we take the n-th term of the numeral and divide by the
2722   // (k-n)th term of the denominator.  This division will always produce an
2723   // integral result, and helps reduce the chance of overflow in the
2724   // intermediate computations. However, we can still overflow even when the
2725   // final result would fit.
2726 
2727   if (n == 0 || n == k) return 1;
2728   if (k > n) return 0;
2729 
2730   if (k > n/2)
2731     k = n-k;
2732 
2733   uint64_t r = 1;
2734   for (uint64_t i = 1; i <= k; ++i) {
2735     r = umul_ov(r, n-(i-1), Overflow);
2736     r /= i;
2737   }
2738   return r;
2739 }
2740 
2741 /// Determine if any of the operands in this SCEV are a constant or if
2742 /// any of the add or multiply expressions in this SCEV contain a constant.
2743 static bool containsConstantInAddMulChain(const SCEV *StartExpr) {
2744   struct FindConstantInAddMulChain {
2745     bool FoundConstant = false;
2746 
2747     bool follow(const SCEV *S) {
2748       FoundConstant |= isa<SCEVConstant>(S);
2749       return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
2750     }
2751 
2752     bool isDone() const {
2753       return FoundConstant;
2754     }
2755   };
2756 
2757   FindConstantInAddMulChain F;
2758   SCEVTraversal<FindConstantInAddMulChain> ST(F);
2759   ST.visitAll(StartExpr);
2760   return F.FoundConstant;
2761 }
2762 
2763 /// Get a canonical multiply expression, or something simpler if possible.
2764 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
2765                                         SCEV::NoWrapFlags Flags,
2766                                         unsigned Depth) {
2767   assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&
2768          "only nuw or nsw allowed");
2769   assert(!Ops.empty() && "Cannot get empty mul!");
2770   if (Ops.size() == 1) return Ops[0];
2771 #ifndef NDEBUG
2772   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2773   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2774     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2775            "SCEVMulExpr operand types don't match!");
2776 #endif
2777 
2778   // Sort by complexity, this groups all similar expression types together.
2779   GroupByComplexity(Ops, &LI, DT);
2780 
2781   Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags);
2782 
2783   // Limit recursion calls depth.
2784   if (Depth > MaxArithDepth)
2785     return getOrCreateMulExpr(Ops, Flags);
2786 
2787   // If there are any constants, fold them together.
2788   unsigned Idx = 0;
2789   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2790 
2791     // C1*(C2+V) -> C1*C2 + C1*V
2792     if (Ops.size() == 2)
2793         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
2794           // If any of Add's ops are Adds or Muls with a constant,
2795           // apply this transformation as well.
2796           if (Add->getNumOperands() == 2)
2797             // TODO: There are some cases where this transformation is not
2798             // profitable, for example:
2799             // Add = (C0 + X) * Y + Z.
2800             // Maybe the scope of this transformation should be narrowed down.
2801             if (containsConstantInAddMulChain(Add))
2802               return getAddExpr(getMulExpr(LHSC, Add->getOperand(0),
2803                                            SCEV::FlagAnyWrap, Depth + 1),
2804                                 getMulExpr(LHSC, Add->getOperand(1),
2805                                            SCEV::FlagAnyWrap, Depth + 1),
2806                                 SCEV::FlagAnyWrap, Depth + 1);
2807 
2808     ++Idx;
2809     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2810       // We found two constants, fold them together!
2811       ConstantInt *Fold =
2812           ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt());
2813       Ops[0] = getConstant(Fold);
2814       Ops.erase(Ops.begin()+1);  // Erase the folded element
2815       if (Ops.size() == 1) return Ops[0];
2816       LHSC = cast<SCEVConstant>(Ops[0]);
2817     }
2818 
2819     // If we are left with a constant one being multiplied, strip it off.
2820     if (cast<SCEVConstant>(Ops[0])->getValue()->isOne()) {
2821       Ops.erase(Ops.begin());
2822       --Idx;
2823     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
2824       // If we have a multiply of zero, it will always be zero.
2825       return Ops[0];
2826     } else if (Ops[0]->isAllOnesValue()) {
2827       // If we have a mul by -1 of an add, try distributing the -1 among the
2828       // add operands.
2829       if (Ops.size() == 2) {
2830         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
2831           SmallVector<const SCEV *, 4> NewOps;
2832           bool AnyFolded = false;
2833           for (const SCEV *AddOp : Add->operands()) {
2834             const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap,
2835                                          Depth + 1);
2836             if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
2837             NewOps.push_back(Mul);
2838           }
2839           if (AnyFolded)
2840             return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1);
2841         } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
2842           // Negation preserves a recurrence's no self-wrap property.
2843           SmallVector<const SCEV *, 4> Operands;
2844           for (const SCEV *AddRecOp : AddRec->operands())
2845             Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap,
2846                                           Depth + 1));
2847 
2848           return getAddRecExpr(Operands, AddRec->getLoop(),
2849                                AddRec->getNoWrapFlags(SCEV::FlagNW));
2850         }
2851       }
2852     }
2853 
2854     if (Ops.size() == 1)
2855       return Ops[0];
2856   }
2857 
2858   // Skip over the add expression until we get to a multiply.
2859   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2860     ++Idx;
2861 
2862   // If there are mul operands inline them all into this expression.
2863   if (Idx < Ops.size()) {
2864     bool DeletedMul = false;
2865     while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2866       if (Ops.size() > MulOpsInlineThreshold)
2867         break;
2868       // If we have an mul, expand the mul operands onto the end of the
2869       // operands list.
2870       Ops.erase(Ops.begin()+Idx);
2871       Ops.append(Mul->op_begin(), Mul->op_end());
2872       DeletedMul = true;
2873     }
2874 
2875     // If we deleted at least one mul, we added operands to the end of the
2876     // list, and they are not necessarily sorted.  Recurse to resort and
2877     // resimplify any operands we just acquired.
2878     if (DeletedMul)
2879       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2880   }
2881 
2882   // If there are any add recurrences in the operands list, see if any other
2883   // added values are loop invariant.  If so, we can fold them into the
2884   // recurrence.
2885   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2886     ++Idx;
2887 
2888   // Scan over all recurrences, trying to fold loop invariants into them.
2889   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2890     // Scan all of the other operands to this mul and add them to the vector
2891     // if they are loop invariant w.r.t. the recurrence.
2892     SmallVector<const SCEV *, 8> LIOps;
2893     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2894     const Loop *AddRecLoop = AddRec->getLoop();
2895     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2896       if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2897         LIOps.push_back(Ops[i]);
2898         Ops.erase(Ops.begin()+i);
2899         --i; --e;
2900       }
2901 
2902     // If we found some loop invariants, fold them into the recurrence.
2903     if (!LIOps.empty()) {
2904       //  NLI * LI * {Start,+,Step}  -->  NLI * {LI*Start,+,LI*Step}
2905       SmallVector<const SCEV *, 4> NewOps;
2906       NewOps.reserve(AddRec->getNumOperands());
2907       const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1);
2908       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
2909         NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
2910                                     SCEV::FlagAnyWrap, Depth + 1));
2911 
2912       // Build the new addrec. Propagate the NUW and NSW flags if both the
2913       // outer mul and the inner addrec are guaranteed to have no overflow.
2914       //
2915       // No self-wrap cannot be guaranteed after changing the step size, but
2916       // will be inferred if either NUW or NSW is true.
2917       Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW));
2918       const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
2919 
2920       // If all of the other operands were loop invariant, we are done.
2921       if (Ops.size() == 1) return NewRec;
2922 
2923       // Otherwise, multiply the folded AddRec by the non-invariant parts.
2924       for (unsigned i = 0;; ++i)
2925         if (Ops[i] == AddRec) {
2926           Ops[i] = NewRec;
2927           break;
2928         }
2929       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2930     }
2931 
2932     // Okay, if there weren't any loop invariants to be folded, check to see
2933     // if there are multiple AddRec's with the same loop induction variable
2934     // being multiplied together.  If so, we can fold them.
2935 
2936     // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
2937     // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
2938     //       choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
2939     //   ]]],+,...up to x=2n}.
2940     // Note that the arguments to choose() are always integers with values
2941     // known at compile time, never SCEV objects.
2942     //
2943     // The implementation avoids pointless extra computations when the two
2944     // addrec's are of different length (mathematically, it's equivalent to
2945     // an infinite stream of zeros on the right).
2946     bool OpsModified = false;
2947     for (unsigned OtherIdx = Idx+1;
2948          OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2949          ++OtherIdx) {
2950       const SCEVAddRecExpr *OtherAddRec =
2951         dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2952       if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
2953         continue;
2954 
2955       // Limit max number of arguments to avoid creation of unreasonably big
2956       // SCEVAddRecs with very complex operands.
2957       if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
2958           MaxAddRecSize)
2959         continue;
2960 
2961       bool Overflow = false;
2962       Type *Ty = AddRec->getType();
2963       bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
2964       SmallVector<const SCEV*, 7> AddRecOps;
2965       for (int x = 0, xe = AddRec->getNumOperands() +
2966              OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
2967         const SCEV *Term = getZero(Ty);
2968         for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
2969           uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
2970           for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
2971                  ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
2972                z < ze && !Overflow; ++z) {
2973             uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
2974             uint64_t Coeff;
2975             if (LargerThan64Bits)
2976               Coeff = umul_ov(Coeff1, Coeff2, Overflow);
2977             else
2978               Coeff = Coeff1*Coeff2;
2979             const SCEV *CoeffTerm = getConstant(Ty, Coeff);
2980             const SCEV *Term1 = AddRec->getOperand(y-z);
2981             const SCEV *Term2 = OtherAddRec->getOperand(z);
2982             Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1, Term2,
2983                                                SCEV::FlagAnyWrap, Depth + 1),
2984                               SCEV::FlagAnyWrap, Depth + 1);
2985           }
2986         }
2987         AddRecOps.push_back(Term);
2988       }
2989       if (!Overflow) {
2990         const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
2991                                               SCEV::FlagAnyWrap);
2992         if (Ops.size() == 2) return NewAddRec;
2993         Ops[Idx] = NewAddRec;
2994         Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2995         OpsModified = true;
2996         AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
2997         if (!AddRec)
2998           break;
2999       }
3000     }
3001     if (OpsModified)
3002       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3003 
3004     // Otherwise couldn't fold anything into this recurrence.  Move onto the
3005     // next one.
3006   }
3007 
3008   // Okay, it looks like we really DO need an mul expr.  Check to see if we
3009   // already have one, otherwise create a new one.
3010   return getOrCreateMulExpr(Ops, Flags);
3011 }
3012 
3013 /// Represents an unsigned remainder expression based on unsigned division.
3014 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS,
3015                                          const SCEV *RHS) {
3016   assert(getEffectiveSCEVType(LHS->getType()) ==
3017          getEffectiveSCEVType(RHS->getType()) &&
3018          "SCEVURemExpr operand types don't match!");
3019 
3020   // Short-circuit easy cases
3021   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3022     // If constant is one, the result is trivial
3023     if (RHSC->getValue()->isOne())
3024       return getZero(LHS->getType()); // X urem 1 --> 0
3025 
3026     // If constant is a power of two, fold into a zext(trunc(LHS)).
3027     if (RHSC->getAPInt().isPowerOf2()) {
3028       Type *FullTy = LHS->getType();
3029       Type *TruncTy =
3030           IntegerType::get(getContext(), RHSC->getAPInt().logBase2());
3031       return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy);
3032     }
3033   }
3034 
3035   // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
3036   const SCEV *UDiv = getUDivExpr(LHS, RHS);
3037   const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW);
3038   return getMinusSCEV(LHS, Mult, SCEV::FlagNUW);
3039 }
3040 
3041 /// Get a canonical unsigned division expression, or something simpler if
3042 /// possible.
3043 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
3044                                          const SCEV *RHS) {
3045   assert(getEffectiveSCEVType(LHS->getType()) ==
3046          getEffectiveSCEVType(RHS->getType()) &&
3047          "SCEVUDivExpr operand types don't match!");
3048 
3049   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3050     if (RHSC->getValue()->isOne())
3051       return LHS;                               // X udiv 1 --> x
3052     // If the denominator is zero, the result of the udiv is undefined. Don't
3053     // try to analyze it, because the resolution chosen here may differ from
3054     // the resolution chosen in other parts of the compiler.
3055     if (!RHSC->getValue()->isZero()) {
3056       // Determine if the division can be folded into the operands of
3057       // its operands.
3058       // TODO: Generalize this to non-constants by using known-bits information.
3059       Type *Ty = LHS->getType();
3060       unsigned LZ = RHSC->getAPInt().countLeadingZeros();
3061       unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
3062       // For non-power-of-two values, effectively round the value up to the
3063       // nearest power of two.
3064       if (!RHSC->getAPInt().isPowerOf2())
3065         ++MaxShiftAmt;
3066       IntegerType *ExtTy =
3067         IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
3068       if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
3069         if (const SCEVConstant *Step =
3070             dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
3071           // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
3072           const APInt &StepInt = Step->getAPInt();
3073           const APInt &DivInt = RHSC->getAPInt();
3074           if (!StepInt.urem(DivInt) &&
3075               getZeroExtendExpr(AR, ExtTy) ==
3076               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3077                             getZeroExtendExpr(Step, ExtTy),
3078                             AR->getLoop(), SCEV::FlagAnyWrap)) {
3079             SmallVector<const SCEV *, 4> Operands;
3080             for (const SCEV *Op : AR->operands())
3081               Operands.push_back(getUDivExpr(Op, RHS));
3082             return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
3083           }
3084           /// Get a canonical UDivExpr for a recurrence.
3085           /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
3086           // We can currently only fold X%N if X is constant.
3087           const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
3088           if (StartC && !DivInt.urem(StepInt) &&
3089               getZeroExtendExpr(AR, ExtTy) ==
3090               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3091                             getZeroExtendExpr(Step, ExtTy),
3092                             AR->getLoop(), SCEV::FlagAnyWrap)) {
3093             const APInt &StartInt = StartC->getAPInt();
3094             const APInt &StartRem = StartInt.urem(StepInt);
3095             if (StartRem != 0)
3096               LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step,
3097                                   AR->getLoop(), SCEV::FlagNW);
3098           }
3099         }
3100       // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
3101       if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
3102         SmallVector<const SCEV *, 4> Operands;
3103         for (const SCEV *Op : M->operands())
3104           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3105         if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
3106           // Find an operand that's safely divisible.
3107           for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3108             const SCEV *Op = M->getOperand(i);
3109             const SCEV *Div = getUDivExpr(Op, RHSC);
3110             if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
3111               Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
3112                                                       M->op_end());
3113               Operands[i] = Div;
3114               return getMulExpr(Operands);
3115             }
3116           }
3117       }
3118       // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
3119       if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
3120         SmallVector<const SCEV *, 4> Operands;
3121         for (const SCEV *Op : A->operands())
3122           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3123         if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
3124           Operands.clear();
3125           for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
3126             const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
3127             if (isa<SCEVUDivExpr>(Op) ||
3128                 getMulExpr(Op, RHS) != A->getOperand(i))
3129               break;
3130             Operands.push_back(Op);
3131           }
3132           if (Operands.size() == A->getNumOperands())
3133             return getAddExpr(Operands);
3134         }
3135       }
3136 
3137       // Fold if both operands are constant.
3138       if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
3139         Constant *LHSCV = LHSC->getValue();
3140         Constant *RHSCV = RHSC->getValue();
3141         return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
3142                                                                    RHSCV)));
3143       }
3144     }
3145   }
3146 
3147   FoldingSetNodeID ID;
3148   ID.AddInteger(scUDivExpr);
3149   ID.AddPointer(LHS);
3150   ID.AddPointer(RHS);
3151   void *IP = nullptr;
3152   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3153   SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
3154                                              LHS, RHS);
3155   UniqueSCEVs.InsertNode(S, IP);
3156   addToLoopUseLists(S);
3157   return S;
3158 }
3159 
3160 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
3161   APInt A = C1->getAPInt().abs();
3162   APInt B = C2->getAPInt().abs();
3163   uint32_t ABW = A.getBitWidth();
3164   uint32_t BBW = B.getBitWidth();
3165 
3166   if (ABW > BBW)
3167     B = B.zext(ABW);
3168   else if (ABW < BBW)
3169     A = A.zext(BBW);
3170 
3171   return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B));
3172 }
3173 
3174 /// Get a canonical unsigned division expression, or something simpler if
3175 /// possible. There is no representation for an exact udiv in SCEV IR, but we
3176 /// can attempt to remove factors from the LHS and RHS.  We can't do this when
3177 /// it's not exact because the udiv may be clearing bits.
3178 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
3179                                               const SCEV *RHS) {
3180   // TODO: we could try to find factors in all sorts of things, but for now we
3181   // just deal with u/exact (multiply, constant). See SCEVDivision towards the
3182   // end of this file for inspiration.
3183 
3184   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
3185   if (!Mul || !Mul->hasNoUnsignedWrap())
3186     return getUDivExpr(LHS, RHS);
3187 
3188   if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
3189     // If the mulexpr multiplies by a constant, then that constant must be the
3190     // first element of the mulexpr.
3191     if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
3192       if (LHSCst == RHSCst) {
3193         SmallVector<const SCEV *, 2> Operands;
3194         Operands.append(Mul->op_begin() + 1, Mul->op_end());
3195         return getMulExpr(Operands);
3196       }
3197 
3198       // We can't just assume that LHSCst divides RHSCst cleanly, it could be
3199       // that there's a factor provided by one of the other terms. We need to
3200       // check.
3201       APInt Factor = gcd(LHSCst, RHSCst);
3202       if (!Factor.isIntN(1)) {
3203         LHSCst =
3204             cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
3205         RHSCst =
3206             cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
3207         SmallVector<const SCEV *, 2> Operands;
3208         Operands.push_back(LHSCst);
3209         Operands.append(Mul->op_begin() + 1, Mul->op_end());
3210         LHS = getMulExpr(Operands);
3211         RHS = RHSCst;
3212         Mul = dyn_cast<SCEVMulExpr>(LHS);
3213         if (!Mul)
3214           return getUDivExactExpr(LHS, RHS);
3215       }
3216     }
3217   }
3218 
3219   for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3220     if (Mul->getOperand(i) == RHS) {
3221       SmallVector<const SCEV *, 2> Operands;
3222       Operands.append(Mul->op_begin(), Mul->op_begin() + i);
3223       Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
3224       return getMulExpr(Operands);
3225     }
3226   }
3227 
3228   return getUDivExpr(LHS, RHS);
3229 }
3230 
3231 /// Get an add recurrence expression for the specified loop.  Simplify the
3232 /// expression as much as possible.
3233 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
3234                                            const Loop *L,
3235                                            SCEV::NoWrapFlags Flags) {
3236   SmallVector<const SCEV *, 4> Operands;
3237   Operands.push_back(Start);
3238   if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3239     if (StepChrec->getLoop() == L) {
3240       Operands.append(StepChrec->op_begin(), StepChrec->op_end());
3241       return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
3242     }
3243 
3244   Operands.push_back(Step);
3245   return getAddRecExpr(Operands, L, Flags);
3246 }
3247 
3248 /// Get an add recurrence expression for the specified loop.  Simplify the
3249 /// expression as much as possible.
3250 const SCEV *
3251 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
3252                                const Loop *L, SCEV::NoWrapFlags Flags) {
3253   if (Operands.size() == 1) return Operands[0];
3254 #ifndef NDEBUG
3255   Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
3256   for (unsigned i = 1, e = Operands.size(); i != e; ++i)
3257     assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
3258            "SCEVAddRecExpr operand types don't match!");
3259   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3260     assert(isLoopInvariant(Operands[i], L) &&
3261            "SCEVAddRecExpr operand is not loop-invariant!");
3262 #endif
3263 
3264   if (Operands.back()->isZero()) {
3265     Operands.pop_back();
3266     return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0}  -->  X
3267   }
3268 
3269   // It's tempting to want to call getMaxBackedgeTakenCount count here and
3270   // use that information to infer NUW and NSW flags. However, computing a
3271   // BE count requires calling getAddRecExpr, so we may not yet have a
3272   // meaningful BE count at this point (and if we don't, we'd be stuck
3273   // with a SCEVCouldNotCompute as the cached BE count).
3274 
3275   Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
3276 
3277   // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3278   if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3279     const Loop *NestedLoop = NestedAR->getLoop();
3280     if (L->contains(NestedLoop)
3281             ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3282             : (!NestedLoop->contains(L) &&
3283                DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3284       SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
3285                                                   NestedAR->op_end());
3286       Operands[0] = NestedAR->getStart();
3287       // AddRecs require their operands be loop-invariant with respect to their
3288       // loops. Don't perform this transformation if it would break this
3289       // requirement.
3290       bool AllInvariant = all_of(
3291           Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3292 
3293       if (AllInvariant) {
3294         // Create a recurrence for the outer loop with the same step size.
3295         //
3296         // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3297         // inner recurrence has the same property.
3298         SCEV::NoWrapFlags OuterFlags =
3299           maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3300 
3301         NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3302         AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3303           return isLoopInvariant(Op, NestedLoop);
3304         });
3305 
3306         if (AllInvariant) {
3307           // Ok, both add recurrences are valid after the transformation.
3308           //
3309           // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3310           // the outer recurrence has the same property.
3311           SCEV::NoWrapFlags InnerFlags =
3312             maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
3313           return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3314         }
3315       }
3316       // Reset Operands to its original state.
3317       Operands[0] = NestedAR;
3318     }
3319   }
3320 
3321   // Okay, it looks like we really DO need an addrec expr.  Check to see if we
3322   // already have one, otherwise create a new one.
3323   FoldingSetNodeID ID;
3324   ID.AddInteger(scAddRecExpr);
3325   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3326     ID.AddPointer(Operands[i]);
3327   ID.AddPointer(L);
3328   void *IP = nullptr;
3329   SCEVAddRecExpr *S =
3330     static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3331   if (!S) {
3332     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
3333     std::uninitialized_copy(Operands.begin(), Operands.end(), O);
3334     S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
3335                                            O, Operands.size(), L);
3336     UniqueSCEVs.InsertNode(S, IP);
3337     addToLoopUseLists(S);
3338   }
3339   S->setNoWrapFlags(Flags);
3340   return S;
3341 }
3342 
3343 const SCEV *
3344 ScalarEvolution::getGEPExpr(GEPOperator *GEP,
3345                             const SmallVectorImpl<const SCEV *> &IndexExprs) {
3346   const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3347   // getSCEV(Base)->getType() has the same address space as Base->getType()
3348   // because SCEV::getType() preserves the address space.
3349   Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType());
3350   // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP
3351   // instruction to its SCEV, because the Instruction may be guarded by control
3352   // flow and the no-overflow bits may not be valid for the expression in any
3353   // context. This can be fixed similarly to how these flags are handled for
3354   // adds.
3355   SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW
3356                                              : SCEV::FlagAnyWrap;
3357 
3358   const SCEV *TotalOffset = getZero(IntPtrTy);
3359   // The array size is unimportant. The first thing we do on CurTy is getting
3360   // its element type.
3361   Type *CurTy = ArrayType::get(GEP->getSourceElementType(), 0);
3362   for (const SCEV *IndexExpr : IndexExprs) {
3363     // Compute the (potentially symbolic) offset in bytes for this index.
3364     if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3365       // For a struct, add the member offset.
3366       ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3367       unsigned FieldNo = Index->getZExtValue();
3368       const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo);
3369 
3370       // Add the field offset to the running total offset.
3371       TotalOffset = getAddExpr(TotalOffset, FieldOffset);
3372 
3373       // Update CurTy to the type of the field at Index.
3374       CurTy = STy->getTypeAtIndex(Index);
3375     } else {
3376       // Update CurTy to its element type.
3377       CurTy = cast<SequentialType>(CurTy)->getElementType();
3378       // For an array, add the element offset, explicitly scaled.
3379       const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy);
3380       // Getelementptr indices are signed.
3381       IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy);
3382 
3383       // Multiply the index by the element size to compute the element offset.
3384       const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap);
3385 
3386       // Add the element offset to the running total offset.
3387       TotalOffset = getAddExpr(TotalOffset, LocalOffset);
3388     }
3389   }
3390 
3391   // Add the total offset from all the GEP indices to the base.
3392   return getAddExpr(BaseExpr, TotalOffset, Wrap);
3393 }
3394 
3395 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
3396                                          const SCEV *RHS) {
3397   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3398   return getSMaxExpr(Ops);
3399 }
3400 
3401 const SCEV *
3402 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3403   assert(!Ops.empty() && "Cannot get empty smax!");
3404   if (Ops.size() == 1) return Ops[0];
3405 #ifndef NDEBUG
3406   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3407   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3408     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3409            "SCEVSMaxExpr operand types don't match!");
3410 #endif
3411 
3412   // Sort by complexity, this groups all similar expression types together.
3413   GroupByComplexity(Ops, &LI, DT);
3414 
3415   // If there are any constants, fold them together.
3416   unsigned Idx = 0;
3417   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3418     ++Idx;
3419     assert(Idx < Ops.size());
3420     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3421       // We found two constants, fold them together!
3422       ConstantInt *Fold = ConstantInt::get(
3423           getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt()));
3424       Ops[0] = getConstant(Fold);
3425       Ops.erase(Ops.begin()+1);  // Erase the folded element
3426       if (Ops.size() == 1) return Ops[0];
3427       LHSC = cast<SCEVConstant>(Ops[0]);
3428     }
3429 
3430     // If we are left with a constant minimum-int, strip it off.
3431     if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
3432       Ops.erase(Ops.begin());
3433       --Idx;
3434     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
3435       // If we have an smax with a constant maximum-int, it will always be
3436       // maximum-int.
3437       return Ops[0];
3438     }
3439 
3440     if (Ops.size() == 1) return Ops[0];
3441   }
3442 
3443   // Find the first SMax
3444   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
3445     ++Idx;
3446 
3447   // Check to see if one of the operands is an SMax. If so, expand its operands
3448   // onto our operand list, and recurse to simplify.
3449   if (Idx < Ops.size()) {
3450     bool DeletedSMax = false;
3451     while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
3452       Ops.erase(Ops.begin()+Idx);
3453       Ops.append(SMax->op_begin(), SMax->op_end());
3454       DeletedSMax = true;
3455     }
3456 
3457     if (DeletedSMax)
3458       return getSMaxExpr(Ops);
3459   }
3460 
3461   // Okay, check to see if the same value occurs in the operand list twice.  If
3462   // so, delete one.  Since we sorted the list, these values are required to
3463   // be adjacent.
3464   for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
3465     //  X smax Y smax Y  -->  X smax Y
3466     //  X smax Y         -->  X, if X is always greater than Y
3467     if (Ops[i] == Ops[i+1] ||
3468         isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
3469       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3470       --i; --e;
3471     } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
3472       Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3473       --i; --e;
3474     }
3475 
3476   if (Ops.size() == 1) return Ops[0];
3477 
3478   assert(!Ops.empty() && "Reduced smax down to nothing!");
3479 
3480   // Okay, it looks like we really DO need an smax expr.  Check to see if we
3481   // already have one, otherwise create a new one.
3482   FoldingSetNodeID ID;
3483   ID.AddInteger(scSMaxExpr);
3484   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3485     ID.AddPointer(Ops[i]);
3486   void *IP = nullptr;
3487   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3488   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3489   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3490   SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
3491                                              O, Ops.size());
3492   UniqueSCEVs.InsertNode(S, IP);
3493   addToLoopUseLists(S);
3494   return S;
3495 }
3496 
3497 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
3498                                          const SCEV *RHS) {
3499   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3500   return getUMaxExpr(Ops);
3501 }
3502 
3503 const SCEV *
3504 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3505   assert(!Ops.empty() && "Cannot get empty umax!");
3506   if (Ops.size() == 1) return Ops[0];
3507 #ifndef NDEBUG
3508   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3509   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3510     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3511            "SCEVUMaxExpr operand types don't match!");
3512 #endif
3513 
3514   // Sort by complexity, this groups all similar expression types together.
3515   GroupByComplexity(Ops, &LI, DT);
3516 
3517   // If there are any constants, fold them together.
3518   unsigned Idx = 0;
3519   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3520     ++Idx;
3521     assert(Idx < Ops.size());
3522     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3523       // We found two constants, fold them together!
3524       ConstantInt *Fold = ConstantInt::get(
3525           getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt()));
3526       Ops[0] = getConstant(Fold);
3527       Ops.erase(Ops.begin()+1);  // Erase the folded element
3528       if (Ops.size() == 1) return Ops[0];
3529       LHSC = cast<SCEVConstant>(Ops[0]);
3530     }
3531 
3532     // If we are left with a constant minimum-int, strip it off.
3533     if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
3534       Ops.erase(Ops.begin());
3535       --Idx;
3536     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
3537       // If we have an umax with a constant maximum-int, it will always be
3538       // maximum-int.
3539       return Ops[0];
3540     }
3541 
3542     if (Ops.size() == 1) return Ops[0];
3543   }
3544 
3545   // Find the first UMax
3546   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
3547     ++Idx;
3548 
3549   // Check to see if one of the operands is a UMax. If so, expand its operands
3550   // onto our operand list, and recurse to simplify.
3551   if (Idx < Ops.size()) {
3552     bool DeletedUMax = false;
3553     while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
3554       Ops.erase(Ops.begin()+Idx);
3555       Ops.append(UMax->op_begin(), UMax->op_end());
3556       DeletedUMax = true;
3557     }
3558 
3559     if (DeletedUMax)
3560       return getUMaxExpr(Ops);
3561   }
3562 
3563   // Okay, check to see if the same value occurs in the operand list twice.  If
3564   // so, delete one.  Since we sorted the list, these values are required to
3565   // be adjacent.
3566   for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
3567     //  X umax Y umax Y  -->  X umax Y
3568     //  X umax Y         -->  X, if X is always greater than Y
3569     if (Ops[i] == Ops[i+1] ||
3570         isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
3571       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3572       --i; --e;
3573     } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
3574       Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3575       --i; --e;
3576     }
3577 
3578   if (Ops.size() == 1) return Ops[0];
3579 
3580   assert(!Ops.empty() && "Reduced umax down to nothing!");
3581 
3582   // Okay, it looks like we really DO need a umax expr.  Check to see if we
3583   // already have one, otherwise create a new one.
3584   FoldingSetNodeID ID;
3585   ID.AddInteger(scUMaxExpr);
3586   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3587     ID.AddPointer(Ops[i]);
3588   void *IP = nullptr;
3589   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3590   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3591   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3592   SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
3593                                              O, Ops.size());
3594   UniqueSCEVs.InsertNode(S, IP);
3595   addToLoopUseLists(S);
3596   return S;
3597 }
3598 
3599 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
3600                                          const SCEV *RHS) {
3601   // ~smax(~x, ~y) == smin(x, y).
3602   return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3603 }
3604 
3605 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
3606                                          const SCEV *RHS) {
3607   // ~umax(~x, ~y) == umin(x, y)
3608   return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3609 }
3610 
3611 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
3612   // We can bypass creating a target-independent
3613   // constant expression and then folding it back into a ConstantInt.
3614   // This is just a compile-time optimization.
3615   return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
3616 }
3617 
3618 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
3619                                              StructType *STy,
3620                                              unsigned FieldNo) {
3621   // We can bypass creating a target-independent
3622   // constant expression and then folding it back into a ConstantInt.
3623   // This is just a compile-time optimization.
3624   return getConstant(
3625       IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
3626 }
3627 
3628 const SCEV *ScalarEvolution::getUnknown(Value *V) {
3629   // Don't attempt to do anything other than create a SCEVUnknown object
3630   // here.  createSCEV only calls getUnknown after checking for all other
3631   // interesting possibilities, and any other code that calls getUnknown
3632   // is doing so in order to hide a value from SCEV canonicalization.
3633 
3634   FoldingSetNodeID ID;
3635   ID.AddInteger(scUnknown);
3636   ID.AddPointer(V);
3637   void *IP = nullptr;
3638   if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3639     assert(cast<SCEVUnknown>(S)->getValue() == V &&
3640            "Stale SCEVUnknown in uniquing map!");
3641     return S;
3642   }
3643   SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3644                                             FirstUnknown);
3645   FirstUnknown = cast<SCEVUnknown>(S);
3646   UniqueSCEVs.InsertNode(S, IP);
3647   return S;
3648 }
3649 
3650 //===----------------------------------------------------------------------===//
3651 //            Basic SCEV Analysis and PHI Idiom Recognition Code
3652 //
3653 
3654 /// Test if values of the given type are analyzable within the SCEV
3655 /// framework. This primarily includes integer types, and it can optionally
3656 /// include pointer types if the ScalarEvolution class has access to
3657 /// target-specific information.
3658 bool ScalarEvolution::isSCEVable(Type *Ty) const {
3659   // Integers and pointers are always SCEVable.
3660   return Ty->isIntegerTy() || Ty->isPointerTy();
3661 }
3662 
3663 /// Return the size in bits of the specified type, for which isSCEVable must
3664 /// return true.
3665 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
3666   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3667   return getDataLayout().getTypeSizeInBits(Ty);
3668 }
3669 
3670 /// Return a type with the same bitwidth as the given type and which represents
3671 /// how SCEV will treat the given type, for which isSCEVable must return
3672 /// true. For pointer types, this is the pointer-sized integer type.
3673 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
3674   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3675 
3676   if (Ty->isIntegerTy())
3677     return Ty;
3678 
3679   // The only other support type is pointer.
3680   assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
3681   return getDataLayout().getIntPtrType(Ty);
3682 }
3683 
3684 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const {
3685   return  getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
3686 }
3687 
3688 const SCEV *ScalarEvolution::getCouldNotCompute() {
3689   return CouldNotCompute.get();
3690 }
3691 
3692 bool ScalarEvolution::checkValidity(const SCEV *S) const {
3693   bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
3694     auto *SU = dyn_cast<SCEVUnknown>(S);
3695     return SU && SU->getValue() == nullptr;
3696   });
3697 
3698   return !ContainsNulls;
3699 }
3700 
3701 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
3702   HasRecMapType::iterator I = HasRecMap.find(S);
3703   if (I != HasRecMap.end())
3704     return I->second;
3705 
3706   bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>);
3707   HasRecMap.insert({S, FoundAddRec});
3708   return FoundAddRec;
3709 }
3710 
3711 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}.
3712 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an
3713 /// offset I, then return {S', I}, else return {\p S, nullptr}.
3714 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) {
3715   const auto *Add = dyn_cast<SCEVAddExpr>(S);
3716   if (!Add)
3717     return {S, nullptr};
3718 
3719   if (Add->getNumOperands() != 2)
3720     return {S, nullptr};
3721 
3722   auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0));
3723   if (!ConstOp)
3724     return {S, nullptr};
3725 
3726   return {Add->getOperand(1), ConstOp->getValue()};
3727 }
3728 
3729 /// Return the ValueOffsetPair set for \p S. \p S can be represented
3730 /// by the value and offset from any ValueOffsetPair in the set.
3731 SetVector<ScalarEvolution::ValueOffsetPair> *
3732 ScalarEvolution::getSCEVValues(const SCEV *S) {
3733   ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
3734   if (SI == ExprValueMap.end())
3735     return nullptr;
3736 #ifndef NDEBUG
3737   if (VerifySCEVMap) {
3738     // Check there is no dangling Value in the set returned.
3739     for (const auto &VE : SI->second)
3740       assert(ValueExprMap.count(VE.first));
3741   }
3742 #endif
3743   return &SI->second;
3744 }
3745 
3746 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
3747 /// cannot be used separately. eraseValueFromMap should be used to remove
3748 /// V from ValueExprMap and ExprValueMap at the same time.
3749 void ScalarEvolution::eraseValueFromMap(Value *V) {
3750   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3751   if (I != ValueExprMap.end()) {
3752     const SCEV *S = I->second;
3753     // Remove {V, 0} from the set of ExprValueMap[S]
3754     if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S))
3755       SV->remove({V, nullptr});
3756 
3757     // Remove {V, Offset} from the set of ExprValueMap[Stripped]
3758     const SCEV *Stripped;
3759     ConstantInt *Offset;
3760     std::tie(Stripped, Offset) = splitAddExpr(S);
3761     if (Offset != nullptr) {
3762       if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped))
3763         SV->remove({V, Offset});
3764     }
3765     ValueExprMap.erase(V);
3766   }
3767 }
3768 
3769 /// Return an existing SCEV if it exists, otherwise analyze the expression and
3770 /// create a new one.
3771 const SCEV *ScalarEvolution::getSCEV(Value *V) {
3772   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3773 
3774   const SCEV *S = getExistingSCEV(V);
3775   if (S == nullptr) {
3776     S = createSCEV(V);
3777     // During PHI resolution, it is possible to create two SCEVs for the same
3778     // V, so it is needed to double check whether V->S is inserted into
3779     // ValueExprMap before insert S->{V, 0} into ExprValueMap.
3780     std::pair<ValueExprMapType::iterator, bool> Pair =
3781         ValueExprMap.insert({SCEVCallbackVH(V, this), S});
3782     if (Pair.second) {
3783       ExprValueMap[S].insert({V, nullptr});
3784 
3785       // If S == Stripped + Offset, add Stripped -> {V, Offset} into
3786       // ExprValueMap.
3787       const SCEV *Stripped = S;
3788       ConstantInt *Offset = nullptr;
3789       std::tie(Stripped, Offset) = splitAddExpr(S);
3790       // If stripped is SCEVUnknown, don't bother to save
3791       // Stripped -> {V, offset}. It doesn't simplify and sometimes even
3792       // increase the complexity of the expansion code.
3793       // If V is GetElementPtrInst, don't save Stripped -> {V, offset}
3794       // because it may generate add/sub instead of GEP in SCEV expansion.
3795       if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) &&
3796           !isa<GetElementPtrInst>(V))
3797         ExprValueMap[Stripped].insert({V, Offset});
3798     }
3799   }
3800   return S;
3801 }
3802 
3803 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
3804   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3805 
3806   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3807   if (I != ValueExprMap.end()) {
3808     const SCEV *S = I->second;
3809     if (checkValidity(S))
3810       return S;
3811     eraseValueFromMap(V);
3812     forgetMemoizedResults(S);
3813   }
3814   return nullptr;
3815 }
3816 
3817 /// Return a SCEV corresponding to -V = -1*V
3818 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
3819                                              SCEV::NoWrapFlags Flags) {
3820   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3821     return getConstant(
3822                cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
3823 
3824   Type *Ty = V->getType();
3825   Ty = getEffectiveSCEVType(Ty);
3826   return getMulExpr(
3827       V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags);
3828 }
3829 
3830 /// Return a SCEV corresponding to ~V = -1-V
3831 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
3832   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3833     return getConstant(
3834                 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
3835 
3836   Type *Ty = V->getType();
3837   Ty = getEffectiveSCEVType(Ty);
3838   const SCEV *AllOnes =
3839                    getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
3840   return getMinusSCEV(AllOnes, V);
3841 }
3842 
3843 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
3844                                           SCEV::NoWrapFlags Flags,
3845                                           unsigned Depth) {
3846   // Fast path: X - X --> 0.
3847   if (LHS == RHS)
3848     return getZero(LHS->getType());
3849 
3850   // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
3851   // makes it so that we cannot make much use of NUW.
3852   auto AddFlags = SCEV::FlagAnyWrap;
3853   const bool RHSIsNotMinSigned =
3854       !getSignedRangeMin(RHS).isMinSignedValue();
3855   if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) {
3856     // Let M be the minimum representable signed value. Then (-1)*RHS
3857     // signed-wraps if and only if RHS is M. That can happen even for
3858     // a NSW subtraction because e.g. (-1)*M signed-wraps even though
3859     // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
3860     // (-1)*RHS, we need to prove that RHS != M.
3861     //
3862     // If LHS is non-negative and we know that LHS - RHS does not
3863     // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
3864     // either by proving that RHS > M or that LHS >= 0.
3865     if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
3866       AddFlags = SCEV::FlagNSW;
3867     }
3868   }
3869 
3870   // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
3871   // RHS is NSW and LHS >= 0.
3872   //
3873   // The difficulty here is that the NSW flag may have been proven
3874   // relative to a loop that is to be found in a recurrence in LHS and
3875   // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
3876   // larger scope than intended.
3877   auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3878 
3879   return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
3880 }
3881 
3882 const SCEV *
3883 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) {
3884   Type *SrcTy = V->getType();
3885   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3886          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3887          "Cannot truncate or zero extend with non-integer arguments!");
3888   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3889     return V;  // No conversion
3890   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
3891     return getTruncateExpr(V, Ty);
3892   return getZeroExtendExpr(V, Ty);
3893 }
3894 
3895 const SCEV *
3896 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
3897                                          Type *Ty) {
3898   Type *SrcTy = V->getType();
3899   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3900          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3901          "Cannot truncate or zero extend with non-integer arguments!");
3902   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3903     return V;  // No conversion
3904   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
3905     return getTruncateExpr(V, Ty);
3906   return getSignExtendExpr(V, Ty);
3907 }
3908 
3909 const SCEV *
3910 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
3911   Type *SrcTy = V->getType();
3912   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3913          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3914          "Cannot noop or zero extend with non-integer arguments!");
3915   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3916          "getNoopOrZeroExtend cannot truncate!");
3917   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3918     return V;  // No conversion
3919   return getZeroExtendExpr(V, Ty);
3920 }
3921 
3922 const SCEV *
3923 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
3924   Type *SrcTy = V->getType();
3925   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3926          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3927          "Cannot noop or sign extend with non-integer arguments!");
3928   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3929          "getNoopOrSignExtend cannot truncate!");
3930   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3931     return V;  // No conversion
3932   return getSignExtendExpr(V, Ty);
3933 }
3934 
3935 const SCEV *
3936 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
3937   Type *SrcTy = V->getType();
3938   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3939          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3940          "Cannot noop or any extend with non-integer arguments!");
3941   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3942          "getNoopOrAnyExtend cannot truncate!");
3943   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3944     return V;  // No conversion
3945   return getAnyExtendExpr(V, Ty);
3946 }
3947 
3948 const SCEV *
3949 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
3950   Type *SrcTy = V->getType();
3951   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3952          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3953          "Cannot truncate or noop with non-integer arguments!");
3954   assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
3955          "getTruncateOrNoop cannot extend!");
3956   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3957     return V;  // No conversion
3958   return getTruncateExpr(V, Ty);
3959 }
3960 
3961 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
3962                                                         const SCEV *RHS) {
3963   const SCEV *PromotedLHS = LHS;
3964   const SCEV *PromotedRHS = RHS;
3965 
3966   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3967     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3968   else
3969     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3970 
3971   return getUMaxExpr(PromotedLHS, PromotedRHS);
3972 }
3973 
3974 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
3975                                                         const SCEV *RHS) {
3976   const SCEV *PromotedLHS = LHS;
3977   const SCEV *PromotedRHS = RHS;
3978 
3979   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3980     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3981   else
3982     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3983 
3984   return getUMinExpr(PromotedLHS, PromotedRHS);
3985 }
3986 
3987 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
3988   // A pointer operand may evaluate to a nonpointer expression, such as null.
3989   if (!V->getType()->isPointerTy())
3990     return V;
3991 
3992   if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
3993     return getPointerBase(Cast->getOperand());
3994   } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
3995     const SCEV *PtrOp = nullptr;
3996     for (const SCEV *NAryOp : NAry->operands()) {
3997       if (NAryOp->getType()->isPointerTy()) {
3998         // Cannot find the base of an expression with multiple pointer operands.
3999         if (PtrOp)
4000           return V;
4001         PtrOp = NAryOp;
4002       }
4003     }
4004     if (!PtrOp)
4005       return V;
4006     return getPointerBase(PtrOp);
4007   }
4008   return V;
4009 }
4010 
4011 /// Push users of the given Instruction onto the given Worklist.
4012 static void
4013 PushDefUseChildren(Instruction *I,
4014                    SmallVectorImpl<Instruction *> &Worklist) {
4015   // Push the def-use children onto the Worklist stack.
4016   for (User *U : I->users())
4017     Worklist.push_back(cast<Instruction>(U));
4018 }
4019 
4020 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) {
4021   SmallVector<Instruction *, 16> Worklist;
4022   PushDefUseChildren(PN, Worklist);
4023 
4024   SmallPtrSet<Instruction *, 8> Visited;
4025   Visited.insert(PN);
4026   while (!Worklist.empty()) {
4027     Instruction *I = Worklist.pop_back_val();
4028     if (!Visited.insert(I).second)
4029       continue;
4030 
4031     auto It = ValueExprMap.find_as(static_cast<Value *>(I));
4032     if (It != ValueExprMap.end()) {
4033       const SCEV *Old = It->second;
4034 
4035       // Short-circuit the def-use traversal if the symbolic name
4036       // ceases to appear in expressions.
4037       if (Old != SymName && !hasOperand(Old, SymName))
4038         continue;
4039 
4040       // SCEVUnknown for a PHI either means that it has an unrecognized
4041       // structure, it's a PHI that's in the progress of being computed
4042       // by createNodeForPHI, or it's a single-value PHI. In the first case,
4043       // additional loop trip count information isn't going to change anything.
4044       // In the second case, createNodeForPHI will perform the necessary
4045       // updates on its own when it gets to that point. In the third, we do
4046       // want to forget the SCEVUnknown.
4047       if (!isa<PHINode>(I) ||
4048           !isa<SCEVUnknown>(Old) ||
4049           (I != PN && Old == SymName)) {
4050         eraseValueFromMap(It->first);
4051         forgetMemoizedResults(Old);
4052       }
4053     }
4054 
4055     PushDefUseChildren(I, Worklist);
4056   }
4057 }
4058 
4059 namespace {
4060 
4061 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
4062 public:
4063   static const SCEV *rewrite(const SCEV *S, const Loop *L,
4064                              ScalarEvolution &SE) {
4065     SCEVInitRewriter Rewriter(L, SE);
4066     const SCEV *Result = Rewriter.visit(S);
4067     return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
4068   }
4069 
4070   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4071     if (!SE.isLoopInvariant(Expr, L))
4072       Valid = false;
4073     return Expr;
4074   }
4075 
4076   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4077     // Only allow AddRecExprs for this loop.
4078     if (Expr->getLoop() == L)
4079       return Expr->getStart();
4080     Valid = false;
4081     return Expr;
4082   }
4083 
4084   bool isValid() { return Valid; }
4085 
4086 private:
4087   explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
4088       : SCEVRewriteVisitor(SE), L(L) {}
4089 
4090   const Loop *L;
4091   bool Valid = true;
4092 };
4093 
4094 /// This class evaluates the compare condition by matching it against the
4095 /// condition of loop latch. If there is a match we assume a true value
4096 /// for the condition while building SCEV nodes.
4097 class SCEVBackedgeConditionFolder
4098     : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> {
4099 public:
4100   static const SCEV *rewrite(const SCEV *S, const Loop *L,
4101                              ScalarEvolution &SE) {
4102     bool IsPosBECond = false;
4103     Value *BECond = nullptr;
4104     if (BasicBlock *Latch = L->getLoopLatch()) {
4105       BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator());
4106       if (BI && BI->isConditional()) {
4107         assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
4108                "Both outgoing branches should not target same header!");
4109         BECond = BI->getCondition();
4110         IsPosBECond = BI->getSuccessor(0) == L->getHeader();
4111       } else {
4112         return S;
4113       }
4114     }
4115     SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE);
4116     return Rewriter.visit(S);
4117   }
4118 
4119   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4120     const SCEV *Result = Expr;
4121     bool InvariantF = SE.isLoopInvariant(Expr, L);
4122 
4123     if (!InvariantF) {
4124       Instruction *I = cast<Instruction>(Expr->getValue());
4125       switch (I->getOpcode()) {
4126       case Instruction::Select: {
4127         SelectInst *SI = cast<SelectInst>(I);
4128         Optional<const SCEV *> Res =
4129             compareWithBackedgeCondition(SI->getCondition());
4130         if (Res.hasValue()) {
4131           bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne();
4132           Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue());
4133         }
4134         break;
4135       }
4136       default: {
4137         Optional<const SCEV *> Res = compareWithBackedgeCondition(I);
4138         if (Res.hasValue())
4139           Result = Res.getValue();
4140         break;
4141       }
4142       }
4143     }
4144     return Result;
4145   }
4146 
4147 private:
4148   explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond,
4149                                        bool IsPosBECond, ScalarEvolution &SE)
4150       : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond),
4151         IsPositiveBECond(IsPosBECond) {}
4152 
4153   Optional<const SCEV *> compareWithBackedgeCondition(Value *IC);
4154 
4155   const Loop *L;
4156   /// Loop back condition.
4157   Value *BackedgeCond = nullptr;
4158   /// Set to true if loop back is on positive branch condition.
4159   bool IsPositiveBECond;
4160 };
4161 
4162 Optional<const SCEV *>
4163 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) {
4164 
4165   // If value matches the backedge condition for loop latch,
4166   // then return a constant evolution node based on loopback
4167   // branch taken.
4168   if (BackedgeCond == IC)
4169     return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext()))
4170                             : SE.getZero(Type::getInt1Ty(SE.getContext()));
4171   return None;
4172 }
4173 
4174 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
4175 public:
4176   static const SCEV *rewrite(const SCEV *S, const Loop *L,
4177                              ScalarEvolution &SE) {
4178     SCEVShiftRewriter Rewriter(L, SE);
4179     const SCEV *Result = Rewriter.visit(S);
4180     return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
4181   }
4182 
4183   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4184     // Only allow AddRecExprs for this loop.
4185     if (!SE.isLoopInvariant(Expr, L))
4186       Valid = false;
4187     return Expr;
4188   }
4189 
4190   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4191     if (Expr->getLoop() == L && Expr->isAffine())
4192       return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
4193     Valid = false;
4194     return Expr;
4195   }
4196 
4197   bool isValid() { return Valid; }
4198 
4199 private:
4200   explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
4201       : SCEVRewriteVisitor(SE), L(L) {}
4202 
4203   const Loop *L;
4204   bool Valid = true;
4205 };
4206 
4207 } // end anonymous namespace
4208 
4209 SCEV::NoWrapFlags
4210 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
4211   if (!AR->isAffine())
4212     return SCEV::FlagAnyWrap;
4213 
4214   using OBO = OverflowingBinaryOperator;
4215 
4216   SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
4217 
4218   if (!AR->hasNoSignedWrap()) {
4219     ConstantRange AddRecRange = getSignedRange(AR);
4220     ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
4221 
4222     auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4223         Instruction::Add, IncRange, OBO::NoSignedWrap);
4224     if (NSWRegion.contains(AddRecRange))
4225       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
4226   }
4227 
4228   if (!AR->hasNoUnsignedWrap()) {
4229     ConstantRange AddRecRange = getUnsignedRange(AR);
4230     ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
4231 
4232     auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4233         Instruction::Add, IncRange, OBO::NoUnsignedWrap);
4234     if (NUWRegion.contains(AddRecRange))
4235       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
4236   }
4237 
4238   return Result;
4239 }
4240 
4241 namespace {
4242 
4243 /// Represents an abstract binary operation.  This may exist as a
4244 /// normal instruction or constant expression, or may have been
4245 /// derived from an expression tree.
4246 struct BinaryOp {
4247   unsigned Opcode;
4248   Value *LHS;
4249   Value *RHS;
4250   bool IsNSW = false;
4251   bool IsNUW = false;
4252 
4253   /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
4254   /// constant expression.
4255   Operator *Op = nullptr;
4256 
4257   explicit BinaryOp(Operator *Op)
4258       : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
4259         Op(Op) {
4260     if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
4261       IsNSW = OBO->hasNoSignedWrap();
4262       IsNUW = OBO->hasNoUnsignedWrap();
4263     }
4264   }
4265 
4266   explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
4267                     bool IsNUW = false)
4268       : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {}
4269 };
4270 
4271 } // end anonymous namespace
4272 
4273 /// Try to map \p V into a BinaryOp, and return \c None on failure.
4274 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) {
4275   auto *Op = dyn_cast<Operator>(V);
4276   if (!Op)
4277     return None;
4278 
4279   // Implementation detail: all the cleverness here should happen without
4280   // creating new SCEV expressions -- our caller knowns tricks to avoid creating
4281   // SCEV expressions when possible, and we should not break that.
4282 
4283   switch (Op->getOpcode()) {
4284   case Instruction::Add:
4285   case Instruction::Sub:
4286   case Instruction::Mul:
4287   case Instruction::UDiv:
4288   case Instruction::URem:
4289   case Instruction::And:
4290   case Instruction::Or:
4291   case Instruction::AShr:
4292   case Instruction::Shl:
4293     return BinaryOp(Op);
4294 
4295   case Instruction::Xor:
4296     if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
4297       // If the RHS of the xor is a signmask, then this is just an add.
4298       // Instcombine turns add of signmask into xor as a strength reduction step.
4299       if (RHSC->getValue().isSignMask())
4300         return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
4301     return BinaryOp(Op);
4302 
4303   case Instruction::LShr:
4304     // Turn logical shift right of a constant into a unsigned divide.
4305     if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
4306       uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
4307 
4308       // If the shift count is not less than the bitwidth, the result of
4309       // the shift is undefined. Don't try to analyze it, because the
4310       // resolution chosen here may differ from the resolution chosen in
4311       // other parts of the compiler.
4312       if (SA->getValue().ult(BitWidth)) {
4313         Constant *X =
4314             ConstantInt::get(SA->getContext(),
4315                              APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
4316         return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
4317       }
4318     }
4319     return BinaryOp(Op);
4320 
4321   case Instruction::ExtractValue: {
4322     auto *EVI = cast<ExtractValueInst>(Op);
4323     if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
4324       break;
4325 
4326     auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand());
4327     if (!CI)
4328       break;
4329 
4330     if (auto *F = CI->getCalledFunction())
4331       switch (F->getIntrinsicID()) {
4332       case Intrinsic::sadd_with_overflow:
4333       case Intrinsic::uadd_with_overflow:
4334         if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT))
4335           return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4336                           CI->getArgOperand(1));
4337 
4338         // Now that we know that all uses of the arithmetic-result component of
4339         // CI are guarded by the overflow check, we can go ahead and pretend
4340         // that the arithmetic is non-overflowing.
4341         if (F->getIntrinsicID() == Intrinsic::sadd_with_overflow)
4342           return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4343                           CI->getArgOperand(1), /* IsNSW = */ true,
4344                           /* IsNUW = */ false);
4345         else
4346           return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4347                           CI->getArgOperand(1), /* IsNSW = */ false,
4348                           /* IsNUW*/ true);
4349       case Intrinsic::ssub_with_overflow:
4350       case Intrinsic::usub_with_overflow:
4351         if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT))
4352           return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
4353                           CI->getArgOperand(1));
4354 
4355         // The same reasoning as sadd/uadd above.
4356         if (F->getIntrinsicID() == Intrinsic::ssub_with_overflow)
4357           return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
4358                           CI->getArgOperand(1), /* IsNSW = */ true,
4359                           /* IsNUW = */ false);
4360         else
4361           return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
4362                           CI->getArgOperand(1), /* IsNSW = */ false,
4363                           /* IsNUW = */ true);
4364       case Intrinsic::smul_with_overflow:
4365       case Intrinsic::umul_with_overflow:
4366         return BinaryOp(Instruction::Mul, CI->getArgOperand(0),
4367                         CI->getArgOperand(1));
4368       default:
4369         break;
4370       }
4371   }
4372 
4373   default:
4374     break;
4375   }
4376 
4377   return None;
4378 }
4379 
4380 /// Helper function to createAddRecFromPHIWithCasts. We have a phi
4381 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
4382 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
4383 /// way. This function checks if \p Op, an operand of this SCEVAddExpr,
4384 /// follows one of the following patterns:
4385 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4386 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4387 /// If the SCEV expression of \p Op conforms with one of the expected patterns
4388 /// we return the type of the truncation operation, and indicate whether the
4389 /// truncated type should be treated as signed/unsigned by setting
4390 /// \p Signed to true/false, respectively.
4391 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
4392                                bool &Signed, ScalarEvolution &SE) {
4393   // The case where Op == SymbolicPHI (that is, with no type conversions on
4394   // the way) is handled by the regular add recurrence creating logic and
4395   // would have already been triggered in createAddRecForPHI. Reaching it here
4396   // means that createAddRecFromPHI had failed for this PHI before (e.g.,
4397   // because one of the other operands of the SCEVAddExpr updating this PHI is
4398   // not invariant).
4399   //
4400   // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
4401   // this case predicates that allow us to prove that Op == SymbolicPHI will
4402   // be added.
4403   if (Op == SymbolicPHI)
4404     return nullptr;
4405 
4406   unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
4407   unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
4408   if (SourceBits != NewBits)
4409     return nullptr;
4410 
4411   const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op);
4412   const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op);
4413   if (!SExt && !ZExt)
4414     return nullptr;
4415   const SCEVTruncateExpr *Trunc =
4416       SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand())
4417            : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand());
4418   if (!Trunc)
4419     return nullptr;
4420   const SCEV *X = Trunc->getOperand();
4421   if (X != SymbolicPHI)
4422     return nullptr;
4423   Signed = SExt != nullptr;
4424   return Trunc->getType();
4425 }
4426 
4427 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
4428   if (!PN->getType()->isIntegerTy())
4429     return nullptr;
4430   const Loop *L = LI.getLoopFor(PN->getParent());
4431   if (!L || L->getHeader() != PN->getParent())
4432     return nullptr;
4433   return L;
4434 }
4435 
4436 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
4437 // computation that updates the phi follows the following pattern:
4438 //   (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
4439 // which correspond to a phi->trunc->sext/zext->add->phi update chain.
4440 // If so, try to see if it can be rewritten as an AddRecExpr under some
4441 // Predicates. If successful, return them as a pair. Also cache the results
4442 // of the analysis.
4443 //
4444 // Example usage scenario:
4445 //    Say the Rewriter is called for the following SCEV:
4446 //         8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4447 //    where:
4448 //         %X = phi i64 (%Start, %BEValue)
4449 //    It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
4450 //    and call this function with %SymbolicPHI = %X.
4451 //
4452 //    The analysis will find that the value coming around the backedge has
4453 //    the following SCEV:
4454 //         BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4455 //    Upon concluding that this matches the desired pattern, the function
4456 //    will return the pair {NewAddRec, SmallPredsVec} where:
4457 //         NewAddRec = {%Start,+,%Step}
4458 //         SmallPredsVec = {P1, P2, P3} as follows:
4459 //           P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
4460 //           P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
4461 //           P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
4462 //    The returned pair means that SymbolicPHI can be rewritten into NewAddRec
4463 //    under the predicates {P1,P2,P3}.
4464 //    This predicated rewrite will be cached in PredicatedSCEVRewrites:
4465 //         PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
4466 //
4467 // TODO's:
4468 //
4469 // 1) Extend the Induction descriptor to also support inductions that involve
4470 //    casts: When needed (namely, when we are called in the context of the
4471 //    vectorizer induction analysis), a Set of cast instructions will be
4472 //    populated by this method, and provided back to isInductionPHI. This is
4473 //    needed to allow the vectorizer to properly record them to be ignored by
4474 //    the cost model and to avoid vectorizing them (otherwise these casts,
4475 //    which are redundant under the runtime overflow checks, will be
4476 //    vectorized, which can be costly).
4477 //
4478 // 2) Support additional induction/PHISCEV patterns: We also want to support
4479 //    inductions where the sext-trunc / zext-trunc operations (partly) occur
4480 //    after the induction update operation (the induction increment):
4481 //
4482 //      (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
4483 //    which correspond to a phi->add->trunc->sext/zext->phi update chain.
4484 //
4485 //      (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
4486 //    which correspond to a phi->trunc->add->sext/zext->phi update chain.
4487 //
4488 // 3) Outline common code with createAddRecFromPHI to avoid duplication.
4489 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4490 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
4491   SmallVector<const SCEVPredicate *, 3> Predicates;
4492 
4493   // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
4494   // return an AddRec expression under some predicate.
4495 
4496   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
4497   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
4498   assert(L && "Expecting an integer loop header phi");
4499 
4500   // The loop may have multiple entrances or multiple exits; we can analyze
4501   // this phi as an addrec if it has a unique entry value and a unique
4502   // backedge value.
4503   Value *BEValueV = nullptr, *StartValueV = nullptr;
4504   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4505     Value *V = PN->getIncomingValue(i);
4506     if (L->contains(PN->getIncomingBlock(i))) {
4507       if (!BEValueV) {
4508         BEValueV = V;
4509       } else if (BEValueV != V) {
4510         BEValueV = nullptr;
4511         break;
4512       }
4513     } else if (!StartValueV) {
4514       StartValueV = V;
4515     } else if (StartValueV != V) {
4516       StartValueV = nullptr;
4517       break;
4518     }
4519   }
4520   if (!BEValueV || !StartValueV)
4521     return None;
4522 
4523   const SCEV *BEValue = getSCEV(BEValueV);
4524 
4525   // If the value coming around the backedge is an add with the symbolic
4526   // value we just inserted, possibly with casts that we can ignore under
4527   // an appropriate runtime guard, then we found a simple induction variable!
4528   const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
4529   if (!Add)
4530     return None;
4531 
4532   // If there is a single occurrence of the symbolic value, possibly
4533   // casted, replace it with a recurrence.
4534   unsigned FoundIndex = Add->getNumOperands();
4535   Type *TruncTy = nullptr;
4536   bool Signed;
4537   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4538     if ((TruncTy =
4539              isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
4540       if (FoundIndex == e) {
4541         FoundIndex = i;
4542         break;
4543       }
4544 
4545   if (FoundIndex == Add->getNumOperands())
4546     return None;
4547 
4548   // Create an add with everything but the specified operand.
4549   SmallVector<const SCEV *, 8> Ops;
4550   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4551     if (i != FoundIndex)
4552       Ops.push_back(Add->getOperand(i));
4553   const SCEV *Accum = getAddExpr(Ops);
4554 
4555   // The runtime checks will not be valid if the step amount is
4556   // varying inside the loop.
4557   if (!isLoopInvariant(Accum, L))
4558     return None;
4559 
4560   // *** Part2: Create the predicates
4561 
4562   // Analysis was successful: we have a phi-with-cast pattern for which we
4563   // can return an AddRec expression under the following predicates:
4564   //
4565   // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
4566   //     fits within the truncated type (does not overflow) for i = 0 to n-1.
4567   // P2: An Equal predicate that guarantees that
4568   //     Start = (Ext ix (Trunc iy (Start) to ix) to iy)
4569   // P3: An Equal predicate that guarantees that
4570   //     Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
4571   //
4572   // As we next prove, the above predicates guarantee that:
4573   //     Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
4574   //
4575   //
4576   // More formally, we want to prove that:
4577   //     Expr(i+1) = Start + (i+1) * Accum
4578   //               = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4579   //
4580   // Given that:
4581   // 1) Expr(0) = Start
4582   // 2) Expr(1) = Start + Accum
4583   //            = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
4584   // 3) Induction hypothesis (step i):
4585   //    Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
4586   //
4587   // Proof:
4588   //  Expr(i+1) =
4589   //   = Start + (i+1)*Accum
4590   //   = (Start + i*Accum) + Accum
4591   //   = Expr(i) + Accum
4592   //   = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
4593   //                                                             :: from step i
4594   //
4595   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
4596   //
4597   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
4598   //     + (Ext ix (Trunc iy (Accum) to ix) to iy)
4599   //     + Accum                                                     :: from P3
4600   //
4601   //   = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
4602   //     + Accum                            :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
4603   //
4604   //   = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
4605   //   = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4606   //
4607   // By induction, the same applies to all iterations 1<=i<n:
4608   //
4609 
4610   // Create a truncated addrec for which we will add a no overflow check (P1).
4611   const SCEV *StartVal = getSCEV(StartValueV);
4612   const SCEV *PHISCEV =
4613       getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
4614                     getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap);
4615 
4616   // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
4617   // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
4618   // will be constant.
4619   //
4620   //  If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
4621   // add P1.
4622   if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
4623     SCEVWrapPredicate::IncrementWrapFlags AddedFlags =
4624         Signed ? SCEVWrapPredicate::IncrementNSSW
4625                : SCEVWrapPredicate::IncrementNUSW;
4626     const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
4627     Predicates.push_back(AddRecPred);
4628   }
4629 
4630   // Create the Equal Predicates P2,P3:
4631 
4632   // It is possible that the predicates P2 and/or P3 are computable at
4633   // compile time due to StartVal and/or Accum being constants.
4634   // If either one is, then we can check that now and escape if either P2
4635   // or P3 is false.
4636 
4637   // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
4638   // for each of StartVal and Accum
4639   auto GetExtendedExpr = [&](const SCEV *Expr) -> const SCEV * {
4640     assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant");
4641     const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
4642     const SCEV *ExtendedExpr =
4643         Signed ? getSignExtendExpr(TruncatedExpr, Expr->getType())
4644                : getZeroExtendExpr(TruncatedExpr, Expr->getType());
4645     return ExtendedExpr;
4646   };
4647 
4648   // Given:
4649   //  ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
4650   //               = GetExtendedExpr(Expr)
4651   // Determine whether the predicate P: Expr == ExtendedExpr
4652   // is known to be false at compile time
4653   auto PredIsKnownFalse = [&](const SCEV *Expr,
4654                               const SCEV *ExtendedExpr) -> bool {
4655     return Expr != ExtendedExpr &&
4656            isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr);
4657   };
4658 
4659   const SCEV *StartExtended = GetExtendedExpr(StartVal);
4660   if (PredIsKnownFalse(StartVal, StartExtended)) {
4661     DEBUG(dbgs() << "P2 is compile-time false\n";);
4662     return None;
4663   }
4664 
4665   const SCEV *AccumExtended = GetExtendedExpr(Accum);
4666   if (PredIsKnownFalse(Accum, AccumExtended)) {
4667     DEBUG(dbgs() << "P3 is compile-time false\n";);
4668     return None;
4669   }
4670 
4671   auto AppendPredicate = [&](const SCEV *Expr,
4672                              const SCEV *ExtendedExpr) -> void {
4673     if (Expr != ExtendedExpr &&
4674         !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
4675       const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
4676       DEBUG (dbgs() << "Added Predicate: " << *Pred);
4677       Predicates.push_back(Pred);
4678     }
4679   };
4680 
4681   AppendPredicate(StartVal, StartExtended);
4682   AppendPredicate(Accum, AccumExtended);
4683 
4684   // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
4685   // which the casts had been folded away. The caller can rewrite SymbolicPHI
4686   // into NewAR if it will also add the runtime overflow checks specified in
4687   // Predicates.
4688   auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap);
4689 
4690   std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
4691       std::make_pair(NewAR, Predicates);
4692   // Remember the result of the analysis for this SCEV at this locayyytion.
4693   PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
4694   return PredRewrite;
4695 }
4696 
4697 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4698 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) {
4699   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
4700   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
4701   if (!L)
4702     return None;
4703 
4704   // Check to see if we already analyzed this PHI.
4705   auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
4706   if (I != PredicatedSCEVRewrites.end()) {
4707     std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
4708         I->second;
4709     // Analysis was done before and failed to create an AddRec:
4710     if (Rewrite.first == SymbolicPHI)
4711       return None;
4712     // Analysis was done before and succeeded to create an AddRec under
4713     // a predicate:
4714     assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec");
4715     assert(!(Rewrite.second).empty() && "Expected to find Predicates");
4716     return Rewrite;
4717   }
4718 
4719   Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4720     Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
4721 
4722   // Record in the cache that the analysis failed
4723   if (!Rewrite) {
4724     SmallVector<const SCEVPredicate *, 3> Predicates;
4725     PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
4726     return None;
4727   }
4728 
4729   return Rewrite;
4730 }
4731 
4732 /// A helper function for createAddRecFromPHI to handle simple cases.
4733 ///
4734 /// This function tries to find an AddRec expression for the simplest (yet most
4735 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
4736 /// If it fails, createAddRecFromPHI will use a more general, but slow,
4737 /// technique for finding the AddRec expression.
4738 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
4739                                                       Value *BEValueV,
4740                                                       Value *StartValueV) {
4741   const Loop *L = LI.getLoopFor(PN->getParent());
4742   assert(L && L->getHeader() == PN->getParent());
4743   assert(BEValueV && StartValueV);
4744 
4745   auto BO = MatchBinaryOp(BEValueV, DT);
4746   if (!BO)
4747     return nullptr;
4748 
4749   if (BO->Opcode != Instruction::Add)
4750     return nullptr;
4751 
4752   const SCEV *Accum = nullptr;
4753   if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
4754     Accum = getSCEV(BO->RHS);
4755   else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
4756     Accum = getSCEV(BO->LHS);
4757 
4758   if (!Accum)
4759     return nullptr;
4760 
4761   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4762   if (BO->IsNUW)
4763     Flags = setFlags(Flags, SCEV::FlagNUW);
4764   if (BO->IsNSW)
4765     Flags = setFlags(Flags, SCEV::FlagNSW);
4766 
4767   const SCEV *StartVal = getSCEV(StartValueV);
4768   const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
4769 
4770   ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
4771 
4772   // We can add Flags to the post-inc expression only if we
4773   // know that it is *undefined behavior* for BEValueV to
4774   // overflow.
4775   if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
4776     if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
4777       (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
4778 
4779   return PHISCEV;
4780 }
4781 
4782 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
4783   const Loop *L = LI.getLoopFor(PN->getParent());
4784   if (!L || L->getHeader() != PN->getParent())
4785     return nullptr;
4786 
4787   // The loop may have multiple entrances or multiple exits; we can analyze
4788   // this phi as an addrec if it has a unique entry value and a unique
4789   // backedge value.
4790   Value *BEValueV = nullptr, *StartValueV = nullptr;
4791   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4792     Value *V = PN->getIncomingValue(i);
4793     if (L->contains(PN->getIncomingBlock(i))) {
4794       if (!BEValueV) {
4795         BEValueV = V;
4796       } else if (BEValueV != V) {
4797         BEValueV = nullptr;
4798         break;
4799       }
4800     } else if (!StartValueV) {
4801       StartValueV = V;
4802     } else if (StartValueV != V) {
4803       StartValueV = nullptr;
4804       break;
4805     }
4806   }
4807   if (!BEValueV || !StartValueV)
4808     return nullptr;
4809 
4810   assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
4811          "PHI node already processed?");
4812 
4813   // First, try to find AddRec expression without creating a fictituos symbolic
4814   // value for PN.
4815   if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
4816     return S;
4817 
4818   // Handle PHI node value symbolically.
4819   const SCEV *SymbolicName = getUnknown(PN);
4820   ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName});
4821 
4822   // Using this symbolic name for the PHI, analyze the value coming around
4823   // the back-edge.
4824   const SCEV *BEValue = getSCEV(BEValueV);
4825 
4826   // NOTE: If BEValue is loop invariant, we know that the PHI node just
4827   // has a special value for the first iteration of the loop.
4828 
4829   // If the value coming around the backedge is an add with the symbolic
4830   // value we just inserted, then we found a simple induction variable!
4831   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
4832     // If there is a single occurrence of the symbolic value, replace it
4833     // with a recurrence.
4834     unsigned FoundIndex = Add->getNumOperands();
4835     for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4836       if (Add->getOperand(i) == SymbolicName)
4837         if (FoundIndex == e) {
4838           FoundIndex = i;
4839           break;
4840         }
4841 
4842     if (FoundIndex != Add->getNumOperands()) {
4843       // Create an add with everything but the specified operand.
4844       SmallVector<const SCEV *, 8> Ops;
4845       for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4846         if (i != FoundIndex)
4847           Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i),
4848                                                              L, *this));
4849       const SCEV *Accum = getAddExpr(Ops);
4850 
4851       // This is not a valid addrec if the step amount is varying each
4852       // loop iteration, but is not itself an addrec in this loop.
4853       if (isLoopInvariant(Accum, L) ||
4854           (isa<SCEVAddRecExpr>(Accum) &&
4855            cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
4856         SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4857 
4858         if (auto BO = MatchBinaryOp(BEValueV, DT)) {
4859           if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
4860             if (BO->IsNUW)
4861               Flags = setFlags(Flags, SCEV::FlagNUW);
4862             if (BO->IsNSW)
4863               Flags = setFlags(Flags, SCEV::FlagNSW);
4864           }
4865         } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
4866           // If the increment is an inbounds GEP, then we know the address
4867           // space cannot be wrapped around. We cannot make any guarantee
4868           // about signed or unsigned overflow because pointers are
4869           // unsigned but we may have a negative index from the base
4870           // pointer. We can guarantee that no unsigned wrap occurs if the
4871           // indices form a positive value.
4872           if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
4873             Flags = setFlags(Flags, SCEV::FlagNW);
4874 
4875             const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
4876             if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
4877               Flags = setFlags(Flags, SCEV::FlagNUW);
4878           }
4879 
4880           // We cannot transfer nuw and nsw flags from subtraction
4881           // operations -- sub nuw X, Y is not the same as add nuw X, -Y
4882           // for instance.
4883         }
4884 
4885         const SCEV *StartVal = getSCEV(StartValueV);
4886         const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
4887 
4888         // Okay, for the entire analysis of this edge we assumed the PHI
4889         // to be symbolic.  We now need to go back and purge all of the
4890         // entries for the scalars that use the symbolic expression.
4891         forgetSymbolicName(PN, SymbolicName);
4892         ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
4893 
4894         // We can add Flags to the post-inc expression only if we
4895         // know that it is *undefined behavior* for BEValueV to
4896         // overflow.
4897         if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
4898           if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
4899             (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
4900 
4901         return PHISCEV;
4902       }
4903     }
4904   } else {
4905     // Otherwise, this could be a loop like this:
4906     //     i = 0;  for (j = 1; ..; ++j) { ....  i = j; }
4907     // In this case, j = {1,+,1}  and BEValue is j.
4908     // Because the other in-value of i (0) fits the evolution of BEValue
4909     // i really is an addrec evolution.
4910     //
4911     // We can generalize this saying that i is the shifted value of BEValue
4912     // by one iteration:
4913     //   PHI(f(0), f({1,+,1})) --> f({0,+,1})
4914     const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
4915     const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this);
4916     if (Shifted != getCouldNotCompute() &&
4917         Start != getCouldNotCompute()) {
4918       const SCEV *StartVal = getSCEV(StartValueV);
4919       if (Start == StartVal) {
4920         // Okay, for the entire analysis of this edge we assumed the PHI
4921         // to be symbolic.  We now need to go back and purge all of the
4922         // entries for the scalars that use the symbolic expression.
4923         forgetSymbolicName(PN, SymbolicName);
4924         ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted;
4925         return Shifted;
4926       }
4927     }
4928   }
4929 
4930   // Remove the temporary PHI node SCEV that has been inserted while intending
4931   // to create an AddRecExpr for this PHI node. We can not keep this temporary
4932   // as it will prevent later (possibly simpler) SCEV expressions to be added
4933   // to the ValueExprMap.
4934   eraseValueFromMap(PN);
4935 
4936   return nullptr;
4937 }
4938 
4939 // Checks if the SCEV S is available at BB.  S is considered available at BB
4940 // if S can be materialized at BB without introducing a fault.
4941 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
4942                                BasicBlock *BB) {
4943   struct CheckAvailable {
4944     bool TraversalDone = false;
4945     bool Available = true;
4946 
4947     const Loop *L = nullptr;  // The loop BB is in (can be nullptr)
4948     BasicBlock *BB = nullptr;
4949     DominatorTree &DT;
4950 
4951     CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
4952       : L(L), BB(BB), DT(DT) {}
4953 
4954     bool setUnavailable() {
4955       TraversalDone = true;
4956       Available = false;
4957       return false;
4958     }
4959 
4960     bool follow(const SCEV *S) {
4961       switch (S->getSCEVType()) {
4962       case scConstant: case scTruncate: case scZeroExtend: case scSignExtend:
4963       case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr:
4964         // These expressions are available if their operand(s) is/are.
4965         return true;
4966 
4967       case scAddRecExpr: {
4968         // We allow add recurrences that are on the loop BB is in, or some
4969         // outer loop.  This guarantees availability because the value of the
4970         // add recurrence at BB is simply the "current" value of the induction
4971         // variable.  We can relax this in the future; for instance an add
4972         // recurrence on a sibling dominating loop is also available at BB.
4973         const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
4974         if (L && (ARLoop == L || ARLoop->contains(L)))
4975           return true;
4976 
4977         return setUnavailable();
4978       }
4979 
4980       case scUnknown: {
4981         // For SCEVUnknown, we check for simple dominance.
4982         const auto *SU = cast<SCEVUnknown>(S);
4983         Value *V = SU->getValue();
4984 
4985         if (isa<Argument>(V))
4986           return false;
4987 
4988         if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
4989           return false;
4990 
4991         return setUnavailable();
4992       }
4993 
4994       case scUDivExpr:
4995       case scCouldNotCompute:
4996         // We do not try to smart about these at all.
4997         return setUnavailable();
4998       }
4999       llvm_unreachable("switch should be fully covered!");
5000     }
5001 
5002     bool isDone() { return TraversalDone; }
5003   };
5004 
5005   CheckAvailable CA(L, BB, DT);
5006   SCEVTraversal<CheckAvailable> ST(CA);
5007 
5008   ST.visitAll(S);
5009   return CA.Available;
5010 }
5011 
5012 // Try to match a control flow sequence that branches out at BI and merges back
5013 // at Merge into a "C ? LHS : RHS" select pattern.  Return true on a successful
5014 // match.
5015 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
5016                           Value *&C, Value *&LHS, Value *&RHS) {
5017   C = BI->getCondition();
5018 
5019   BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
5020   BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
5021 
5022   if (!LeftEdge.isSingleEdge())
5023     return false;
5024 
5025   assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
5026 
5027   Use &LeftUse = Merge->getOperandUse(0);
5028   Use &RightUse = Merge->getOperandUse(1);
5029 
5030   if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
5031     LHS = LeftUse;
5032     RHS = RightUse;
5033     return true;
5034   }
5035 
5036   if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
5037     LHS = RightUse;
5038     RHS = LeftUse;
5039     return true;
5040   }
5041 
5042   return false;
5043 }
5044 
5045 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
5046   auto IsReachable =
5047       [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
5048   if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
5049     const Loop *L = LI.getLoopFor(PN->getParent());
5050 
5051     // We don't want to break LCSSA, even in a SCEV expression tree.
5052     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
5053       if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
5054         return nullptr;
5055 
5056     // Try to match
5057     //
5058     //  br %cond, label %left, label %right
5059     // left:
5060     //  br label %merge
5061     // right:
5062     //  br label %merge
5063     // merge:
5064     //  V = phi [ %x, %left ], [ %y, %right ]
5065     //
5066     // as "select %cond, %x, %y"
5067 
5068     BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
5069     assert(IDom && "At least the entry block should dominate PN");
5070 
5071     auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
5072     Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
5073 
5074     if (BI && BI->isConditional() &&
5075         BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
5076         IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
5077         IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
5078       return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
5079   }
5080 
5081   return nullptr;
5082 }
5083 
5084 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
5085   if (const SCEV *S = createAddRecFromPHI(PN))
5086     return S;
5087 
5088   if (const SCEV *S = createNodeFromSelectLikePHI(PN))
5089     return S;
5090 
5091   // If the PHI has a single incoming value, follow that value, unless the
5092   // PHI's incoming blocks are in a different loop, in which case doing so
5093   // risks breaking LCSSA form. Instcombine would normally zap these, but
5094   // it doesn't have DominatorTree information, so it may miss cases.
5095   if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC}))
5096     if (LI.replacementPreservesLCSSAForm(PN, V))
5097       return getSCEV(V);
5098 
5099   // If it's not a loop phi, we can't handle it yet.
5100   return getUnknown(PN);
5101 }
5102 
5103 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I,
5104                                                       Value *Cond,
5105                                                       Value *TrueVal,
5106                                                       Value *FalseVal) {
5107   // Handle "constant" branch or select. This can occur for instance when a
5108   // loop pass transforms an inner loop and moves on to process the outer loop.
5109   if (auto *CI = dyn_cast<ConstantInt>(Cond))
5110     return getSCEV(CI->isOne() ? TrueVal : FalseVal);
5111 
5112   // Try to match some simple smax or umax patterns.
5113   auto *ICI = dyn_cast<ICmpInst>(Cond);
5114   if (!ICI)
5115     return getUnknown(I);
5116 
5117   Value *LHS = ICI->getOperand(0);
5118   Value *RHS = ICI->getOperand(1);
5119 
5120   switch (ICI->getPredicate()) {
5121   case ICmpInst::ICMP_SLT:
5122   case ICmpInst::ICMP_SLE:
5123     std::swap(LHS, RHS);
5124     LLVM_FALLTHROUGH;
5125   case ICmpInst::ICMP_SGT:
5126   case ICmpInst::ICMP_SGE:
5127     // a >s b ? a+x : b+x  ->  smax(a, b)+x
5128     // a >s b ? b+x : a+x  ->  smin(a, b)+x
5129     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5130       const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType());
5131       const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType());
5132       const SCEV *LA = getSCEV(TrueVal);
5133       const SCEV *RA = getSCEV(FalseVal);
5134       const SCEV *LDiff = getMinusSCEV(LA, LS);
5135       const SCEV *RDiff = getMinusSCEV(RA, RS);
5136       if (LDiff == RDiff)
5137         return getAddExpr(getSMaxExpr(LS, RS), LDiff);
5138       LDiff = getMinusSCEV(LA, RS);
5139       RDiff = getMinusSCEV(RA, LS);
5140       if (LDiff == RDiff)
5141         return getAddExpr(getSMinExpr(LS, RS), LDiff);
5142     }
5143     break;
5144   case ICmpInst::ICMP_ULT:
5145   case ICmpInst::ICMP_ULE:
5146     std::swap(LHS, RHS);
5147     LLVM_FALLTHROUGH;
5148   case ICmpInst::ICMP_UGT:
5149   case ICmpInst::ICMP_UGE:
5150     // a >u b ? a+x : b+x  ->  umax(a, b)+x
5151     // a >u b ? b+x : a+x  ->  umin(a, b)+x
5152     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5153       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5154       const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType());
5155       const SCEV *LA = getSCEV(TrueVal);
5156       const SCEV *RA = getSCEV(FalseVal);
5157       const SCEV *LDiff = getMinusSCEV(LA, LS);
5158       const SCEV *RDiff = getMinusSCEV(RA, RS);
5159       if (LDiff == RDiff)
5160         return getAddExpr(getUMaxExpr(LS, RS), LDiff);
5161       LDiff = getMinusSCEV(LA, RS);
5162       RDiff = getMinusSCEV(RA, LS);
5163       if (LDiff == RDiff)
5164         return getAddExpr(getUMinExpr(LS, RS), LDiff);
5165     }
5166     break;
5167   case ICmpInst::ICMP_NE:
5168     // n != 0 ? n+x : 1+x  ->  umax(n, 1)+x
5169     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5170         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5171       const SCEV *One = getOne(I->getType());
5172       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5173       const SCEV *LA = getSCEV(TrueVal);
5174       const SCEV *RA = getSCEV(FalseVal);
5175       const SCEV *LDiff = getMinusSCEV(LA, LS);
5176       const SCEV *RDiff = getMinusSCEV(RA, One);
5177       if (LDiff == RDiff)
5178         return getAddExpr(getUMaxExpr(One, LS), LDiff);
5179     }
5180     break;
5181   case ICmpInst::ICMP_EQ:
5182     // n == 0 ? 1+x : n+x  ->  umax(n, 1)+x
5183     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5184         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5185       const SCEV *One = getOne(I->getType());
5186       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5187       const SCEV *LA = getSCEV(TrueVal);
5188       const SCEV *RA = getSCEV(FalseVal);
5189       const SCEV *LDiff = getMinusSCEV(LA, One);
5190       const SCEV *RDiff = getMinusSCEV(RA, LS);
5191       if (LDiff == RDiff)
5192         return getAddExpr(getUMaxExpr(One, LS), LDiff);
5193     }
5194     break;
5195   default:
5196     break;
5197   }
5198 
5199   return getUnknown(I);
5200 }
5201 
5202 /// Expand GEP instructions into add and multiply operations. This allows them
5203 /// to be analyzed by regular SCEV code.
5204 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
5205   // Don't attempt to analyze GEPs over unsized objects.
5206   if (!GEP->getSourceElementType()->isSized())
5207     return getUnknown(GEP);
5208 
5209   SmallVector<const SCEV *, 4> IndexExprs;
5210   for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
5211     IndexExprs.push_back(getSCEV(*Index));
5212   return getGEPExpr(GEP, IndexExprs);
5213 }
5214 
5215 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) {
5216   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5217     return C->getAPInt().countTrailingZeros();
5218 
5219   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
5220     return std::min(GetMinTrailingZeros(T->getOperand()),
5221                     (uint32_t)getTypeSizeInBits(T->getType()));
5222 
5223   if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
5224     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5225     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5226                ? getTypeSizeInBits(E->getType())
5227                : OpRes;
5228   }
5229 
5230   if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
5231     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5232     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5233                ? getTypeSizeInBits(E->getType())
5234                : OpRes;
5235   }
5236 
5237   if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
5238     // The result is the min of all operands results.
5239     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5240     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5241       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5242     return MinOpRes;
5243   }
5244 
5245   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
5246     // The result is the sum of all operands results.
5247     uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
5248     uint32_t BitWidth = getTypeSizeInBits(M->getType());
5249     for (unsigned i = 1, e = M->getNumOperands();
5250          SumOpRes != BitWidth && i != e; ++i)
5251       SumOpRes =
5252           std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth);
5253     return SumOpRes;
5254   }
5255 
5256   if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
5257     // The result is the min of all operands results.
5258     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5259     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5260       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5261     return MinOpRes;
5262   }
5263 
5264   if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
5265     // The result is the min of all operands results.
5266     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5267     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5268       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5269     return MinOpRes;
5270   }
5271 
5272   if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
5273     // The result is the min of all operands results.
5274     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5275     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5276       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5277     return MinOpRes;
5278   }
5279 
5280   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5281     // For a SCEVUnknown, ask ValueTracking.
5282     KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT);
5283     return Known.countMinTrailingZeros();
5284   }
5285 
5286   // SCEVUDivExpr
5287   return 0;
5288 }
5289 
5290 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
5291   auto I = MinTrailingZerosCache.find(S);
5292   if (I != MinTrailingZerosCache.end())
5293     return I->second;
5294 
5295   uint32_t Result = GetMinTrailingZerosImpl(S);
5296   auto InsertPair = MinTrailingZerosCache.insert({S, Result});
5297   assert(InsertPair.second && "Should insert a new key");
5298   return InsertPair.first->second;
5299 }
5300 
5301 /// Helper method to assign a range to V from metadata present in the IR.
5302 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
5303   if (Instruction *I = dyn_cast<Instruction>(V))
5304     if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
5305       return getConstantRangeFromMetadata(*MD);
5306 
5307   return None;
5308 }
5309 
5310 /// Determine the range for a particular SCEV.  If SignHint is
5311 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
5312 /// with a "cleaner" unsigned (resp. signed) representation.
5313 const ConstantRange &
5314 ScalarEvolution::getRangeRef(const SCEV *S,
5315                              ScalarEvolution::RangeSignHint SignHint) {
5316   DenseMap<const SCEV *, ConstantRange> &Cache =
5317       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
5318                                                        : SignedRanges;
5319 
5320   // See if we've computed this range already.
5321   DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
5322   if (I != Cache.end())
5323     return I->second;
5324 
5325   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5326     return setRange(C, SignHint, ConstantRange(C->getAPInt()));
5327 
5328   unsigned BitWidth = getTypeSizeInBits(S->getType());
5329   ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
5330 
5331   // If the value has known zeros, the maximum value will have those known zeros
5332   // as well.
5333   uint32_t TZ = GetMinTrailingZeros(S);
5334   if (TZ != 0) {
5335     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
5336       ConservativeResult =
5337           ConstantRange(APInt::getMinValue(BitWidth),
5338                         APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
5339     else
5340       ConservativeResult = ConstantRange(
5341           APInt::getSignedMinValue(BitWidth),
5342           APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
5343   }
5344 
5345   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
5346     ConstantRange X = getRangeRef(Add->getOperand(0), SignHint);
5347     for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
5348       X = X.add(getRangeRef(Add->getOperand(i), SignHint));
5349     return setRange(Add, SignHint, ConservativeResult.intersectWith(X));
5350   }
5351 
5352   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
5353     ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint);
5354     for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
5355       X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint));
5356     return setRange(Mul, SignHint, ConservativeResult.intersectWith(X));
5357   }
5358 
5359   if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
5360     ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint);
5361     for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
5362       X = X.smax(getRangeRef(SMax->getOperand(i), SignHint));
5363     return setRange(SMax, SignHint, ConservativeResult.intersectWith(X));
5364   }
5365 
5366   if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
5367     ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint);
5368     for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
5369       X = X.umax(getRangeRef(UMax->getOperand(i), SignHint));
5370     return setRange(UMax, SignHint, ConservativeResult.intersectWith(X));
5371   }
5372 
5373   if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
5374     ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint);
5375     ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint);
5376     return setRange(UDiv, SignHint,
5377                     ConservativeResult.intersectWith(X.udiv(Y)));
5378   }
5379 
5380   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
5381     ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint);
5382     return setRange(ZExt, SignHint,
5383                     ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
5384   }
5385 
5386   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
5387     ConstantRange X = getRangeRef(SExt->getOperand(), SignHint);
5388     return setRange(SExt, SignHint,
5389                     ConservativeResult.intersectWith(X.signExtend(BitWidth)));
5390   }
5391 
5392   if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
5393     ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint);
5394     return setRange(Trunc, SignHint,
5395                     ConservativeResult.intersectWith(X.truncate(BitWidth)));
5396   }
5397 
5398   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
5399     // If there's no unsigned wrap, the value will never be less than its
5400     // initial value.
5401     if (AddRec->hasNoUnsignedWrap())
5402       if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
5403         if (!C->getValue()->isZero())
5404           ConservativeResult = ConservativeResult.intersectWith(
5405               ConstantRange(C->getAPInt(), APInt(BitWidth, 0)));
5406 
5407     // If there's no signed wrap, and all the operands have the same sign or
5408     // zero, the value won't ever change sign.
5409     if (AddRec->hasNoSignedWrap()) {
5410       bool AllNonNeg = true;
5411       bool AllNonPos = true;
5412       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
5413         if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
5414         if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
5415       }
5416       if (AllNonNeg)
5417         ConservativeResult = ConservativeResult.intersectWith(
5418           ConstantRange(APInt(BitWidth, 0),
5419                         APInt::getSignedMinValue(BitWidth)));
5420       else if (AllNonPos)
5421         ConservativeResult = ConservativeResult.intersectWith(
5422           ConstantRange(APInt::getSignedMinValue(BitWidth),
5423                         APInt(BitWidth, 1)));
5424     }
5425 
5426     // TODO: non-affine addrec
5427     if (AddRec->isAffine()) {
5428       const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
5429       if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
5430           getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
5431         auto RangeFromAffine = getRangeForAffineAR(
5432             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
5433             BitWidth);
5434         if (!RangeFromAffine.isFullSet())
5435           ConservativeResult =
5436               ConservativeResult.intersectWith(RangeFromAffine);
5437 
5438         auto RangeFromFactoring = getRangeViaFactoring(
5439             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
5440             BitWidth);
5441         if (!RangeFromFactoring.isFullSet())
5442           ConservativeResult =
5443               ConservativeResult.intersectWith(RangeFromFactoring);
5444       }
5445     }
5446 
5447     return setRange(AddRec, SignHint, std::move(ConservativeResult));
5448   }
5449 
5450   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5451     // Check if the IR explicitly contains !range metadata.
5452     Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
5453     if (MDRange.hasValue())
5454       ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue());
5455 
5456     // Split here to avoid paying the compile-time cost of calling both
5457     // computeKnownBits and ComputeNumSignBits.  This restriction can be lifted
5458     // if needed.
5459     const DataLayout &DL = getDataLayout();
5460     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
5461       // For a SCEVUnknown, ask ValueTracking.
5462       KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
5463       if (Known.One != ~Known.Zero + 1)
5464         ConservativeResult =
5465             ConservativeResult.intersectWith(ConstantRange(Known.One,
5466                                                            ~Known.Zero + 1));
5467     } else {
5468       assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED &&
5469              "generalize as needed!");
5470       unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
5471       if (NS > 1)
5472         ConservativeResult = ConservativeResult.intersectWith(
5473             ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
5474                           APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1));
5475     }
5476 
5477     return setRange(U, SignHint, std::move(ConservativeResult));
5478   }
5479 
5480   return setRange(S, SignHint, std::move(ConservativeResult));
5481 }
5482 
5483 // Given a StartRange, Step and MaxBECount for an expression compute a range of
5484 // values that the expression can take. Initially, the expression has a value
5485 // from StartRange and then is changed by Step up to MaxBECount times. Signed
5486 // argument defines if we treat Step as signed or unsigned.
5487 static ConstantRange getRangeForAffineARHelper(APInt Step,
5488                                                const ConstantRange &StartRange,
5489                                                const APInt &MaxBECount,
5490                                                unsigned BitWidth, bool Signed) {
5491   // If either Step or MaxBECount is 0, then the expression won't change, and we
5492   // just need to return the initial range.
5493   if (Step == 0 || MaxBECount == 0)
5494     return StartRange;
5495 
5496   // If we don't know anything about the initial value (i.e. StartRange is
5497   // FullRange), then we don't know anything about the final range either.
5498   // Return FullRange.
5499   if (StartRange.isFullSet())
5500     return ConstantRange(BitWidth, /* isFullSet = */ true);
5501 
5502   // If Step is signed and negative, then we use its absolute value, but we also
5503   // note that we're moving in the opposite direction.
5504   bool Descending = Signed && Step.isNegative();
5505 
5506   if (Signed)
5507     // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
5508     // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
5509     // This equations hold true due to the well-defined wrap-around behavior of
5510     // APInt.
5511     Step = Step.abs();
5512 
5513   // Check if Offset is more than full span of BitWidth. If it is, the
5514   // expression is guaranteed to overflow.
5515   if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
5516     return ConstantRange(BitWidth, /* isFullSet = */ true);
5517 
5518   // Offset is by how much the expression can change. Checks above guarantee no
5519   // overflow here.
5520   APInt Offset = Step * MaxBECount;
5521 
5522   // Minimum value of the final range will match the minimal value of StartRange
5523   // if the expression is increasing and will be decreased by Offset otherwise.
5524   // Maximum value of the final range will match the maximal value of StartRange
5525   // if the expression is decreasing and will be increased by Offset otherwise.
5526   APInt StartLower = StartRange.getLower();
5527   APInt StartUpper = StartRange.getUpper() - 1;
5528   APInt MovedBoundary = Descending ? (StartLower - std::move(Offset))
5529                                    : (StartUpper + std::move(Offset));
5530 
5531   // It's possible that the new minimum/maximum value will fall into the initial
5532   // range (due to wrap around). This means that the expression can take any
5533   // value in this bitwidth, and we have to return full range.
5534   if (StartRange.contains(MovedBoundary))
5535     return ConstantRange(BitWidth, /* isFullSet = */ true);
5536 
5537   APInt NewLower =
5538       Descending ? std::move(MovedBoundary) : std::move(StartLower);
5539   APInt NewUpper =
5540       Descending ? std::move(StartUpper) : std::move(MovedBoundary);
5541   NewUpper += 1;
5542 
5543   // If we end up with full range, return a proper full range.
5544   if (NewLower == NewUpper)
5545     return ConstantRange(BitWidth, /* isFullSet = */ true);
5546 
5547   // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
5548   return ConstantRange(std::move(NewLower), std::move(NewUpper));
5549 }
5550 
5551 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
5552                                                    const SCEV *Step,
5553                                                    const SCEV *MaxBECount,
5554                                                    unsigned BitWidth) {
5555   assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&
5556          getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
5557          "Precondition!");
5558 
5559   MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType());
5560   APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount);
5561 
5562   // First, consider step signed.
5563   ConstantRange StartSRange = getSignedRange(Start);
5564   ConstantRange StepSRange = getSignedRange(Step);
5565 
5566   // If Step can be both positive and negative, we need to find ranges for the
5567   // maximum absolute step values in both directions and union them.
5568   ConstantRange SR =
5569       getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange,
5570                                 MaxBECountValue, BitWidth, /* Signed = */ true);
5571   SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(),
5572                                               StartSRange, MaxBECountValue,
5573                                               BitWidth, /* Signed = */ true));
5574 
5575   // Next, consider step unsigned.
5576   ConstantRange UR = getRangeForAffineARHelper(
5577       getUnsignedRangeMax(Step), getUnsignedRange(Start),
5578       MaxBECountValue, BitWidth, /* Signed = */ false);
5579 
5580   // Finally, intersect signed and unsigned ranges.
5581   return SR.intersectWith(UR);
5582 }
5583 
5584 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
5585                                                     const SCEV *Step,
5586                                                     const SCEV *MaxBECount,
5587                                                     unsigned BitWidth) {
5588   //    RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
5589   // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
5590 
5591   struct SelectPattern {
5592     Value *Condition = nullptr;
5593     APInt TrueValue;
5594     APInt FalseValue;
5595 
5596     explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
5597                            const SCEV *S) {
5598       Optional<unsigned> CastOp;
5599       APInt Offset(BitWidth, 0);
5600 
5601       assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&
5602              "Should be!");
5603 
5604       // Peel off a constant offset:
5605       if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
5606         // In the future we could consider being smarter here and handle
5607         // {Start+Step,+,Step} too.
5608         if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
5609           return;
5610 
5611         Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
5612         S = SA->getOperand(1);
5613       }
5614 
5615       // Peel off a cast operation
5616       if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) {
5617         CastOp = SCast->getSCEVType();
5618         S = SCast->getOperand();
5619       }
5620 
5621       using namespace llvm::PatternMatch;
5622 
5623       auto *SU = dyn_cast<SCEVUnknown>(S);
5624       const APInt *TrueVal, *FalseVal;
5625       if (!SU ||
5626           !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
5627                                           m_APInt(FalseVal)))) {
5628         Condition = nullptr;
5629         return;
5630       }
5631 
5632       TrueValue = *TrueVal;
5633       FalseValue = *FalseVal;
5634 
5635       // Re-apply the cast we peeled off earlier
5636       if (CastOp.hasValue())
5637         switch (*CastOp) {
5638         default:
5639           llvm_unreachable("Unknown SCEV cast type!");
5640 
5641         case scTruncate:
5642           TrueValue = TrueValue.trunc(BitWidth);
5643           FalseValue = FalseValue.trunc(BitWidth);
5644           break;
5645         case scZeroExtend:
5646           TrueValue = TrueValue.zext(BitWidth);
5647           FalseValue = FalseValue.zext(BitWidth);
5648           break;
5649         case scSignExtend:
5650           TrueValue = TrueValue.sext(BitWidth);
5651           FalseValue = FalseValue.sext(BitWidth);
5652           break;
5653         }
5654 
5655       // Re-apply the constant offset we peeled off earlier
5656       TrueValue += Offset;
5657       FalseValue += Offset;
5658     }
5659 
5660     bool isRecognized() { return Condition != nullptr; }
5661   };
5662 
5663   SelectPattern StartPattern(*this, BitWidth, Start);
5664   if (!StartPattern.isRecognized())
5665     return ConstantRange(BitWidth, /* isFullSet = */ true);
5666 
5667   SelectPattern StepPattern(*this, BitWidth, Step);
5668   if (!StepPattern.isRecognized())
5669     return ConstantRange(BitWidth, /* isFullSet = */ true);
5670 
5671   if (StartPattern.Condition != StepPattern.Condition) {
5672     // We don't handle this case today; but we could, by considering four
5673     // possibilities below instead of two. I'm not sure if there are cases where
5674     // that will help over what getRange already does, though.
5675     return ConstantRange(BitWidth, /* isFullSet = */ true);
5676   }
5677 
5678   // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
5679   // construct arbitrary general SCEV expressions here.  This function is called
5680   // from deep in the call stack, and calling getSCEV (on a sext instruction,
5681   // say) can end up caching a suboptimal value.
5682 
5683   // FIXME: without the explicit `this` receiver below, MSVC errors out with
5684   // C2352 and C2512 (otherwise it isn't needed).
5685 
5686   const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
5687   const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
5688   const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
5689   const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
5690 
5691   ConstantRange TrueRange =
5692       this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
5693   ConstantRange FalseRange =
5694       this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
5695 
5696   return TrueRange.unionWith(FalseRange);
5697 }
5698 
5699 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
5700   if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
5701   const BinaryOperator *BinOp = cast<BinaryOperator>(V);
5702 
5703   // Return early if there are no flags to propagate to the SCEV.
5704   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5705   if (BinOp->hasNoUnsignedWrap())
5706     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
5707   if (BinOp->hasNoSignedWrap())
5708     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
5709   if (Flags == SCEV::FlagAnyWrap)
5710     return SCEV::FlagAnyWrap;
5711 
5712   return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
5713 }
5714 
5715 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
5716   // Here we check that I is in the header of the innermost loop containing I,
5717   // since we only deal with instructions in the loop header. The actual loop we
5718   // need to check later will come from an add recurrence, but getting that
5719   // requires computing the SCEV of the operands, which can be expensive. This
5720   // check we can do cheaply to rule out some cases early.
5721   Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent());
5722   if (InnermostContainingLoop == nullptr ||
5723       InnermostContainingLoop->getHeader() != I->getParent())
5724     return false;
5725 
5726   // Only proceed if we can prove that I does not yield poison.
5727   if (!programUndefinedIfFullPoison(I))
5728     return false;
5729 
5730   // At this point we know that if I is executed, then it does not wrap
5731   // according to at least one of NSW or NUW. If I is not executed, then we do
5732   // not know if the calculation that I represents would wrap. Multiple
5733   // instructions can map to the same SCEV. If we apply NSW or NUW from I to
5734   // the SCEV, we must guarantee no wrapping for that SCEV also when it is
5735   // derived from other instructions that map to the same SCEV. We cannot make
5736   // that guarantee for cases where I is not executed. So we need to find the
5737   // loop that I is considered in relation to and prove that I is executed for
5738   // every iteration of that loop. That implies that the value that I
5739   // calculates does not wrap anywhere in the loop, so then we can apply the
5740   // flags to the SCEV.
5741   //
5742   // We check isLoopInvariant to disambiguate in case we are adding recurrences
5743   // from different loops, so that we know which loop to prove that I is
5744   // executed in.
5745   for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) {
5746     // I could be an extractvalue from a call to an overflow intrinsic.
5747     // TODO: We can do better here in some cases.
5748     if (!isSCEVable(I->getOperand(OpIndex)->getType()))
5749       return false;
5750     const SCEV *Op = getSCEV(I->getOperand(OpIndex));
5751     if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
5752       bool AllOtherOpsLoopInvariant = true;
5753       for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands();
5754            ++OtherOpIndex) {
5755         if (OtherOpIndex != OpIndex) {
5756           const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex));
5757           if (!isLoopInvariant(OtherOp, AddRec->getLoop())) {
5758             AllOtherOpsLoopInvariant = false;
5759             break;
5760           }
5761         }
5762       }
5763       if (AllOtherOpsLoopInvariant &&
5764           isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop()))
5765         return true;
5766     }
5767   }
5768   return false;
5769 }
5770 
5771 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
5772   // If we know that \c I can never be poison period, then that's enough.
5773   if (isSCEVExprNeverPoison(I))
5774     return true;
5775 
5776   // For an add recurrence specifically, we assume that infinite loops without
5777   // side effects are undefined behavior, and then reason as follows:
5778   //
5779   // If the add recurrence is poison in any iteration, it is poison on all
5780   // future iterations (since incrementing poison yields poison). If the result
5781   // of the add recurrence is fed into the loop latch condition and the loop
5782   // does not contain any throws or exiting blocks other than the latch, we now
5783   // have the ability to "choose" whether the backedge is taken or not (by
5784   // choosing a sufficiently evil value for the poison feeding into the branch)
5785   // for every iteration including and after the one in which \p I first became
5786   // poison.  There are two possibilities (let's call the iteration in which \p
5787   // I first became poison as K):
5788   //
5789   //  1. In the set of iterations including and after K, the loop body executes
5790   //     no side effects.  In this case executing the backege an infinte number
5791   //     of times will yield undefined behavior.
5792   //
5793   //  2. In the set of iterations including and after K, the loop body executes
5794   //     at least one side effect.  In this case, that specific instance of side
5795   //     effect is control dependent on poison, which also yields undefined
5796   //     behavior.
5797 
5798   auto *ExitingBB = L->getExitingBlock();
5799   auto *LatchBB = L->getLoopLatch();
5800   if (!ExitingBB || !LatchBB || ExitingBB != LatchBB)
5801     return false;
5802 
5803   SmallPtrSet<const Instruction *, 16> Pushed;
5804   SmallVector<const Instruction *, 8> PoisonStack;
5805 
5806   // We start by assuming \c I, the post-inc add recurrence, is poison.  Only
5807   // things that are known to be fully poison under that assumption go on the
5808   // PoisonStack.
5809   Pushed.insert(I);
5810   PoisonStack.push_back(I);
5811 
5812   bool LatchControlDependentOnPoison = false;
5813   while (!PoisonStack.empty() && !LatchControlDependentOnPoison) {
5814     const Instruction *Poison = PoisonStack.pop_back_val();
5815 
5816     for (auto *PoisonUser : Poison->users()) {
5817       if (propagatesFullPoison(cast<Instruction>(PoisonUser))) {
5818         if (Pushed.insert(cast<Instruction>(PoisonUser)).second)
5819           PoisonStack.push_back(cast<Instruction>(PoisonUser));
5820       } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) {
5821         assert(BI->isConditional() && "Only possibility!");
5822         if (BI->getParent() == LatchBB) {
5823           LatchControlDependentOnPoison = true;
5824           break;
5825         }
5826       }
5827     }
5828   }
5829 
5830   return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L);
5831 }
5832 
5833 ScalarEvolution::LoopProperties
5834 ScalarEvolution::getLoopProperties(const Loop *L) {
5835   using LoopProperties = ScalarEvolution::LoopProperties;
5836 
5837   auto Itr = LoopPropertiesCache.find(L);
5838   if (Itr == LoopPropertiesCache.end()) {
5839     auto HasSideEffects = [](Instruction *I) {
5840       if (auto *SI = dyn_cast<StoreInst>(I))
5841         return !SI->isSimple();
5842 
5843       return I->mayHaveSideEffects();
5844     };
5845 
5846     LoopProperties LP = {/* HasNoAbnormalExits */ true,
5847                          /*HasNoSideEffects*/ true};
5848 
5849     for (auto *BB : L->getBlocks())
5850       for (auto &I : *BB) {
5851         if (!isGuaranteedToTransferExecutionToSuccessor(&I))
5852           LP.HasNoAbnormalExits = false;
5853         if (HasSideEffects(&I))
5854           LP.HasNoSideEffects = false;
5855         if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
5856           break; // We're already as pessimistic as we can get.
5857       }
5858 
5859     auto InsertPair = LoopPropertiesCache.insert({L, LP});
5860     assert(InsertPair.second && "We just checked!");
5861     Itr = InsertPair.first;
5862   }
5863 
5864   return Itr->second;
5865 }
5866 
5867 const SCEV *ScalarEvolution::createSCEV(Value *V) {
5868   if (!isSCEVable(V->getType()))
5869     return getUnknown(V);
5870 
5871   if (Instruction *I = dyn_cast<Instruction>(V)) {
5872     // Don't attempt to analyze instructions in blocks that aren't
5873     // reachable. Such instructions don't matter, and they aren't required
5874     // to obey basic rules for definitions dominating uses which this
5875     // analysis depends on.
5876     if (!DT.isReachableFromEntry(I->getParent()))
5877       return getUnknown(V);
5878   } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
5879     return getConstant(CI);
5880   else if (isa<ConstantPointerNull>(V))
5881     return getZero(V->getType());
5882   else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
5883     return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee());
5884   else if (!isa<ConstantExpr>(V))
5885     return getUnknown(V);
5886 
5887   Operator *U = cast<Operator>(V);
5888   if (auto BO = MatchBinaryOp(U, DT)) {
5889     switch (BO->Opcode) {
5890     case Instruction::Add: {
5891       // The simple thing to do would be to just call getSCEV on both operands
5892       // and call getAddExpr with the result. However if we're looking at a
5893       // bunch of things all added together, this can be quite inefficient,
5894       // because it leads to N-1 getAddExpr calls for N ultimate operands.
5895       // Instead, gather up all the operands and make a single getAddExpr call.
5896       // LLVM IR canonical form means we need only traverse the left operands.
5897       SmallVector<const SCEV *, 4> AddOps;
5898       do {
5899         if (BO->Op) {
5900           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
5901             AddOps.push_back(OpSCEV);
5902             break;
5903           }
5904 
5905           // If a NUW or NSW flag can be applied to the SCEV for this
5906           // addition, then compute the SCEV for this addition by itself
5907           // with a separate call to getAddExpr. We need to do that
5908           // instead of pushing the operands of the addition onto AddOps,
5909           // since the flags are only known to apply to this particular
5910           // addition - they may not apply to other additions that can be
5911           // formed with operands from AddOps.
5912           const SCEV *RHS = getSCEV(BO->RHS);
5913           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
5914           if (Flags != SCEV::FlagAnyWrap) {
5915             const SCEV *LHS = getSCEV(BO->LHS);
5916             if (BO->Opcode == Instruction::Sub)
5917               AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
5918             else
5919               AddOps.push_back(getAddExpr(LHS, RHS, Flags));
5920             break;
5921           }
5922         }
5923 
5924         if (BO->Opcode == Instruction::Sub)
5925           AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
5926         else
5927           AddOps.push_back(getSCEV(BO->RHS));
5928 
5929         auto NewBO = MatchBinaryOp(BO->LHS, DT);
5930         if (!NewBO || (NewBO->Opcode != Instruction::Add &&
5931                        NewBO->Opcode != Instruction::Sub)) {
5932           AddOps.push_back(getSCEV(BO->LHS));
5933           break;
5934         }
5935         BO = NewBO;
5936       } while (true);
5937 
5938       return getAddExpr(AddOps);
5939     }
5940 
5941     case Instruction::Mul: {
5942       SmallVector<const SCEV *, 4> MulOps;
5943       do {
5944         if (BO->Op) {
5945           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
5946             MulOps.push_back(OpSCEV);
5947             break;
5948           }
5949 
5950           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
5951           if (Flags != SCEV::FlagAnyWrap) {
5952             MulOps.push_back(
5953                 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags));
5954             break;
5955           }
5956         }
5957 
5958         MulOps.push_back(getSCEV(BO->RHS));
5959         auto NewBO = MatchBinaryOp(BO->LHS, DT);
5960         if (!NewBO || NewBO->Opcode != Instruction::Mul) {
5961           MulOps.push_back(getSCEV(BO->LHS));
5962           break;
5963         }
5964         BO = NewBO;
5965       } while (true);
5966 
5967       return getMulExpr(MulOps);
5968     }
5969     case Instruction::UDiv:
5970       return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
5971     case Instruction::URem:
5972       return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
5973     case Instruction::Sub: {
5974       SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5975       if (BO->Op)
5976         Flags = getNoWrapFlagsFromUB(BO->Op);
5977       return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags);
5978     }
5979     case Instruction::And:
5980       // For an expression like x&255 that merely masks off the high bits,
5981       // use zext(trunc(x)) as the SCEV expression.
5982       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5983         if (CI->isZero())
5984           return getSCEV(BO->RHS);
5985         if (CI->isMinusOne())
5986           return getSCEV(BO->LHS);
5987         const APInt &A = CI->getValue();
5988 
5989         // Instcombine's ShrinkDemandedConstant may strip bits out of
5990         // constants, obscuring what would otherwise be a low-bits mask.
5991         // Use computeKnownBits to compute what ShrinkDemandedConstant
5992         // knew about to reconstruct a low-bits mask value.
5993         unsigned LZ = A.countLeadingZeros();
5994         unsigned TZ = A.countTrailingZeros();
5995         unsigned BitWidth = A.getBitWidth();
5996         KnownBits Known(BitWidth);
5997         computeKnownBits(BO->LHS, Known, getDataLayout(),
5998                          0, &AC, nullptr, &DT);
5999 
6000         APInt EffectiveMask =
6001             APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
6002         if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
6003           const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
6004           const SCEV *LHS = getSCEV(BO->LHS);
6005           const SCEV *ShiftedLHS = nullptr;
6006           if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
6007             if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
6008               // For an expression like (x * 8) & 8, simplify the multiply.
6009               unsigned MulZeros = OpC->getAPInt().countTrailingZeros();
6010               unsigned GCD = std::min(MulZeros, TZ);
6011               APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
6012               SmallVector<const SCEV*, 4> MulOps;
6013               MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD)));
6014               MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end());
6015               auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
6016               ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
6017             }
6018           }
6019           if (!ShiftedLHS)
6020             ShiftedLHS = getUDivExpr(LHS, MulCount);
6021           return getMulExpr(
6022               getZeroExtendExpr(
6023                   getTruncateExpr(ShiftedLHS,
6024                       IntegerType::get(getContext(), BitWidth - LZ - TZ)),
6025                   BO->LHS->getType()),
6026               MulCount);
6027         }
6028       }
6029       break;
6030 
6031     case Instruction::Or:
6032       // If the RHS of the Or is a constant, we may have something like:
6033       // X*4+1 which got turned into X*4|1.  Handle this as an Add so loop
6034       // optimizations will transparently handle this case.
6035       //
6036       // In order for this transformation to be safe, the LHS must be of the
6037       // form X*(2^n) and the Or constant must be less than 2^n.
6038       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6039         const SCEV *LHS = getSCEV(BO->LHS);
6040         const APInt &CIVal = CI->getValue();
6041         if (GetMinTrailingZeros(LHS) >=
6042             (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
6043           // Build a plain add SCEV.
6044           const SCEV *S = getAddExpr(LHS, getSCEV(CI));
6045           // If the LHS of the add was an addrec and it has no-wrap flags,
6046           // transfer the no-wrap flags, since an or won't introduce a wrap.
6047           if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
6048             const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
6049             const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags(
6050                 OldAR->getNoWrapFlags());
6051           }
6052           return S;
6053         }
6054       }
6055       break;
6056 
6057     case Instruction::Xor:
6058       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6059         // If the RHS of xor is -1, then this is a not operation.
6060         if (CI->isMinusOne())
6061           return getNotSCEV(getSCEV(BO->LHS));
6062 
6063         // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
6064         // This is a variant of the check for xor with -1, and it handles
6065         // the case where instcombine has trimmed non-demanded bits out
6066         // of an xor with -1.
6067         if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
6068           if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
6069             if (LBO->getOpcode() == Instruction::And &&
6070                 LCI->getValue() == CI->getValue())
6071               if (const SCEVZeroExtendExpr *Z =
6072                       dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
6073                 Type *UTy = BO->LHS->getType();
6074                 const SCEV *Z0 = Z->getOperand();
6075                 Type *Z0Ty = Z0->getType();
6076                 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
6077 
6078                 // If C is a low-bits mask, the zero extend is serving to
6079                 // mask off the high bits. Complement the operand and
6080                 // re-apply the zext.
6081                 if (CI->getValue().isMask(Z0TySize))
6082                   return getZeroExtendExpr(getNotSCEV(Z0), UTy);
6083 
6084                 // If C is a single bit, it may be in the sign-bit position
6085                 // before the zero-extend. In this case, represent the xor
6086                 // using an add, which is equivalent, and re-apply the zext.
6087                 APInt Trunc = CI->getValue().trunc(Z0TySize);
6088                 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
6089                     Trunc.isSignMask())
6090                   return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
6091                                            UTy);
6092               }
6093       }
6094       break;
6095 
6096   case Instruction::Shl:
6097     // Turn shift left of a constant amount into a multiply.
6098     if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
6099       uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
6100 
6101       // If the shift count is not less than the bitwidth, the result of
6102       // the shift is undefined. Don't try to analyze it, because the
6103       // resolution chosen here may differ from the resolution chosen in
6104       // other parts of the compiler.
6105       if (SA->getValue().uge(BitWidth))
6106         break;
6107 
6108       // It is currently not resolved how to interpret NSW for left
6109       // shift by BitWidth - 1, so we avoid applying flags in that
6110       // case. Remove this check (or this comment) once the situation
6111       // is resolved. See
6112       // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html
6113       // and http://reviews.llvm.org/D8890 .
6114       auto Flags = SCEV::FlagAnyWrap;
6115       if (BO->Op && SA->getValue().ult(BitWidth - 1))
6116         Flags = getNoWrapFlagsFromUB(BO->Op);
6117 
6118       Constant *X = ConstantInt::get(getContext(),
6119         APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
6120       return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags);
6121     }
6122     break;
6123 
6124     case Instruction::AShr: {
6125       // AShr X, C, where C is a constant.
6126       ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
6127       if (!CI)
6128         break;
6129 
6130       Type *OuterTy = BO->LHS->getType();
6131       uint64_t BitWidth = getTypeSizeInBits(OuterTy);
6132       // If the shift count is not less than the bitwidth, the result of
6133       // the shift is undefined. Don't try to analyze it, because the
6134       // resolution chosen here may differ from the resolution chosen in
6135       // other parts of the compiler.
6136       if (CI->getValue().uge(BitWidth))
6137         break;
6138 
6139       if (CI->isZero())
6140         return getSCEV(BO->LHS); // shift by zero --> noop
6141 
6142       uint64_t AShrAmt = CI->getZExtValue();
6143       Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
6144 
6145       Operator *L = dyn_cast<Operator>(BO->LHS);
6146       if (L && L->getOpcode() == Instruction::Shl) {
6147         // X = Shl A, n
6148         // Y = AShr X, m
6149         // Both n and m are constant.
6150 
6151         const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
6152         if (L->getOperand(1) == BO->RHS)
6153           // For a two-shift sext-inreg, i.e. n = m,
6154           // use sext(trunc(x)) as the SCEV expression.
6155           return getSignExtendExpr(
6156               getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy);
6157 
6158         ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
6159         if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) {
6160           uint64_t ShlAmt = ShlAmtCI->getZExtValue();
6161           if (ShlAmt > AShrAmt) {
6162             // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
6163             // expression. We already checked that ShlAmt < BitWidth, so
6164             // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
6165             // ShlAmt - AShrAmt < Amt.
6166             APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
6167                                             ShlAmt - AShrAmt);
6168             return getSignExtendExpr(
6169                 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy),
6170                 getConstant(Mul)), OuterTy);
6171           }
6172         }
6173       }
6174       break;
6175     }
6176     }
6177   }
6178 
6179   switch (U->getOpcode()) {
6180   case Instruction::Trunc:
6181     return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
6182 
6183   case Instruction::ZExt:
6184     return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
6185 
6186   case Instruction::SExt:
6187     if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) {
6188       // The NSW flag of a subtract does not always survive the conversion to
6189       // A + (-1)*B.  By pushing sign extension onto its operands we are much
6190       // more likely to preserve NSW and allow later AddRec optimisations.
6191       //
6192       // NOTE: This is effectively duplicating this logic from getSignExtend:
6193       //   sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
6194       // but by that point the NSW information has potentially been lost.
6195       if (BO->Opcode == Instruction::Sub && BO->IsNSW) {
6196         Type *Ty = U->getType();
6197         auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty);
6198         auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty);
6199         return getMinusSCEV(V1, V2, SCEV::FlagNSW);
6200       }
6201     }
6202     return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
6203 
6204   case Instruction::BitCast:
6205     // BitCasts are no-op casts so we just eliminate the cast.
6206     if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
6207       return getSCEV(U->getOperand(0));
6208     break;
6209 
6210   // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
6211   // lead to pointer expressions which cannot safely be expanded to GEPs,
6212   // because ScalarEvolution doesn't respect the GEP aliasing rules when
6213   // simplifying integer expressions.
6214 
6215   case Instruction::GetElementPtr:
6216     return createNodeForGEP(cast<GEPOperator>(U));
6217 
6218   case Instruction::PHI:
6219     return createNodeForPHI(cast<PHINode>(U));
6220 
6221   case Instruction::Select:
6222     // U can also be a select constant expr, which let fall through.  Since
6223     // createNodeForSelect only works for a condition that is an `ICmpInst`, and
6224     // constant expressions cannot have instructions as operands, we'd have
6225     // returned getUnknown for a select constant expressions anyway.
6226     if (isa<Instruction>(U))
6227       return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0),
6228                                       U->getOperand(1), U->getOperand(2));
6229     break;
6230 
6231   case Instruction::Call:
6232   case Instruction::Invoke:
6233     if (Value *RV = CallSite(U).getReturnedArgOperand())
6234       return getSCEV(RV);
6235     break;
6236   }
6237 
6238   return getUnknown(V);
6239 }
6240 
6241 //===----------------------------------------------------------------------===//
6242 //                   Iteration Count Computation Code
6243 //
6244 
6245 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
6246   if (!ExitCount)
6247     return 0;
6248 
6249   ConstantInt *ExitConst = ExitCount->getValue();
6250 
6251   // Guard against huge trip counts.
6252   if (ExitConst->getValue().getActiveBits() > 32)
6253     return 0;
6254 
6255   // In case of integer overflow, this returns 0, which is correct.
6256   return ((unsigned)ExitConst->getZExtValue()) + 1;
6257 }
6258 
6259 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) {
6260   if (BasicBlock *ExitingBB = L->getExitingBlock())
6261     return getSmallConstantTripCount(L, ExitingBB);
6262 
6263   // No trip count information for multiple exits.
6264   return 0;
6265 }
6266 
6267 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L,
6268                                                     BasicBlock *ExitingBlock) {
6269   assert(ExitingBlock && "Must pass a non-null exiting block!");
6270   assert(L->isLoopExiting(ExitingBlock) &&
6271          "Exiting block must actually branch out of the loop!");
6272   const SCEVConstant *ExitCount =
6273       dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
6274   return getConstantTripCount(ExitCount);
6275 }
6276 
6277 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) {
6278   const auto *MaxExitCount =
6279       dyn_cast<SCEVConstant>(getMaxBackedgeTakenCount(L));
6280   return getConstantTripCount(MaxExitCount);
6281 }
6282 
6283 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) {
6284   if (BasicBlock *ExitingBB = L->getExitingBlock())
6285     return getSmallConstantTripMultiple(L, ExitingBB);
6286 
6287   // No trip multiple information for multiple exits.
6288   return 0;
6289 }
6290 
6291 /// Returns the largest constant divisor of the trip count of this loop as a
6292 /// normal unsigned value, if possible. This means that the actual trip count is
6293 /// always a multiple of the returned value (don't forget the trip count could
6294 /// very well be zero as well!).
6295 ///
6296 /// Returns 1 if the trip count is unknown or not guaranteed to be the
6297 /// multiple of a constant (which is also the case if the trip count is simply
6298 /// constant, use getSmallConstantTripCount for that case), Will also return 1
6299 /// if the trip count is very large (>= 2^32).
6300 ///
6301 /// As explained in the comments for getSmallConstantTripCount, this assumes
6302 /// that control exits the loop via ExitingBlock.
6303 unsigned
6304 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
6305                                               BasicBlock *ExitingBlock) {
6306   assert(ExitingBlock && "Must pass a non-null exiting block!");
6307   assert(L->isLoopExiting(ExitingBlock) &&
6308          "Exiting block must actually branch out of the loop!");
6309   const SCEV *ExitCount = getExitCount(L, ExitingBlock);
6310   if (ExitCount == getCouldNotCompute())
6311     return 1;
6312 
6313   // Get the trip count from the BE count by adding 1.
6314   const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType()));
6315 
6316   const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr);
6317   if (!TC)
6318     // Attempt to factor more general cases. Returns the greatest power of
6319     // two divisor. If overflow happens, the trip count expression is still
6320     // divisible by the greatest power of 2 divisor returned.
6321     return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr));
6322 
6323   ConstantInt *Result = TC->getValue();
6324 
6325   // Guard against huge trip counts (this requires checking
6326   // for zero to handle the case where the trip count == -1 and the
6327   // addition wraps).
6328   if (!Result || Result->getValue().getActiveBits() > 32 ||
6329       Result->getValue().getActiveBits() == 0)
6330     return 1;
6331 
6332   return (unsigned)Result->getZExtValue();
6333 }
6334 
6335 /// Get the expression for the number of loop iterations for which this loop is
6336 /// guaranteed not to exit via ExitingBlock. Otherwise return
6337 /// SCEVCouldNotCompute.
6338 const SCEV *ScalarEvolution::getExitCount(const Loop *L,
6339                                           BasicBlock *ExitingBlock) {
6340   return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
6341 }
6342 
6343 const SCEV *
6344 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
6345                                                  SCEVUnionPredicate &Preds) {
6346   return getPredicatedBackedgeTakenInfo(L).getExact(this, &Preds);
6347 }
6348 
6349 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
6350   return getBackedgeTakenInfo(L).getExact(this);
6351 }
6352 
6353 /// Similar to getBackedgeTakenCount, except return the least SCEV value that is
6354 /// known never to be less than the actual backedge taken count.
6355 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
6356   return getBackedgeTakenInfo(L).getMax(this);
6357 }
6358 
6359 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) {
6360   return getBackedgeTakenInfo(L).isMaxOrZero(this);
6361 }
6362 
6363 /// Push PHI nodes in the header of the given loop onto the given Worklist.
6364 static void
6365 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
6366   BasicBlock *Header = L->getHeader();
6367 
6368   // Push all Loop-header PHIs onto the Worklist stack.
6369   for (BasicBlock::iterator I = Header->begin();
6370        PHINode *PN = dyn_cast<PHINode>(I); ++I)
6371     Worklist.push_back(PN);
6372 }
6373 
6374 const ScalarEvolution::BackedgeTakenInfo &
6375 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
6376   auto &BTI = getBackedgeTakenInfo(L);
6377   if (BTI.hasFullInfo())
6378     return BTI;
6379 
6380   auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
6381 
6382   if (!Pair.second)
6383     return Pair.first->second;
6384 
6385   BackedgeTakenInfo Result =
6386       computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
6387 
6388   return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
6389 }
6390 
6391 const ScalarEvolution::BackedgeTakenInfo &
6392 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
6393   // Initially insert an invalid entry for this loop. If the insertion
6394   // succeeds, proceed to actually compute a backedge-taken count and
6395   // update the value. The temporary CouldNotCompute value tells SCEV
6396   // code elsewhere that it shouldn't attempt to request a new
6397   // backedge-taken count, which could result in infinite recursion.
6398   std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
6399       BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
6400   if (!Pair.second)
6401     return Pair.first->second;
6402 
6403   // computeBackedgeTakenCount may allocate memory for its result. Inserting it
6404   // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
6405   // must be cleared in this scope.
6406   BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
6407 
6408   if (Result.getExact(this) != getCouldNotCompute()) {
6409     assert(isLoopInvariant(Result.getExact(this), L) &&
6410            isLoopInvariant(Result.getMax(this), L) &&
6411            "Computed backedge-taken count isn't loop invariant for loop!");
6412     ++NumTripCountsComputed;
6413   }
6414   else if (Result.getMax(this) == getCouldNotCompute() &&
6415            isa<PHINode>(L->getHeader()->begin())) {
6416     // Only count loops that have phi nodes as not being computable.
6417     ++NumTripCountsNotComputed;
6418   }
6419 
6420   // Now that we know more about the trip count for this loop, forget any
6421   // existing SCEV values for PHI nodes in this loop since they are only
6422   // conservative estimates made without the benefit of trip count
6423   // information. This is similar to the code in forgetLoop, except that
6424   // it handles SCEVUnknown PHI nodes specially.
6425   if (Result.hasAnyInfo()) {
6426     SmallVector<Instruction *, 16> Worklist;
6427     PushLoopPHIs(L, Worklist);
6428 
6429     SmallPtrSet<Instruction *, 8> Discovered;
6430     while (!Worklist.empty()) {
6431       Instruction *I = Worklist.pop_back_val();
6432 
6433       ValueExprMapType::iterator It =
6434         ValueExprMap.find_as(static_cast<Value *>(I));
6435       if (It != ValueExprMap.end()) {
6436         const SCEV *Old = It->second;
6437 
6438         // SCEVUnknown for a PHI either means that it has an unrecognized
6439         // structure, or it's a PHI that's in the progress of being computed
6440         // by createNodeForPHI.  In the former case, additional loop trip
6441         // count information isn't going to change anything. In the later
6442         // case, createNodeForPHI will perform the necessary updates on its
6443         // own when it gets to that point.
6444         if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
6445           eraseValueFromMap(It->first);
6446           forgetMemoizedResults(Old);
6447         }
6448         if (PHINode *PN = dyn_cast<PHINode>(I))
6449           ConstantEvolutionLoopExitValue.erase(PN);
6450       }
6451 
6452       // Since we don't need to invalidate anything for correctness and we're
6453       // only invalidating to make SCEV's results more precise, we get to stop
6454       // early to avoid invalidating too much.  This is especially important in
6455       // cases like:
6456       //
6457       //   %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node
6458       // loop0:
6459       //   %pn0 = phi
6460       //   ...
6461       // loop1:
6462       //   %pn1 = phi
6463       //   ...
6464       //
6465       // where both loop0 and loop1's backedge taken count uses the SCEV
6466       // expression for %v.  If we don't have the early stop below then in cases
6467       // like the above, getBackedgeTakenInfo(loop1) will clear out the trip
6468       // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip
6469       // count for loop1, effectively nullifying SCEV's trip count cache.
6470       for (auto *U : I->users())
6471         if (auto *I = dyn_cast<Instruction>(U)) {
6472           auto *LoopForUser = LI.getLoopFor(I->getParent());
6473           if (LoopForUser && L->contains(LoopForUser) &&
6474               Discovered.insert(I).second)
6475             Worklist.push_back(I);
6476         }
6477     }
6478   }
6479 
6480   // Re-lookup the insert position, since the call to
6481   // computeBackedgeTakenCount above could result in a
6482   // recusive call to getBackedgeTakenInfo (on a different
6483   // loop), which would invalidate the iterator computed
6484   // earlier.
6485   return BackedgeTakenCounts.find(L)->second = std::move(Result);
6486 }
6487 
6488 void ScalarEvolution::forgetLoop(const Loop *L) {
6489   // Drop any stored trip count value.
6490   auto RemoveLoopFromBackedgeMap =
6491       [](DenseMap<const Loop *, BackedgeTakenInfo> &Map, const Loop *L) {
6492         auto BTCPos = Map.find(L);
6493         if (BTCPos != Map.end()) {
6494           BTCPos->second.clear();
6495           Map.erase(BTCPos);
6496         }
6497       };
6498 
6499   SmallVector<const Loop *, 16> LoopWorklist(1, L);
6500   SmallVector<Instruction *, 32> Worklist;
6501   SmallPtrSet<Instruction *, 16> Visited;
6502 
6503   // Iterate over all the loops and sub-loops to drop SCEV information.
6504   while (!LoopWorklist.empty()) {
6505     auto *CurrL = LoopWorklist.pop_back_val();
6506 
6507     RemoveLoopFromBackedgeMap(BackedgeTakenCounts, CurrL);
6508     RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts, CurrL);
6509 
6510     // Drop information about predicated SCEV rewrites for this loop.
6511     for (auto I = PredicatedSCEVRewrites.begin();
6512          I != PredicatedSCEVRewrites.end();) {
6513       std::pair<const SCEV *, const Loop *> Entry = I->first;
6514       if (Entry.second == CurrL)
6515         PredicatedSCEVRewrites.erase(I++);
6516       else
6517         ++I;
6518     }
6519 
6520     auto LoopUsersItr = LoopUsers.find(CurrL);
6521     if (LoopUsersItr != LoopUsers.end()) {
6522       for (auto *S : LoopUsersItr->second)
6523         forgetMemoizedResults(S);
6524       LoopUsers.erase(LoopUsersItr);
6525     }
6526 
6527     // Drop information about expressions based on loop-header PHIs.
6528     PushLoopPHIs(CurrL, Worklist);
6529 
6530     while (!Worklist.empty()) {
6531       Instruction *I = Worklist.pop_back_val();
6532       if (!Visited.insert(I).second)
6533         continue;
6534 
6535       ValueExprMapType::iterator It =
6536           ValueExprMap.find_as(static_cast<Value *>(I));
6537       if (It != ValueExprMap.end()) {
6538         eraseValueFromMap(It->first);
6539         forgetMemoizedResults(It->second);
6540         if (PHINode *PN = dyn_cast<PHINode>(I))
6541           ConstantEvolutionLoopExitValue.erase(PN);
6542       }
6543 
6544       PushDefUseChildren(I, Worklist);
6545     }
6546 
6547     LoopPropertiesCache.erase(CurrL);
6548     // Forget all contained loops too, to avoid dangling entries in the
6549     // ValuesAtScopes map.
6550     LoopWorklist.append(CurrL->begin(), CurrL->end());
6551   }
6552 }
6553 
6554 void ScalarEvolution::forgetValue(Value *V) {
6555   Instruction *I = dyn_cast<Instruction>(V);
6556   if (!I) return;
6557 
6558   // Drop information about expressions based on loop-header PHIs.
6559   SmallVector<Instruction *, 16> Worklist;
6560   Worklist.push_back(I);
6561 
6562   SmallPtrSet<Instruction *, 8> Visited;
6563   while (!Worklist.empty()) {
6564     I = Worklist.pop_back_val();
6565     if (!Visited.insert(I).second)
6566       continue;
6567 
6568     ValueExprMapType::iterator It =
6569       ValueExprMap.find_as(static_cast<Value *>(I));
6570     if (It != ValueExprMap.end()) {
6571       eraseValueFromMap(It->first);
6572       forgetMemoizedResults(It->second);
6573       if (PHINode *PN = dyn_cast<PHINode>(I))
6574         ConstantEvolutionLoopExitValue.erase(PN);
6575     }
6576 
6577     PushDefUseChildren(I, Worklist);
6578   }
6579 }
6580 
6581 /// Get the exact loop backedge taken count considering all loop exits. A
6582 /// computable result can only be returned for loops with a single exit.
6583 /// Returning the minimum taken count among all exits is incorrect because one
6584 /// of the loop's exit limit's may have been skipped. howFarToZero assumes that
6585 /// the limit of each loop test is never skipped. This is a valid assumption as
6586 /// long as the loop exits via that test. For precise results, it is the
6587 /// caller's responsibility to specify the relevant loop exit using
6588 /// getExact(ExitingBlock, SE).
6589 const SCEV *
6590 ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE,
6591                                              SCEVUnionPredicate *Preds) const {
6592   // If any exits were not computable, the loop is not computable.
6593   if (!isComplete() || ExitNotTaken.empty())
6594     return SE->getCouldNotCompute();
6595 
6596   const SCEV *BECount = nullptr;
6597   for (auto &ENT : ExitNotTaken) {
6598     assert(ENT.ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV");
6599 
6600     if (!BECount)
6601       BECount = ENT.ExactNotTaken;
6602     else if (BECount != ENT.ExactNotTaken)
6603       return SE->getCouldNotCompute();
6604     if (Preds && !ENT.hasAlwaysTruePredicate())
6605       Preds->add(ENT.Predicate.get());
6606 
6607     assert((Preds || ENT.hasAlwaysTruePredicate()) &&
6608            "Predicate should be always true!");
6609   }
6610 
6611   assert(BECount && "Invalid not taken count for loop exit");
6612   return BECount;
6613 }
6614 
6615 /// Get the exact not taken count for this loop exit.
6616 const SCEV *
6617 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock,
6618                                              ScalarEvolution *SE) const {
6619   for (auto &ENT : ExitNotTaken)
6620     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
6621       return ENT.ExactNotTaken;
6622 
6623   return SE->getCouldNotCompute();
6624 }
6625 
6626 /// getMax - Get the max backedge taken count for the loop.
6627 const SCEV *
6628 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const {
6629   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
6630     return !ENT.hasAlwaysTruePredicate();
6631   };
6632 
6633   if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax())
6634     return SE->getCouldNotCompute();
6635 
6636   assert((isa<SCEVCouldNotCompute>(getMax()) || isa<SCEVConstant>(getMax())) &&
6637          "No point in having a non-constant max backedge taken count!");
6638   return getMax();
6639 }
6640 
6641 bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const {
6642   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
6643     return !ENT.hasAlwaysTruePredicate();
6644   };
6645   return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
6646 }
6647 
6648 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S,
6649                                                     ScalarEvolution *SE) const {
6650   if (getMax() && getMax() != SE->getCouldNotCompute() &&
6651       SE->hasOperand(getMax(), S))
6652     return true;
6653 
6654   for (auto &ENT : ExitNotTaken)
6655     if (ENT.ExactNotTaken != SE->getCouldNotCompute() &&
6656         SE->hasOperand(ENT.ExactNotTaken, S))
6657       return true;
6658 
6659   return false;
6660 }
6661 
6662 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E)
6663     : ExactNotTaken(E), MaxNotTaken(E) {
6664   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6665           isa<SCEVConstant>(MaxNotTaken)) &&
6666          "No point in having a non-constant max backedge taken count!");
6667 }
6668 
6669 ScalarEvolution::ExitLimit::ExitLimit(
6670     const SCEV *E, const SCEV *M, bool MaxOrZero,
6671     ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList)
6672     : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) {
6673   assert((isa<SCEVCouldNotCompute>(ExactNotTaken) ||
6674           !isa<SCEVCouldNotCompute>(MaxNotTaken)) &&
6675          "Exact is not allowed to be less precise than Max");
6676   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6677           isa<SCEVConstant>(MaxNotTaken)) &&
6678          "No point in having a non-constant max backedge taken count!");
6679   for (auto *PredSet : PredSetList)
6680     for (auto *P : *PredSet)
6681       addPredicate(P);
6682 }
6683 
6684 ScalarEvolution::ExitLimit::ExitLimit(
6685     const SCEV *E, const SCEV *M, bool MaxOrZero,
6686     const SmallPtrSetImpl<const SCEVPredicate *> &PredSet)
6687     : ExitLimit(E, M, MaxOrZero, {&PredSet}) {
6688   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6689           isa<SCEVConstant>(MaxNotTaken)) &&
6690          "No point in having a non-constant max backedge taken count!");
6691 }
6692 
6693 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M,
6694                                       bool MaxOrZero)
6695     : ExitLimit(E, M, MaxOrZero, None) {
6696   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6697           isa<SCEVConstant>(MaxNotTaken)) &&
6698          "No point in having a non-constant max backedge taken count!");
6699 }
6700 
6701 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
6702 /// computable exit into a persistent ExitNotTakenInfo array.
6703 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
6704     SmallVectorImpl<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo>
6705         &&ExitCounts,
6706     bool Complete, const SCEV *MaxCount, bool MaxOrZero)
6707     : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) {
6708   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
6709 
6710   ExitNotTaken.reserve(ExitCounts.size());
6711   std::transform(
6712       ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken),
6713       [&](const EdgeExitInfo &EEI) {
6714         BasicBlock *ExitBB = EEI.first;
6715         const ExitLimit &EL = EEI.second;
6716         if (EL.Predicates.empty())
6717           return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr);
6718 
6719         std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate);
6720         for (auto *Pred : EL.Predicates)
6721           Predicate->add(Pred);
6722 
6723         return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, std::move(Predicate));
6724       });
6725   assert((isa<SCEVCouldNotCompute>(MaxCount) || isa<SCEVConstant>(MaxCount)) &&
6726          "No point in having a non-constant max backedge taken count!");
6727 }
6728 
6729 /// Invalidate this result and free the ExitNotTakenInfo array.
6730 void ScalarEvolution::BackedgeTakenInfo::clear() {
6731   ExitNotTaken.clear();
6732 }
6733 
6734 /// Compute the number of times the backedge of the specified loop will execute.
6735 ScalarEvolution::BackedgeTakenInfo
6736 ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
6737                                            bool AllowPredicates) {
6738   SmallVector<BasicBlock *, 8> ExitingBlocks;
6739   L->getExitingBlocks(ExitingBlocks);
6740 
6741   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
6742 
6743   SmallVector<EdgeExitInfo, 4> ExitCounts;
6744   bool CouldComputeBECount = true;
6745   BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
6746   const SCEV *MustExitMaxBECount = nullptr;
6747   const SCEV *MayExitMaxBECount = nullptr;
6748   bool MustExitMaxOrZero = false;
6749 
6750   // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
6751   // and compute maxBECount.
6752   // Do a union of all the predicates here.
6753   for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
6754     BasicBlock *ExitBB = ExitingBlocks[i];
6755     ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
6756 
6757     assert((AllowPredicates || EL.Predicates.empty()) &&
6758            "Predicated exit limit when predicates are not allowed!");
6759 
6760     // 1. For each exit that can be computed, add an entry to ExitCounts.
6761     // CouldComputeBECount is true only if all exits can be computed.
6762     if (EL.ExactNotTaken == getCouldNotCompute())
6763       // We couldn't compute an exact value for this exit, so
6764       // we won't be able to compute an exact value for the loop.
6765       CouldComputeBECount = false;
6766     else
6767       ExitCounts.emplace_back(ExitBB, EL);
6768 
6769     // 2. Derive the loop's MaxBECount from each exit's max number of
6770     // non-exiting iterations. Partition the loop exits into two kinds:
6771     // LoopMustExits and LoopMayExits.
6772     //
6773     // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
6774     // is a LoopMayExit.  If any computable LoopMustExit is found, then
6775     // MaxBECount is the minimum EL.MaxNotTaken of computable
6776     // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
6777     // EL.MaxNotTaken, where CouldNotCompute is considered greater than any
6778     // computable EL.MaxNotTaken.
6779     if (EL.MaxNotTaken != getCouldNotCompute() && Latch &&
6780         DT.dominates(ExitBB, Latch)) {
6781       if (!MustExitMaxBECount) {
6782         MustExitMaxBECount = EL.MaxNotTaken;
6783         MustExitMaxOrZero = EL.MaxOrZero;
6784       } else {
6785         MustExitMaxBECount =
6786             getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken);
6787       }
6788     } else if (MayExitMaxBECount != getCouldNotCompute()) {
6789       if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute())
6790         MayExitMaxBECount = EL.MaxNotTaken;
6791       else {
6792         MayExitMaxBECount =
6793             getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken);
6794       }
6795     }
6796   }
6797   const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
6798     (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
6799   // The loop backedge will be taken the maximum or zero times if there's
6800   // a single exit that must be taken the maximum or zero times.
6801   bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
6802   return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
6803                            MaxBECount, MaxOrZero);
6804 }
6805 
6806 ScalarEvolution::ExitLimit
6807 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
6808                                       bool AllowPredicates) {
6809   // Okay, we've chosen an exiting block.  See what condition causes us to exit
6810   // at this block and remember the exit block and whether all other targets
6811   // lead to the loop header.
6812   bool MustExecuteLoopHeader = true;
6813   BasicBlock *Exit = nullptr;
6814   for (auto *SBB : successors(ExitingBlock))
6815     if (!L->contains(SBB)) {
6816       if (Exit) // Multiple exit successors.
6817         return getCouldNotCompute();
6818       Exit = SBB;
6819     } else if (SBB != L->getHeader()) {
6820       MustExecuteLoopHeader = false;
6821     }
6822 
6823   // At this point, we know we have a conditional branch that determines whether
6824   // the loop is exited.  However, we don't know if the branch is executed each
6825   // time through the loop.  If not, then the execution count of the branch will
6826   // not be equal to the trip count of the loop.
6827   //
6828   // Currently we check for this by checking to see if the Exit branch goes to
6829   // the loop header.  If so, we know it will always execute the same number of
6830   // times as the loop.  We also handle the case where the exit block *is* the
6831   // loop header.  This is common for un-rotated loops.
6832   //
6833   // If both of those tests fail, walk up the unique predecessor chain to the
6834   // header, stopping if there is an edge that doesn't exit the loop. If the
6835   // header is reached, the execution count of the branch will be equal to the
6836   // trip count of the loop.
6837   //
6838   //  More extensive analysis could be done to handle more cases here.
6839   //
6840   if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) {
6841     // The simple checks failed, try climbing the unique predecessor chain
6842     // up to the header.
6843     bool Ok = false;
6844     for (BasicBlock *BB = ExitingBlock; BB; ) {
6845       BasicBlock *Pred = BB->getUniquePredecessor();
6846       if (!Pred)
6847         return getCouldNotCompute();
6848       TerminatorInst *PredTerm = Pred->getTerminator();
6849       for (const BasicBlock *PredSucc : PredTerm->successors()) {
6850         if (PredSucc == BB)
6851           continue;
6852         // If the predecessor has a successor that isn't BB and isn't
6853         // outside the loop, assume the worst.
6854         if (L->contains(PredSucc))
6855           return getCouldNotCompute();
6856       }
6857       if (Pred == L->getHeader()) {
6858         Ok = true;
6859         break;
6860       }
6861       BB = Pred;
6862     }
6863     if (!Ok)
6864       return getCouldNotCompute();
6865   }
6866 
6867   bool IsOnlyExit = (L->getExitingBlock() != nullptr);
6868   TerminatorInst *Term = ExitingBlock->getTerminator();
6869   if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
6870     assert(BI->isConditional() && "If unconditional, it can't be in loop!");
6871     // Proceed to the next level to examine the exit condition expression.
6872     return computeExitLimitFromCond(
6873         L, BI->getCondition(), BI->getSuccessor(0), BI->getSuccessor(1),
6874         /*ControlsExit=*/IsOnlyExit, AllowPredicates);
6875   }
6876 
6877   if (SwitchInst *SI = dyn_cast<SwitchInst>(Term))
6878     return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
6879                                                 /*ControlsExit=*/IsOnlyExit);
6880 
6881   return getCouldNotCompute();
6882 }
6883 
6884 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond(
6885     const Loop *L, Value *ExitCond, BasicBlock *TBB, BasicBlock *FBB,
6886     bool ControlsExit, bool AllowPredicates) {
6887   ScalarEvolution::ExitLimitCacheTy Cache(L, TBB, FBB, AllowPredicates);
6888   return computeExitLimitFromCondCached(Cache, L, ExitCond, TBB, FBB,
6889                                         ControlsExit, AllowPredicates);
6890 }
6891 
6892 Optional<ScalarEvolution::ExitLimit>
6893 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
6894                                       BasicBlock *TBB, BasicBlock *FBB,
6895                                       bool ControlsExit, bool AllowPredicates) {
6896   (void)this->L;
6897   (void)this->TBB;
6898   (void)this->FBB;
6899   (void)this->AllowPredicates;
6900 
6901   assert(this->L == L && this->TBB == TBB && this->FBB == FBB &&
6902          this->AllowPredicates == AllowPredicates &&
6903          "Variance in assumed invariant key components!");
6904   auto Itr = TripCountMap.find({ExitCond, ControlsExit});
6905   if (Itr == TripCountMap.end())
6906     return None;
6907   return Itr->second;
6908 }
6909 
6910 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
6911                                              BasicBlock *TBB, BasicBlock *FBB,
6912                                              bool ControlsExit,
6913                                              bool AllowPredicates,
6914                                              const ExitLimit &EL) {
6915   assert(this->L == L && this->TBB == TBB && this->FBB == FBB &&
6916          this->AllowPredicates == AllowPredicates &&
6917          "Variance in assumed invariant key components!");
6918 
6919   auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL});
6920   assert(InsertResult.second && "Expected successful insertion!");
6921   (void)InsertResult;
6922 }
6923 
6924 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
6925     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, BasicBlock *TBB,
6926     BasicBlock *FBB, bool ControlsExit, bool AllowPredicates) {
6927 
6928   if (auto MaybeEL =
6929           Cache.find(L, ExitCond, TBB, FBB, ControlsExit, AllowPredicates))
6930     return *MaybeEL;
6931 
6932   ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, TBB, FBB,
6933                                               ControlsExit, AllowPredicates);
6934   Cache.insert(L, ExitCond, TBB, FBB, ControlsExit, AllowPredicates, EL);
6935   return EL;
6936 }
6937 
6938 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
6939     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, BasicBlock *TBB,
6940     BasicBlock *FBB, bool ControlsExit, bool AllowPredicates) {
6941   // Check if the controlling expression for this loop is an And or Or.
6942   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
6943     if (BO->getOpcode() == Instruction::And) {
6944       // Recurse on the operands of the and.
6945       bool EitherMayExit = L->contains(TBB);
6946       ExitLimit EL0 = computeExitLimitFromCondCached(
6947           Cache, L, BO->getOperand(0), TBB, FBB, ControlsExit && !EitherMayExit,
6948           AllowPredicates);
6949       ExitLimit EL1 = computeExitLimitFromCondCached(
6950           Cache, L, BO->getOperand(1), TBB, FBB, ControlsExit && !EitherMayExit,
6951           AllowPredicates);
6952       const SCEV *BECount = getCouldNotCompute();
6953       const SCEV *MaxBECount = getCouldNotCompute();
6954       if (EitherMayExit) {
6955         // Both conditions must be true for the loop to continue executing.
6956         // Choose the less conservative count.
6957         if (EL0.ExactNotTaken == getCouldNotCompute() ||
6958             EL1.ExactNotTaken == getCouldNotCompute())
6959           BECount = getCouldNotCompute();
6960         else
6961           BECount =
6962               getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
6963         if (EL0.MaxNotTaken == getCouldNotCompute())
6964           MaxBECount = EL1.MaxNotTaken;
6965         else if (EL1.MaxNotTaken == getCouldNotCompute())
6966           MaxBECount = EL0.MaxNotTaken;
6967         else
6968           MaxBECount =
6969               getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
6970       } else {
6971         // Both conditions must be true at the same time for the loop to exit.
6972         // For now, be conservative.
6973         assert(L->contains(FBB) && "Loop block has no successor in loop!");
6974         if (EL0.MaxNotTaken == EL1.MaxNotTaken)
6975           MaxBECount = EL0.MaxNotTaken;
6976         if (EL0.ExactNotTaken == EL1.ExactNotTaken)
6977           BECount = EL0.ExactNotTaken;
6978       }
6979 
6980       // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
6981       // to be more aggressive when computing BECount than when computing
6982       // MaxBECount.  In these cases it is possible for EL0.ExactNotTaken and
6983       // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
6984       // to not.
6985       if (isa<SCEVCouldNotCompute>(MaxBECount) &&
6986           !isa<SCEVCouldNotCompute>(BECount))
6987         MaxBECount = getConstant(getUnsignedRangeMax(BECount));
6988 
6989       return ExitLimit(BECount, MaxBECount, false,
6990                        {&EL0.Predicates, &EL1.Predicates});
6991     }
6992     if (BO->getOpcode() == Instruction::Or) {
6993       // Recurse on the operands of the or.
6994       bool EitherMayExit = L->contains(FBB);
6995       ExitLimit EL0 = computeExitLimitFromCondCached(
6996           Cache, L, BO->getOperand(0), TBB, FBB, ControlsExit && !EitherMayExit,
6997           AllowPredicates);
6998       ExitLimit EL1 = computeExitLimitFromCondCached(
6999           Cache, L, BO->getOperand(1), TBB, FBB, ControlsExit && !EitherMayExit,
7000           AllowPredicates);
7001       const SCEV *BECount = getCouldNotCompute();
7002       const SCEV *MaxBECount = getCouldNotCompute();
7003       if (EitherMayExit) {
7004         // Both conditions must be false for the loop to continue executing.
7005         // Choose the less conservative count.
7006         if (EL0.ExactNotTaken == getCouldNotCompute() ||
7007             EL1.ExactNotTaken == getCouldNotCompute())
7008           BECount = getCouldNotCompute();
7009         else
7010           BECount =
7011               getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
7012         if (EL0.MaxNotTaken == getCouldNotCompute())
7013           MaxBECount = EL1.MaxNotTaken;
7014         else if (EL1.MaxNotTaken == getCouldNotCompute())
7015           MaxBECount = EL0.MaxNotTaken;
7016         else
7017           MaxBECount =
7018               getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
7019       } else {
7020         // Both conditions must be false at the same time for the loop to exit.
7021         // For now, be conservative.
7022         assert(L->contains(TBB) && "Loop block has no successor in loop!");
7023         if (EL0.MaxNotTaken == EL1.MaxNotTaken)
7024           MaxBECount = EL0.MaxNotTaken;
7025         if (EL0.ExactNotTaken == EL1.ExactNotTaken)
7026           BECount = EL0.ExactNotTaken;
7027       }
7028 
7029       return ExitLimit(BECount, MaxBECount, false,
7030                        {&EL0.Predicates, &EL1.Predicates});
7031     }
7032   }
7033 
7034   // With an icmp, it may be feasible to compute an exact backedge-taken count.
7035   // Proceed to the next level to examine the icmp.
7036   if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
7037     ExitLimit EL =
7038         computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit);
7039     if (EL.hasFullInfo() || !AllowPredicates)
7040       return EL;
7041 
7042     // Try again, but use SCEV predicates this time.
7043     return computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit,
7044                                     /*AllowPredicates=*/true);
7045   }
7046 
7047   // Check for a constant condition. These are normally stripped out by
7048   // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
7049   // preserve the CFG and is temporarily leaving constant conditions
7050   // in place.
7051   if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
7052     if (L->contains(FBB) == !CI->getZExtValue())
7053       // The backedge is always taken.
7054       return getCouldNotCompute();
7055     else
7056       // The backedge is never taken.
7057       return getZero(CI->getType());
7058   }
7059 
7060   // If it's not an integer or pointer comparison then compute it the hard way.
7061   return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
7062 }
7063 
7064 ScalarEvolution::ExitLimit
7065 ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
7066                                           ICmpInst *ExitCond,
7067                                           BasicBlock *TBB,
7068                                           BasicBlock *FBB,
7069                                           bool ControlsExit,
7070                                           bool AllowPredicates) {
7071   // If the condition was exit on true, convert the condition to exit on false
7072   ICmpInst::Predicate Pred;
7073   if (!L->contains(FBB))
7074     Pred = ExitCond->getPredicate();
7075   else
7076     Pred = ExitCond->getInversePredicate();
7077   const ICmpInst::Predicate OriginalPred = Pred;
7078 
7079   // Handle common loops like: for (X = "string"; *X; ++X)
7080   if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
7081     if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
7082       ExitLimit ItCnt =
7083         computeLoadConstantCompareExitLimit(LI, RHS, L, Pred);
7084       if (ItCnt.hasAnyInfo())
7085         return ItCnt;
7086     }
7087 
7088   const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
7089   const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
7090 
7091   // Try to evaluate any dependencies out of the loop.
7092   LHS = getSCEVAtScope(LHS, L);
7093   RHS = getSCEVAtScope(RHS, L);
7094 
7095   // At this point, we would like to compute how many iterations of the
7096   // loop the predicate will return true for these inputs.
7097   if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
7098     // If there is a loop-invariant, force it into the RHS.
7099     std::swap(LHS, RHS);
7100     Pred = ICmpInst::getSwappedPredicate(Pred);
7101   }
7102 
7103   // Simplify the operands before analyzing them.
7104   (void)SimplifyICmpOperands(Pred, LHS, RHS);
7105 
7106   // If we have a comparison of a chrec against a constant, try to use value
7107   // ranges to answer this query.
7108   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
7109     if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
7110       if (AddRec->getLoop() == L) {
7111         // Form the constant range.
7112         ConstantRange CompRange =
7113             ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt());
7114 
7115         const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
7116         if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
7117       }
7118 
7119   switch (Pred) {
7120   case ICmpInst::ICMP_NE: {                     // while (X != Y)
7121     // Convert to: while (X-Y != 0)
7122     ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit,
7123                                 AllowPredicates);
7124     if (EL.hasAnyInfo()) return EL;
7125     break;
7126   }
7127   case ICmpInst::ICMP_EQ: {                     // while (X == Y)
7128     // Convert to: while (X-Y == 0)
7129     ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
7130     if (EL.hasAnyInfo()) return EL;
7131     break;
7132   }
7133   case ICmpInst::ICMP_SLT:
7134   case ICmpInst::ICMP_ULT: {                    // while (X < Y)
7135     bool IsSigned = Pred == ICmpInst::ICMP_SLT;
7136     ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit,
7137                                     AllowPredicates);
7138     if (EL.hasAnyInfo()) return EL;
7139     break;
7140   }
7141   case ICmpInst::ICMP_SGT:
7142   case ICmpInst::ICMP_UGT: {                    // while (X > Y)
7143     bool IsSigned = Pred == ICmpInst::ICMP_SGT;
7144     ExitLimit EL =
7145         howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
7146                             AllowPredicates);
7147     if (EL.hasAnyInfo()) return EL;
7148     break;
7149   }
7150   default:
7151     break;
7152   }
7153 
7154   auto *ExhaustiveCount =
7155       computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
7156 
7157   if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
7158     return ExhaustiveCount;
7159 
7160   return computeShiftCompareExitLimit(ExitCond->getOperand(0),
7161                                       ExitCond->getOperand(1), L, OriginalPred);
7162 }
7163 
7164 ScalarEvolution::ExitLimit
7165 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
7166                                                       SwitchInst *Switch,
7167                                                       BasicBlock *ExitingBlock,
7168                                                       bool ControlsExit) {
7169   assert(!L->contains(ExitingBlock) && "Not an exiting block!");
7170 
7171   // Give up if the exit is the default dest of a switch.
7172   if (Switch->getDefaultDest() == ExitingBlock)
7173     return getCouldNotCompute();
7174 
7175   assert(L->contains(Switch->getDefaultDest()) &&
7176          "Default case must not exit the loop!");
7177   const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
7178   const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
7179 
7180   // while (X != Y) --> while (X-Y != 0)
7181   ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
7182   if (EL.hasAnyInfo())
7183     return EL;
7184 
7185   return getCouldNotCompute();
7186 }
7187 
7188 static ConstantInt *
7189 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
7190                                 ScalarEvolution &SE) {
7191   const SCEV *InVal = SE.getConstant(C);
7192   const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
7193   assert(isa<SCEVConstant>(Val) &&
7194          "Evaluation of SCEV at constant didn't fold correctly?");
7195   return cast<SCEVConstant>(Val)->getValue();
7196 }
7197 
7198 /// Given an exit condition of 'icmp op load X, cst', try to see if we can
7199 /// compute the backedge execution count.
7200 ScalarEvolution::ExitLimit
7201 ScalarEvolution::computeLoadConstantCompareExitLimit(
7202   LoadInst *LI,
7203   Constant *RHS,
7204   const Loop *L,
7205   ICmpInst::Predicate predicate) {
7206   if (LI->isVolatile()) return getCouldNotCompute();
7207 
7208   // Check to see if the loaded pointer is a getelementptr of a global.
7209   // TODO: Use SCEV instead of manually grubbing with GEPs.
7210   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
7211   if (!GEP) return getCouldNotCompute();
7212 
7213   // Make sure that it is really a constant global we are gepping, with an
7214   // initializer, and make sure the first IDX is really 0.
7215   GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
7216   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
7217       GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
7218       !cast<Constant>(GEP->getOperand(1))->isNullValue())
7219     return getCouldNotCompute();
7220 
7221   // Okay, we allow one non-constant index into the GEP instruction.
7222   Value *VarIdx = nullptr;
7223   std::vector<Constant*> Indexes;
7224   unsigned VarIdxNum = 0;
7225   for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
7226     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
7227       Indexes.push_back(CI);
7228     } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
7229       if (VarIdx) return getCouldNotCompute();  // Multiple non-constant idx's.
7230       VarIdx = GEP->getOperand(i);
7231       VarIdxNum = i-2;
7232       Indexes.push_back(nullptr);
7233     }
7234 
7235   // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
7236   if (!VarIdx)
7237     return getCouldNotCompute();
7238 
7239   // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
7240   // Check to see if X is a loop variant variable value now.
7241   const SCEV *Idx = getSCEV(VarIdx);
7242   Idx = getSCEVAtScope(Idx, L);
7243 
7244   // We can only recognize very limited forms of loop index expressions, in
7245   // particular, only affine AddRec's like {C1,+,C2}.
7246   const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
7247   if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
7248       !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
7249       !isa<SCEVConstant>(IdxExpr->getOperand(1)))
7250     return getCouldNotCompute();
7251 
7252   unsigned MaxSteps = MaxBruteForceIterations;
7253   for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
7254     ConstantInt *ItCst = ConstantInt::get(
7255                            cast<IntegerType>(IdxExpr->getType()), IterationNum);
7256     ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
7257 
7258     // Form the GEP offset.
7259     Indexes[VarIdxNum] = Val;
7260 
7261     Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
7262                                                          Indexes);
7263     if (!Result) break;  // Cannot compute!
7264 
7265     // Evaluate the condition for this iteration.
7266     Result = ConstantExpr::getICmp(predicate, Result, RHS);
7267     if (!isa<ConstantInt>(Result)) break;  // Couldn't decide for sure
7268     if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
7269       ++NumArrayLenItCounts;
7270       return getConstant(ItCst);   // Found terminating iteration!
7271     }
7272   }
7273   return getCouldNotCompute();
7274 }
7275 
7276 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
7277     Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
7278   ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
7279   if (!RHS)
7280     return getCouldNotCompute();
7281 
7282   const BasicBlock *Latch = L->getLoopLatch();
7283   if (!Latch)
7284     return getCouldNotCompute();
7285 
7286   const BasicBlock *Predecessor = L->getLoopPredecessor();
7287   if (!Predecessor)
7288     return getCouldNotCompute();
7289 
7290   // Return true if V is of the form "LHS `shift_op` <positive constant>".
7291   // Return LHS in OutLHS and shift_opt in OutOpCode.
7292   auto MatchPositiveShift =
7293       [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
7294 
7295     using namespace PatternMatch;
7296 
7297     ConstantInt *ShiftAmt;
7298     if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7299       OutOpCode = Instruction::LShr;
7300     else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7301       OutOpCode = Instruction::AShr;
7302     else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7303       OutOpCode = Instruction::Shl;
7304     else
7305       return false;
7306 
7307     return ShiftAmt->getValue().isStrictlyPositive();
7308   };
7309 
7310   // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
7311   //
7312   // loop:
7313   //   %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
7314   //   %iv.shifted = lshr i32 %iv, <positive constant>
7315   //
7316   // Return true on a successful match.  Return the corresponding PHI node (%iv
7317   // above) in PNOut and the opcode of the shift operation in OpCodeOut.
7318   auto MatchShiftRecurrence =
7319       [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
7320     Optional<Instruction::BinaryOps> PostShiftOpCode;
7321 
7322     {
7323       Instruction::BinaryOps OpC;
7324       Value *V;
7325 
7326       // If we encounter a shift instruction, "peel off" the shift operation,
7327       // and remember that we did so.  Later when we inspect %iv's backedge
7328       // value, we will make sure that the backedge value uses the same
7329       // operation.
7330       //
7331       // Note: the peeled shift operation does not have to be the same
7332       // instruction as the one feeding into the PHI's backedge value.  We only
7333       // really care about it being the same *kind* of shift instruction --
7334       // that's all that is required for our later inferences to hold.
7335       if (MatchPositiveShift(LHS, V, OpC)) {
7336         PostShiftOpCode = OpC;
7337         LHS = V;
7338       }
7339     }
7340 
7341     PNOut = dyn_cast<PHINode>(LHS);
7342     if (!PNOut || PNOut->getParent() != L->getHeader())
7343       return false;
7344 
7345     Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
7346     Value *OpLHS;
7347 
7348     return
7349         // The backedge value for the PHI node must be a shift by a positive
7350         // amount
7351         MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
7352 
7353         // of the PHI node itself
7354         OpLHS == PNOut &&
7355 
7356         // and the kind of shift should be match the kind of shift we peeled
7357         // off, if any.
7358         (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut);
7359   };
7360 
7361   PHINode *PN;
7362   Instruction::BinaryOps OpCode;
7363   if (!MatchShiftRecurrence(LHS, PN, OpCode))
7364     return getCouldNotCompute();
7365 
7366   const DataLayout &DL = getDataLayout();
7367 
7368   // The key rationale for this optimization is that for some kinds of shift
7369   // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
7370   // within a finite number of iterations.  If the condition guarding the
7371   // backedge (in the sense that the backedge is taken if the condition is true)
7372   // is false for the value the shift recurrence stabilizes to, then we know
7373   // that the backedge is taken only a finite number of times.
7374 
7375   ConstantInt *StableValue = nullptr;
7376   switch (OpCode) {
7377   default:
7378     llvm_unreachable("Impossible case!");
7379 
7380   case Instruction::AShr: {
7381     // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
7382     // bitwidth(K) iterations.
7383     Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
7384     KnownBits Known = computeKnownBits(FirstValue, DL, 0, nullptr,
7385                                        Predecessor->getTerminator(), &DT);
7386     auto *Ty = cast<IntegerType>(RHS->getType());
7387     if (Known.isNonNegative())
7388       StableValue = ConstantInt::get(Ty, 0);
7389     else if (Known.isNegative())
7390       StableValue = ConstantInt::get(Ty, -1, true);
7391     else
7392       return getCouldNotCompute();
7393 
7394     break;
7395   }
7396   case Instruction::LShr:
7397   case Instruction::Shl:
7398     // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
7399     // stabilize to 0 in at most bitwidth(K) iterations.
7400     StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
7401     break;
7402   }
7403 
7404   auto *Result =
7405       ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
7406   assert(Result->getType()->isIntegerTy(1) &&
7407          "Otherwise cannot be an operand to a branch instruction");
7408 
7409   if (Result->isZeroValue()) {
7410     unsigned BitWidth = getTypeSizeInBits(RHS->getType());
7411     const SCEV *UpperBound =
7412         getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
7413     return ExitLimit(getCouldNotCompute(), UpperBound, false);
7414   }
7415 
7416   return getCouldNotCompute();
7417 }
7418 
7419 /// Return true if we can constant fold an instruction of the specified type,
7420 /// assuming that all operands were constants.
7421 static bool CanConstantFold(const Instruction *I) {
7422   if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
7423       isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
7424       isa<LoadInst>(I))
7425     return true;
7426 
7427   if (const CallInst *CI = dyn_cast<CallInst>(I))
7428     if (const Function *F = CI->getCalledFunction())
7429       return canConstantFoldCallTo(CI, F);
7430   return false;
7431 }
7432 
7433 /// Determine whether this instruction can constant evolve within this loop
7434 /// assuming its operands can all constant evolve.
7435 static bool canConstantEvolve(Instruction *I, const Loop *L) {
7436   // An instruction outside of the loop can't be derived from a loop PHI.
7437   if (!L->contains(I)) return false;
7438 
7439   if (isa<PHINode>(I)) {
7440     // We don't currently keep track of the control flow needed to evaluate
7441     // PHIs, so we cannot handle PHIs inside of loops.
7442     return L->getHeader() == I->getParent();
7443   }
7444 
7445   // If we won't be able to constant fold this expression even if the operands
7446   // are constants, bail early.
7447   return CanConstantFold(I);
7448 }
7449 
7450 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
7451 /// recursing through each instruction operand until reaching a loop header phi.
7452 static PHINode *
7453 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
7454                                DenseMap<Instruction *, PHINode *> &PHIMap,
7455                                unsigned Depth) {
7456   if (Depth > MaxConstantEvolvingDepth)
7457     return nullptr;
7458 
7459   // Otherwise, we can evaluate this instruction if all of its operands are
7460   // constant or derived from a PHI node themselves.
7461   PHINode *PHI = nullptr;
7462   for (Value *Op : UseInst->operands()) {
7463     if (isa<Constant>(Op)) continue;
7464 
7465     Instruction *OpInst = dyn_cast<Instruction>(Op);
7466     if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
7467 
7468     PHINode *P = dyn_cast<PHINode>(OpInst);
7469     if (!P)
7470       // If this operand is already visited, reuse the prior result.
7471       // We may have P != PHI if this is the deepest point at which the
7472       // inconsistent paths meet.
7473       P = PHIMap.lookup(OpInst);
7474     if (!P) {
7475       // Recurse and memoize the results, whether a phi is found or not.
7476       // This recursive call invalidates pointers into PHIMap.
7477       P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1);
7478       PHIMap[OpInst] = P;
7479     }
7480     if (!P)
7481       return nullptr;  // Not evolving from PHI
7482     if (PHI && PHI != P)
7483       return nullptr;  // Evolving from multiple different PHIs.
7484     PHI = P;
7485   }
7486   // This is a expression evolving from a constant PHI!
7487   return PHI;
7488 }
7489 
7490 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
7491 /// in the loop that V is derived from.  We allow arbitrary operations along the
7492 /// way, but the operands of an operation must either be constants or a value
7493 /// derived from a constant PHI.  If this expression does not fit with these
7494 /// constraints, return null.
7495 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
7496   Instruction *I = dyn_cast<Instruction>(V);
7497   if (!I || !canConstantEvolve(I, L)) return nullptr;
7498 
7499   if (PHINode *PN = dyn_cast<PHINode>(I))
7500     return PN;
7501 
7502   // Record non-constant instructions contained by the loop.
7503   DenseMap<Instruction *, PHINode *> PHIMap;
7504   return getConstantEvolvingPHIOperands(I, L, PHIMap, 0);
7505 }
7506 
7507 /// EvaluateExpression - Given an expression that passes the
7508 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
7509 /// in the loop has the value PHIVal.  If we can't fold this expression for some
7510 /// reason, return null.
7511 static Constant *EvaluateExpression(Value *V, const Loop *L,
7512                                     DenseMap<Instruction *, Constant *> &Vals,
7513                                     const DataLayout &DL,
7514                                     const TargetLibraryInfo *TLI) {
7515   // Convenient constant check, but redundant for recursive calls.
7516   if (Constant *C = dyn_cast<Constant>(V)) return C;
7517   Instruction *I = dyn_cast<Instruction>(V);
7518   if (!I) return nullptr;
7519 
7520   if (Constant *C = Vals.lookup(I)) return C;
7521 
7522   // An instruction inside the loop depends on a value outside the loop that we
7523   // weren't given a mapping for, or a value such as a call inside the loop.
7524   if (!canConstantEvolve(I, L)) return nullptr;
7525 
7526   // An unmapped PHI can be due to a branch or another loop inside this loop,
7527   // or due to this not being the initial iteration through a loop where we
7528   // couldn't compute the evolution of this particular PHI last time.
7529   if (isa<PHINode>(I)) return nullptr;
7530 
7531   std::vector<Constant*> Operands(I->getNumOperands());
7532 
7533   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
7534     Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
7535     if (!Operand) {
7536       Operands[i] = dyn_cast<Constant>(I->getOperand(i));
7537       if (!Operands[i]) return nullptr;
7538       continue;
7539     }
7540     Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
7541     Vals[Operand] = C;
7542     if (!C) return nullptr;
7543     Operands[i] = C;
7544   }
7545 
7546   if (CmpInst *CI = dyn_cast<CmpInst>(I))
7547     return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
7548                                            Operands[1], DL, TLI);
7549   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
7550     if (!LI->isVolatile())
7551       return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
7552   }
7553   return ConstantFoldInstOperands(I, Operands, DL, TLI);
7554 }
7555 
7556 
7557 // If every incoming value to PN except the one for BB is a specific Constant,
7558 // return that, else return nullptr.
7559 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
7560   Constant *IncomingVal = nullptr;
7561 
7562   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
7563     if (PN->getIncomingBlock(i) == BB)
7564       continue;
7565 
7566     auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
7567     if (!CurrentVal)
7568       return nullptr;
7569 
7570     if (IncomingVal != CurrentVal) {
7571       if (IncomingVal)
7572         return nullptr;
7573       IncomingVal = CurrentVal;
7574     }
7575   }
7576 
7577   return IncomingVal;
7578 }
7579 
7580 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
7581 /// in the header of its containing loop, we know the loop executes a
7582 /// constant number of times, and the PHI node is just a recurrence
7583 /// involving constants, fold it.
7584 Constant *
7585 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
7586                                                    const APInt &BEs,
7587                                                    const Loop *L) {
7588   auto I = ConstantEvolutionLoopExitValue.find(PN);
7589   if (I != ConstantEvolutionLoopExitValue.end())
7590     return I->second;
7591 
7592   if (BEs.ugt(MaxBruteForceIterations))
7593     return ConstantEvolutionLoopExitValue[PN] = nullptr;  // Not going to evaluate it.
7594 
7595   Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
7596 
7597   DenseMap<Instruction *, Constant *> CurrentIterVals;
7598   BasicBlock *Header = L->getHeader();
7599   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
7600 
7601   BasicBlock *Latch = L->getLoopLatch();
7602   if (!Latch)
7603     return nullptr;
7604 
7605   for (auto &I : *Header) {
7606     PHINode *PHI = dyn_cast<PHINode>(&I);
7607     if (!PHI) break;
7608     auto *StartCST = getOtherIncomingValue(PHI, Latch);
7609     if (!StartCST) continue;
7610     CurrentIterVals[PHI] = StartCST;
7611   }
7612   if (!CurrentIterVals.count(PN))
7613     return RetVal = nullptr;
7614 
7615   Value *BEValue = PN->getIncomingValueForBlock(Latch);
7616 
7617   // Execute the loop symbolically to determine the exit value.
7618   assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) &&
7619          "BEs is <= MaxBruteForceIterations which is an 'unsigned'!");
7620 
7621   unsigned NumIterations = BEs.getZExtValue(); // must be in range
7622   unsigned IterationNum = 0;
7623   const DataLayout &DL = getDataLayout();
7624   for (; ; ++IterationNum) {
7625     if (IterationNum == NumIterations)
7626       return RetVal = CurrentIterVals[PN];  // Got exit value!
7627 
7628     // Compute the value of the PHIs for the next iteration.
7629     // EvaluateExpression adds non-phi values to the CurrentIterVals map.
7630     DenseMap<Instruction *, Constant *> NextIterVals;
7631     Constant *NextPHI =
7632         EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
7633     if (!NextPHI)
7634       return nullptr;        // Couldn't evaluate!
7635     NextIterVals[PN] = NextPHI;
7636 
7637     bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
7638 
7639     // Also evaluate the other PHI nodes.  However, we don't get to stop if we
7640     // cease to be able to evaluate one of them or if they stop evolving,
7641     // because that doesn't necessarily prevent us from computing PN.
7642     SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
7643     for (const auto &I : CurrentIterVals) {
7644       PHINode *PHI = dyn_cast<PHINode>(I.first);
7645       if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
7646       PHIsToCompute.emplace_back(PHI, I.second);
7647     }
7648     // We use two distinct loops because EvaluateExpression may invalidate any
7649     // iterators into CurrentIterVals.
7650     for (const auto &I : PHIsToCompute) {
7651       PHINode *PHI = I.first;
7652       Constant *&NextPHI = NextIterVals[PHI];
7653       if (!NextPHI) {   // Not already computed.
7654         Value *BEValue = PHI->getIncomingValueForBlock(Latch);
7655         NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
7656       }
7657       if (NextPHI != I.second)
7658         StoppedEvolving = false;
7659     }
7660 
7661     // If all entries in CurrentIterVals == NextIterVals then we can stop
7662     // iterating, the loop can't continue to change.
7663     if (StoppedEvolving)
7664       return RetVal = CurrentIterVals[PN];
7665 
7666     CurrentIterVals.swap(NextIterVals);
7667   }
7668 }
7669 
7670 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
7671                                                           Value *Cond,
7672                                                           bool ExitWhen) {
7673   PHINode *PN = getConstantEvolvingPHI(Cond, L);
7674   if (!PN) return getCouldNotCompute();
7675 
7676   // If the loop is canonicalized, the PHI will have exactly two entries.
7677   // That's the only form we support here.
7678   if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
7679 
7680   DenseMap<Instruction *, Constant *> CurrentIterVals;
7681   BasicBlock *Header = L->getHeader();
7682   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
7683 
7684   BasicBlock *Latch = L->getLoopLatch();
7685   assert(Latch && "Should follow from NumIncomingValues == 2!");
7686 
7687   for (auto &I : *Header) {
7688     PHINode *PHI = dyn_cast<PHINode>(&I);
7689     if (!PHI)
7690       break;
7691     auto *StartCST = getOtherIncomingValue(PHI, Latch);
7692     if (!StartCST) continue;
7693     CurrentIterVals[PHI] = StartCST;
7694   }
7695   if (!CurrentIterVals.count(PN))
7696     return getCouldNotCompute();
7697 
7698   // Okay, we find a PHI node that defines the trip count of this loop.  Execute
7699   // the loop symbolically to determine when the condition gets a value of
7700   // "ExitWhen".
7701   unsigned MaxIterations = MaxBruteForceIterations;   // Limit analysis.
7702   const DataLayout &DL = getDataLayout();
7703   for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
7704     auto *CondVal = dyn_cast_or_null<ConstantInt>(
7705         EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
7706 
7707     // Couldn't symbolically evaluate.
7708     if (!CondVal) return getCouldNotCompute();
7709 
7710     if (CondVal->getValue() == uint64_t(ExitWhen)) {
7711       ++NumBruteForceTripCountsComputed;
7712       return getConstant(Type::getInt32Ty(getContext()), IterationNum);
7713     }
7714 
7715     // Update all the PHI nodes for the next iteration.
7716     DenseMap<Instruction *, Constant *> NextIterVals;
7717 
7718     // Create a list of which PHIs we need to compute. We want to do this before
7719     // calling EvaluateExpression on them because that may invalidate iterators
7720     // into CurrentIterVals.
7721     SmallVector<PHINode *, 8> PHIsToCompute;
7722     for (const auto &I : CurrentIterVals) {
7723       PHINode *PHI = dyn_cast<PHINode>(I.first);
7724       if (!PHI || PHI->getParent() != Header) continue;
7725       PHIsToCompute.push_back(PHI);
7726     }
7727     for (PHINode *PHI : PHIsToCompute) {
7728       Constant *&NextPHI = NextIterVals[PHI];
7729       if (NextPHI) continue;    // Already computed!
7730 
7731       Value *BEValue = PHI->getIncomingValueForBlock(Latch);
7732       NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
7733     }
7734     CurrentIterVals.swap(NextIterVals);
7735   }
7736 
7737   // Too many iterations were needed to evaluate.
7738   return getCouldNotCompute();
7739 }
7740 
7741 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
7742   SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
7743       ValuesAtScopes[V];
7744   // Check to see if we've folded this expression at this loop before.
7745   for (auto &LS : Values)
7746     if (LS.first == L)
7747       return LS.second ? LS.second : V;
7748 
7749   Values.emplace_back(L, nullptr);
7750 
7751   // Otherwise compute it.
7752   const SCEV *C = computeSCEVAtScope(V, L);
7753   for (auto &LS : reverse(ValuesAtScopes[V]))
7754     if (LS.first == L) {
7755       LS.second = C;
7756       break;
7757     }
7758   return C;
7759 }
7760 
7761 /// This builds up a Constant using the ConstantExpr interface.  That way, we
7762 /// will return Constants for objects which aren't represented by a
7763 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
7764 /// Returns NULL if the SCEV isn't representable as a Constant.
7765 static Constant *BuildConstantFromSCEV(const SCEV *V) {
7766   switch (static_cast<SCEVTypes>(V->getSCEVType())) {
7767     case scCouldNotCompute:
7768     case scAddRecExpr:
7769       break;
7770     case scConstant:
7771       return cast<SCEVConstant>(V)->getValue();
7772     case scUnknown:
7773       return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
7774     case scSignExtend: {
7775       const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
7776       if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
7777         return ConstantExpr::getSExt(CastOp, SS->getType());
7778       break;
7779     }
7780     case scZeroExtend: {
7781       const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
7782       if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
7783         return ConstantExpr::getZExt(CastOp, SZ->getType());
7784       break;
7785     }
7786     case scTruncate: {
7787       const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
7788       if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
7789         return ConstantExpr::getTrunc(CastOp, ST->getType());
7790       break;
7791     }
7792     case scAddExpr: {
7793       const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
7794       if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
7795         if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
7796           unsigned AS = PTy->getAddressSpace();
7797           Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
7798           C = ConstantExpr::getBitCast(C, DestPtrTy);
7799         }
7800         for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
7801           Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
7802           if (!C2) return nullptr;
7803 
7804           // First pointer!
7805           if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
7806             unsigned AS = C2->getType()->getPointerAddressSpace();
7807             std::swap(C, C2);
7808             Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
7809             // The offsets have been converted to bytes.  We can add bytes to an
7810             // i8* by GEP with the byte count in the first index.
7811             C = ConstantExpr::getBitCast(C, DestPtrTy);
7812           }
7813 
7814           // Don't bother trying to sum two pointers. We probably can't
7815           // statically compute a load that results from it anyway.
7816           if (C2->getType()->isPointerTy())
7817             return nullptr;
7818 
7819           if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
7820             if (PTy->getElementType()->isStructTy())
7821               C2 = ConstantExpr::getIntegerCast(
7822                   C2, Type::getInt32Ty(C->getContext()), true);
7823             C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2);
7824           } else
7825             C = ConstantExpr::getAdd(C, C2);
7826         }
7827         return C;
7828       }
7829       break;
7830     }
7831     case scMulExpr: {
7832       const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
7833       if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
7834         // Don't bother with pointers at all.
7835         if (C->getType()->isPointerTy()) return nullptr;
7836         for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
7837           Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
7838           if (!C2 || C2->getType()->isPointerTy()) return nullptr;
7839           C = ConstantExpr::getMul(C, C2);
7840         }
7841         return C;
7842       }
7843       break;
7844     }
7845     case scUDivExpr: {
7846       const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
7847       if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
7848         if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
7849           if (LHS->getType() == RHS->getType())
7850             return ConstantExpr::getUDiv(LHS, RHS);
7851       break;
7852     }
7853     case scSMaxExpr:
7854     case scUMaxExpr:
7855       break; // TODO: smax, umax.
7856   }
7857   return nullptr;
7858 }
7859 
7860 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
7861   if (isa<SCEVConstant>(V)) return V;
7862 
7863   // If this instruction is evolved from a constant-evolving PHI, compute the
7864   // exit value from the loop without using SCEVs.
7865   if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
7866     if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
7867       const Loop *LI = this->LI[I->getParent()];
7868       if (LI && LI->getParentLoop() == L)  // Looking for loop exit value.
7869         if (PHINode *PN = dyn_cast<PHINode>(I))
7870           if (PN->getParent() == LI->getHeader()) {
7871             // Okay, there is no closed form solution for the PHI node.  Check
7872             // to see if the loop that contains it has a known backedge-taken
7873             // count.  If so, we may be able to force computation of the exit
7874             // value.
7875             const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
7876             if (const SCEVConstant *BTCC =
7877                   dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
7878 
7879               // This trivial case can show up in some degenerate cases where
7880               // the incoming IR has not yet been fully simplified.
7881               if (BTCC->getValue()->isZero()) {
7882                 Value *InitValue = nullptr;
7883                 bool MultipleInitValues = false;
7884                 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
7885                   if (!LI->contains(PN->getIncomingBlock(i))) {
7886                     if (!InitValue)
7887                       InitValue = PN->getIncomingValue(i);
7888                     else if (InitValue != PN->getIncomingValue(i)) {
7889                       MultipleInitValues = true;
7890                       break;
7891                     }
7892                   }
7893                   if (!MultipleInitValues && InitValue)
7894                     return getSCEV(InitValue);
7895                 }
7896               }
7897               // Okay, we know how many times the containing loop executes.  If
7898               // this is a constant evolving PHI node, get the final value at
7899               // the specified iteration number.
7900               Constant *RV =
7901                   getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI);
7902               if (RV) return getSCEV(RV);
7903             }
7904           }
7905 
7906       // Okay, this is an expression that we cannot symbolically evaluate
7907       // into a SCEV.  Check to see if it's possible to symbolically evaluate
7908       // the arguments into constants, and if so, try to constant propagate the
7909       // result.  This is particularly useful for computing loop exit values.
7910       if (CanConstantFold(I)) {
7911         SmallVector<Constant *, 4> Operands;
7912         bool MadeImprovement = false;
7913         for (Value *Op : I->operands()) {
7914           if (Constant *C = dyn_cast<Constant>(Op)) {
7915             Operands.push_back(C);
7916             continue;
7917           }
7918 
7919           // If any of the operands is non-constant and if they are
7920           // non-integer and non-pointer, don't even try to analyze them
7921           // with scev techniques.
7922           if (!isSCEVable(Op->getType()))
7923             return V;
7924 
7925           const SCEV *OrigV = getSCEV(Op);
7926           const SCEV *OpV = getSCEVAtScope(OrigV, L);
7927           MadeImprovement |= OrigV != OpV;
7928 
7929           Constant *C = BuildConstantFromSCEV(OpV);
7930           if (!C) return V;
7931           if (C->getType() != Op->getType())
7932             C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
7933                                                               Op->getType(),
7934                                                               false),
7935                                       C, Op->getType());
7936           Operands.push_back(C);
7937         }
7938 
7939         // Check to see if getSCEVAtScope actually made an improvement.
7940         if (MadeImprovement) {
7941           Constant *C = nullptr;
7942           const DataLayout &DL = getDataLayout();
7943           if (const CmpInst *CI = dyn_cast<CmpInst>(I))
7944             C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
7945                                                 Operands[1], DL, &TLI);
7946           else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
7947             if (!LI->isVolatile())
7948               C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
7949           } else
7950             C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
7951           if (!C) return V;
7952           return getSCEV(C);
7953         }
7954       }
7955     }
7956 
7957     // This is some other type of SCEVUnknown, just return it.
7958     return V;
7959   }
7960 
7961   if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
7962     // Avoid performing the look-up in the common case where the specified
7963     // expression has no loop-variant portions.
7964     for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
7965       const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
7966       if (OpAtScope != Comm->getOperand(i)) {
7967         // Okay, at least one of these operands is loop variant but might be
7968         // foldable.  Build a new instance of the folded commutative expression.
7969         SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
7970                                             Comm->op_begin()+i);
7971         NewOps.push_back(OpAtScope);
7972 
7973         for (++i; i != e; ++i) {
7974           OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
7975           NewOps.push_back(OpAtScope);
7976         }
7977         if (isa<SCEVAddExpr>(Comm))
7978           return getAddExpr(NewOps);
7979         if (isa<SCEVMulExpr>(Comm))
7980           return getMulExpr(NewOps);
7981         if (isa<SCEVSMaxExpr>(Comm))
7982           return getSMaxExpr(NewOps);
7983         if (isa<SCEVUMaxExpr>(Comm))
7984           return getUMaxExpr(NewOps);
7985         llvm_unreachable("Unknown commutative SCEV type!");
7986       }
7987     }
7988     // If we got here, all operands are loop invariant.
7989     return Comm;
7990   }
7991 
7992   if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
7993     const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
7994     const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
7995     if (LHS == Div->getLHS() && RHS == Div->getRHS())
7996       return Div;   // must be loop invariant
7997     return getUDivExpr(LHS, RHS);
7998   }
7999 
8000   // If this is a loop recurrence for a loop that does not contain L, then we
8001   // are dealing with the final value computed by the loop.
8002   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
8003     // First, attempt to evaluate each operand.
8004     // Avoid performing the look-up in the common case where the specified
8005     // expression has no loop-variant portions.
8006     for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
8007       const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
8008       if (OpAtScope == AddRec->getOperand(i))
8009         continue;
8010 
8011       // Okay, at least one of these operands is loop variant but might be
8012       // foldable.  Build a new instance of the folded commutative expression.
8013       SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
8014                                           AddRec->op_begin()+i);
8015       NewOps.push_back(OpAtScope);
8016       for (++i; i != e; ++i)
8017         NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
8018 
8019       const SCEV *FoldedRec =
8020         getAddRecExpr(NewOps, AddRec->getLoop(),
8021                       AddRec->getNoWrapFlags(SCEV::FlagNW));
8022       AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
8023       // The addrec may be folded to a nonrecurrence, for example, if the
8024       // induction variable is multiplied by zero after constant folding. Go
8025       // ahead and return the folded value.
8026       if (!AddRec)
8027         return FoldedRec;
8028       break;
8029     }
8030 
8031     // If the scope is outside the addrec's loop, evaluate it by using the
8032     // loop exit value of the addrec.
8033     if (!AddRec->getLoop()->contains(L)) {
8034       // To evaluate this recurrence, we need to know how many times the AddRec
8035       // loop iterates.  Compute this now.
8036       const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
8037       if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
8038 
8039       // Then, evaluate the AddRec.
8040       return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
8041     }
8042 
8043     return AddRec;
8044   }
8045 
8046   if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
8047     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8048     if (Op == Cast->getOperand())
8049       return Cast;  // must be loop invariant
8050     return getZeroExtendExpr(Op, Cast->getType());
8051   }
8052 
8053   if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
8054     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8055     if (Op == Cast->getOperand())
8056       return Cast;  // must be loop invariant
8057     return getSignExtendExpr(Op, Cast->getType());
8058   }
8059 
8060   if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
8061     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8062     if (Op == Cast->getOperand())
8063       return Cast;  // must be loop invariant
8064     return getTruncateExpr(Op, Cast->getType());
8065   }
8066 
8067   llvm_unreachable("Unknown SCEV type!");
8068 }
8069 
8070 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
8071   return getSCEVAtScope(getSCEV(V), L);
8072 }
8073 
8074 /// Finds the minimum unsigned root of the following equation:
8075 ///
8076 ///     A * X = B (mod N)
8077 ///
8078 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
8079 /// A and B isn't important.
8080 ///
8081 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
8082 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B,
8083                                                ScalarEvolution &SE) {
8084   uint32_t BW = A.getBitWidth();
8085   assert(BW == SE.getTypeSizeInBits(B->getType()));
8086   assert(A != 0 && "A must be non-zero.");
8087 
8088   // 1. D = gcd(A, N)
8089   //
8090   // The gcd of A and N may have only one prime factor: 2. The number of
8091   // trailing zeros in A is its multiplicity
8092   uint32_t Mult2 = A.countTrailingZeros();
8093   // D = 2^Mult2
8094 
8095   // 2. Check if B is divisible by D.
8096   //
8097   // B is divisible by D if and only if the multiplicity of prime factor 2 for B
8098   // is not less than multiplicity of this prime factor for D.
8099   if (SE.GetMinTrailingZeros(B) < Mult2)
8100     return SE.getCouldNotCompute();
8101 
8102   // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
8103   // modulo (N / D).
8104   //
8105   // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
8106   // (N / D) in general. The inverse itself always fits into BW bits, though,
8107   // so we immediately truncate it.
8108   APInt AD = A.lshr(Mult2).zext(BW + 1);  // AD = A / D
8109   APInt Mod(BW + 1, 0);
8110   Mod.setBit(BW - Mult2);  // Mod = N / D
8111   APInt I = AD.multiplicativeInverse(Mod).trunc(BW);
8112 
8113   // 4. Compute the minimum unsigned root of the equation:
8114   // I * (B / D) mod (N / D)
8115   // To simplify the computation, we factor out the divide by D:
8116   // (I * B mod N) / D
8117   const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
8118   return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
8119 }
8120 
8121 /// Find the roots of the quadratic equation for the given quadratic chrec
8122 /// {L,+,M,+,N}.  This returns either the two roots (which might be the same) or
8123 /// two SCEVCouldNotCompute objects.
8124 static Optional<std::pair<const SCEVConstant *,const SCEVConstant *>>
8125 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
8126   assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
8127   const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
8128   const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
8129   const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
8130 
8131   // We currently can only solve this if the coefficients are constants.
8132   if (!LC || !MC || !NC)
8133     return None;
8134 
8135   uint32_t BitWidth = LC->getAPInt().getBitWidth();
8136   const APInt &L = LC->getAPInt();
8137   const APInt &M = MC->getAPInt();
8138   const APInt &N = NC->getAPInt();
8139   APInt Two(BitWidth, 2);
8140 
8141   // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
8142 
8143   // The A coefficient is N/2
8144   APInt A = N.sdiv(Two);
8145 
8146   // The B coefficient is M-N/2
8147   APInt B = M;
8148   B -= A; // A is the same as N/2.
8149 
8150   // The C coefficient is L.
8151   const APInt& C = L;
8152 
8153   // Compute the B^2-4ac term.
8154   APInt SqrtTerm = B;
8155   SqrtTerm *= B;
8156   SqrtTerm -= 4 * (A * C);
8157 
8158   if (SqrtTerm.isNegative()) {
8159     // The loop is provably infinite.
8160     return None;
8161   }
8162 
8163   // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
8164   // integer value or else APInt::sqrt() will assert.
8165   APInt SqrtVal = SqrtTerm.sqrt();
8166 
8167   // Compute the two solutions for the quadratic formula.
8168   // The divisions must be performed as signed divisions.
8169   APInt NegB = -std::move(B);
8170   APInt TwoA = std::move(A);
8171   TwoA <<= 1;
8172   if (TwoA.isNullValue())
8173     return None;
8174 
8175   LLVMContext &Context = SE.getContext();
8176 
8177   ConstantInt *Solution1 =
8178     ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
8179   ConstantInt *Solution2 =
8180     ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
8181 
8182   return std::make_pair(cast<SCEVConstant>(SE.getConstant(Solution1)),
8183                         cast<SCEVConstant>(SE.getConstant(Solution2)));
8184 }
8185 
8186 ScalarEvolution::ExitLimit
8187 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit,
8188                               bool AllowPredicates) {
8189 
8190   // This is only used for loops with a "x != y" exit test. The exit condition
8191   // is now expressed as a single expression, V = x-y. So the exit test is
8192   // effectively V != 0.  We know and take advantage of the fact that this
8193   // expression only being used in a comparison by zero context.
8194 
8195   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
8196   // If the value is a constant
8197   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
8198     // If the value is already zero, the branch will execute zero times.
8199     if (C->getValue()->isZero()) return C;
8200     return getCouldNotCompute();  // Otherwise it will loop infinitely.
8201   }
8202 
8203   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
8204   if (!AddRec && AllowPredicates)
8205     // Try to make this an AddRec using runtime tests, in the first X
8206     // iterations of this loop, where X is the SCEV expression found by the
8207     // algorithm below.
8208     AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
8209 
8210   if (!AddRec || AddRec->getLoop() != L)
8211     return getCouldNotCompute();
8212 
8213   // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
8214   // the quadratic equation to solve it.
8215   if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
8216     if (auto Roots = SolveQuadraticEquation(AddRec, *this)) {
8217       const SCEVConstant *R1 = Roots->first;
8218       const SCEVConstant *R2 = Roots->second;
8219       // Pick the smallest positive root value.
8220       if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
8221               CmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
8222         if (!CB->getZExtValue())
8223           std::swap(R1, R2); // R1 is the minimum root now.
8224 
8225         // We can only use this value if the chrec ends up with an exact zero
8226         // value at this index.  When solving for "X*X != 5", for example, we
8227         // should not accept a root of 2.
8228         const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
8229         if (Val->isZero())
8230           // We found a quadratic root!
8231           return ExitLimit(R1, R1, false, Predicates);
8232       }
8233     }
8234     return getCouldNotCompute();
8235   }
8236 
8237   // Otherwise we can only handle this if it is affine.
8238   if (!AddRec->isAffine())
8239     return getCouldNotCompute();
8240 
8241   // If this is an affine expression, the execution count of this branch is
8242   // the minimum unsigned root of the following equation:
8243   //
8244   //     Start + Step*N = 0 (mod 2^BW)
8245   //
8246   // equivalent to:
8247   //
8248   //             Step*N = -Start (mod 2^BW)
8249   //
8250   // where BW is the common bit width of Start and Step.
8251 
8252   // Get the initial value for the loop.
8253   const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
8254   const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
8255 
8256   // For now we handle only constant steps.
8257   //
8258   // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
8259   // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
8260   // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
8261   // We have not yet seen any such cases.
8262   const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
8263   if (!StepC || StepC->getValue()->isZero())
8264     return getCouldNotCompute();
8265 
8266   // For positive steps (counting up until unsigned overflow):
8267   //   N = -Start/Step (as unsigned)
8268   // For negative steps (counting down to zero):
8269   //   N = Start/-Step
8270   // First compute the unsigned distance from zero in the direction of Step.
8271   bool CountDown = StepC->getAPInt().isNegative();
8272   const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
8273 
8274   // Handle unitary steps, which cannot wraparound.
8275   // 1*N = -Start; -1*N = Start (mod 2^BW), so:
8276   //   N = Distance (as unsigned)
8277   if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) {
8278     APInt MaxBECount = getUnsignedRangeMax(Distance);
8279 
8280     // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
8281     // we end up with a loop whose backedge-taken count is n - 1.  Detect this
8282     // case, and see if we can improve the bound.
8283     //
8284     // Explicitly handling this here is necessary because getUnsignedRange
8285     // isn't context-sensitive; it doesn't know that we only care about the
8286     // range inside the loop.
8287     const SCEV *Zero = getZero(Distance->getType());
8288     const SCEV *One = getOne(Distance->getType());
8289     const SCEV *DistancePlusOne = getAddExpr(Distance, One);
8290     if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
8291       // If Distance + 1 doesn't overflow, we can compute the maximum distance
8292       // as "unsigned_max(Distance + 1) - 1".
8293       ConstantRange CR = getUnsignedRange(DistancePlusOne);
8294       MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1);
8295     }
8296     return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates);
8297   }
8298 
8299   // If the condition controls loop exit (the loop exits only if the expression
8300   // is true) and the addition is no-wrap we can use unsigned divide to
8301   // compute the backedge count.  In this case, the step may not divide the
8302   // distance, but we don't care because if the condition is "missed" the loop
8303   // will have undefined behavior due to wrapping.
8304   if (ControlsExit && AddRec->hasNoSelfWrap() &&
8305       loopHasNoAbnormalExits(AddRec->getLoop())) {
8306     const SCEV *Exact =
8307         getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
8308     const SCEV *Max =
8309         Exact == getCouldNotCompute()
8310             ? Exact
8311             : getConstant(getUnsignedRangeMax(Exact));
8312     return ExitLimit(Exact, Max, false, Predicates);
8313   }
8314 
8315   // Solve the general equation.
8316   const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(),
8317                                                getNegativeSCEV(Start), *this);
8318   const SCEV *M = E == getCouldNotCompute()
8319                       ? E
8320                       : getConstant(getUnsignedRangeMax(E));
8321   return ExitLimit(E, M, false, Predicates);
8322 }
8323 
8324 ScalarEvolution::ExitLimit
8325 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
8326   // Loops that look like: while (X == 0) are very strange indeed.  We don't
8327   // handle them yet except for the trivial case.  This could be expanded in the
8328   // future as needed.
8329 
8330   // If the value is a constant, check to see if it is known to be non-zero
8331   // already.  If so, the backedge will execute zero times.
8332   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
8333     if (!C->getValue()->isZero())
8334       return getZero(C->getType());
8335     return getCouldNotCompute();  // Otherwise it will loop infinitely.
8336   }
8337 
8338   // We could implement others, but I really doubt anyone writes loops like
8339   // this, and if they did, they would already be constant folded.
8340   return getCouldNotCompute();
8341 }
8342 
8343 std::pair<BasicBlock *, BasicBlock *>
8344 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
8345   // If the block has a unique predecessor, then there is no path from the
8346   // predecessor to the block that does not go through the direct edge
8347   // from the predecessor to the block.
8348   if (BasicBlock *Pred = BB->getSinglePredecessor())
8349     return {Pred, BB};
8350 
8351   // A loop's header is defined to be a block that dominates the loop.
8352   // If the header has a unique predecessor outside the loop, it must be
8353   // a block that has exactly one successor that can reach the loop.
8354   if (Loop *L = LI.getLoopFor(BB))
8355     return {L->getLoopPredecessor(), L->getHeader()};
8356 
8357   return {nullptr, nullptr};
8358 }
8359 
8360 /// SCEV structural equivalence is usually sufficient for testing whether two
8361 /// expressions are equal, however for the purposes of looking for a condition
8362 /// guarding a loop, it can be useful to be a little more general, since a
8363 /// front-end may have replicated the controlling expression.
8364 static bool HasSameValue(const SCEV *A, const SCEV *B) {
8365   // Quick check to see if they are the same SCEV.
8366   if (A == B) return true;
8367 
8368   auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
8369     // Not all instructions that are "identical" compute the same value.  For
8370     // instance, two distinct alloca instructions allocating the same type are
8371     // identical and do not read memory; but compute distinct values.
8372     return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
8373   };
8374 
8375   // Otherwise, if they're both SCEVUnknown, it's possible that they hold
8376   // two different instructions with the same value. Check for this case.
8377   if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
8378     if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
8379       if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
8380         if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
8381           if (ComputesEqualValues(AI, BI))
8382             return true;
8383 
8384   // Otherwise assume they may have a different value.
8385   return false;
8386 }
8387 
8388 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
8389                                            const SCEV *&LHS, const SCEV *&RHS,
8390                                            unsigned Depth) {
8391   bool Changed = false;
8392 
8393   // If we hit the max recursion limit bail out.
8394   if (Depth >= 3)
8395     return false;
8396 
8397   // Canonicalize a constant to the right side.
8398   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
8399     // Check for both operands constant.
8400     if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
8401       if (ConstantExpr::getICmp(Pred,
8402                                 LHSC->getValue(),
8403                                 RHSC->getValue())->isNullValue())
8404         goto trivially_false;
8405       else
8406         goto trivially_true;
8407     }
8408     // Otherwise swap the operands to put the constant on the right.
8409     std::swap(LHS, RHS);
8410     Pred = ICmpInst::getSwappedPredicate(Pred);
8411     Changed = true;
8412   }
8413 
8414   // If we're comparing an addrec with a value which is loop-invariant in the
8415   // addrec's loop, put the addrec on the left. Also make a dominance check,
8416   // as both operands could be addrecs loop-invariant in each other's loop.
8417   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
8418     const Loop *L = AR->getLoop();
8419     if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
8420       std::swap(LHS, RHS);
8421       Pred = ICmpInst::getSwappedPredicate(Pred);
8422       Changed = true;
8423     }
8424   }
8425 
8426   // If there's a constant operand, canonicalize comparisons with boundary
8427   // cases, and canonicalize *-or-equal comparisons to regular comparisons.
8428   if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
8429     const APInt &RA = RC->getAPInt();
8430 
8431     bool SimplifiedByConstantRange = false;
8432 
8433     if (!ICmpInst::isEquality(Pred)) {
8434       ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA);
8435       if (ExactCR.isFullSet())
8436         goto trivially_true;
8437       else if (ExactCR.isEmptySet())
8438         goto trivially_false;
8439 
8440       APInt NewRHS;
8441       CmpInst::Predicate NewPred;
8442       if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
8443           ICmpInst::isEquality(NewPred)) {
8444         // We were able to convert an inequality to an equality.
8445         Pred = NewPred;
8446         RHS = getConstant(NewRHS);
8447         Changed = SimplifiedByConstantRange = true;
8448       }
8449     }
8450 
8451     if (!SimplifiedByConstantRange) {
8452       switch (Pred) {
8453       default:
8454         break;
8455       case ICmpInst::ICMP_EQ:
8456       case ICmpInst::ICMP_NE:
8457         // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
8458         if (!RA)
8459           if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
8460             if (const SCEVMulExpr *ME =
8461                     dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
8462               if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
8463                   ME->getOperand(0)->isAllOnesValue()) {
8464                 RHS = AE->getOperand(1);
8465                 LHS = ME->getOperand(1);
8466                 Changed = true;
8467               }
8468         break;
8469 
8470 
8471         // The "Should have been caught earlier!" messages refer to the fact
8472         // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
8473         // should have fired on the corresponding cases, and canonicalized the
8474         // check to trivially_true or trivially_false.
8475 
8476       case ICmpInst::ICMP_UGE:
8477         assert(!RA.isMinValue() && "Should have been caught earlier!");
8478         Pred = ICmpInst::ICMP_UGT;
8479         RHS = getConstant(RA - 1);
8480         Changed = true;
8481         break;
8482       case ICmpInst::ICMP_ULE:
8483         assert(!RA.isMaxValue() && "Should have been caught earlier!");
8484         Pred = ICmpInst::ICMP_ULT;
8485         RHS = getConstant(RA + 1);
8486         Changed = true;
8487         break;
8488       case ICmpInst::ICMP_SGE:
8489         assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
8490         Pred = ICmpInst::ICMP_SGT;
8491         RHS = getConstant(RA - 1);
8492         Changed = true;
8493         break;
8494       case ICmpInst::ICMP_SLE:
8495         assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
8496         Pred = ICmpInst::ICMP_SLT;
8497         RHS = getConstant(RA + 1);
8498         Changed = true;
8499         break;
8500       }
8501     }
8502   }
8503 
8504   // Check for obvious equality.
8505   if (HasSameValue(LHS, RHS)) {
8506     if (ICmpInst::isTrueWhenEqual(Pred))
8507       goto trivially_true;
8508     if (ICmpInst::isFalseWhenEqual(Pred))
8509       goto trivially_false;
8510   }
8511 
8512   // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
8513   // adding or subtracting 1 from one of the operands.
8514   switch (Pred) {
8515   case ICmpInst::ICMP_SLE:
8516     if (!getSignedRangeMax(RHS).isMaxSignedValue()) {
8517       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
8518                        SCEV::FlagNSW);
8519       Pred = ICmpInst::ICMP_SLT;
8520       Changed = true;
8521     } else if (!getSignedRangeMin(LHS).isMinSignedValue()) {
8522       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
8523                        SCEV::FlagNSW);
8524       Pred = ICmpInst::ICMP_SLT;
8525       Changed = true;
8526     }
8527     break;
8528   case ICmpInst::ICMP_SGE:
8529     if (!getSignedRangeMin(RHS).isMinSignedValue()) {
8530       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
8531                        SCEV::FlagNSW);
8532       Pred = ICmpInst::ICMP_SGT;
8533       Changed = true;
8534     } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) {
8535       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
8536                        SCEV::FlagNSW);
8537       Pred = ICmpInst::ICMP_SGT;
8538       Changed = true;
8539     }
8540     break;
8541   case ICmpInst::ICMP_ULE:
8542     if (!getUnsignedRangeMax(RHS).isMaxValue()) {
8543       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
8544                        SCEV::FlagNUW);
8545       Pred = ICmpInst::ICMP_ULT;
8546       Changed = true;
8547     } else if (!getUnsignedRangeMin(LHS).isMinValue()) {
8548       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
8549       Pred = ICmpInst::ICMP_ULT;
8550       Changed = true;
8551     }
8552     break;
8553   case ICmpInst::ICMP_UGE:
8554     if (!getUnsignedRangeMin(RHS).isMinValue()) {
8555       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
8556       Pred = ICmpInst::ICMP_UGT;
8557       Changed = true;
8558     } else if (!getUnsignedRangeMax(LHS).isMaxValue()) {
8559       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
8560                        SCEV::FlagNUW);
8561       Pred = ICmpInst::ICMP_UGT;
8562       Changed = true;
8563     }
8564     break;
8565   default:
8566     break;
8567   }
8568 
8569   // TODO: More simplifications are possible here.
8570 
8571   // Recursively simplify until we either hit a recursion limit or nothing
8572   // changes.
8573   if (Changed)
8574     return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
8575 
8576   return Changed;
8577 
8578 trivially_true:
8579   // Return 0 == 0.
8580   LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
8581   Pred = ICmpInst::ICMP_EQ;
8582   return true;
8583 
8584 trivially_false:
8585   // Return 0 != 0.
8586   LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
8587   Pred = ICmpInst::ICMP_NE;
8588   return true;
8589 }
8590 
8591 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
8592   return getSignedRangeMax(S).isNegative();
8593 }
8594 
8595 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
8596   return getSignedRangeMin(S).isStrictlyPositive();
8597 }
8598 
8599 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
8600   return !getSignedRangeMin(S).isNegative();
8601 }
8602 
8603 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
8604   return !getSignedRangeMax(S).isStrictlyPositive();
8605 }
8606 
8607 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
8608   return isKnownNegative(S) || isKnownPositive(S);
8609 }
8610 
8611 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
8612                                        const SCEV *LHS, const SCEV *RHS) {
8613   // Canonicalize the inputs first.
8614   (void)SimplifyICmpOperands(Pred, LHS, RHS);
8615 
8616   // If LHS or RHS is an addrec, check to see if the condition is true in
8617   // every iteration of the loop.
8618   // If LHS and RHS are both addrec, both conditions must be true in
8619   // every iteration of the loop.
8620   const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
8621   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
8622   bool LeftGuarded = false;
8623   bool RightGuarded = false;
8624   if (LAR) {
8625     const Loop *L = LAR->getLoop();
8626     if (isLoopEntryGuardedByCond(L, Pred, LAR->getStart(), RHS) &&
8627         isLoopBackedgeGuardedByCond(L, Pred, LAR->getPostIncExpr(*this), RHS)) {
8628       if (!RAR) return true;
8629       LeftGuarded = true;
8630     }
8631   }
8632   if (RAR) {
8633     const Loop *L = RAR->getLoop();
8634     if (isLoopEntryGuardedByCond(L, Pred, LHS, RAR->getStart()) &&
8635         isLoopBackedgeGuardedByCond(L, Pred, LHS, RAR->getPostIncExpr(*this))) {
8636       if (!LAR) return true;
8637       RightGuarded = true;
8638     }
8639   }
8640   if (LeftGuarded && RightGuarded)
8641     return true;
8642 
8643   if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
8644     return true;
8645 
8646   // Otherwise see what can be done with known constant ranges.
8647   return isKnownPredicateViaConstantRanges(Pred, LHS, RHS);
8648 }
8649 
8650 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS,
8651                                            ICmpInst::Predicate Pred,
8652                                            bool &Increasing) {
8653   bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing);
8654 
8655 #ifndef NDEBUG
8656   // Verify an invariant: inverting the predicate should turn a monotonically
8657   // increasing change to a monotonically decreasing one, and vice versa.
8658   bool IncreasingSwapped;
8659   bool ResultSwapped = isMonotonicPredicateImpl(
8660       LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped);
8661 
8662   assert(Result == ResultSwapped && "should be able to analyze both!");
8663   if (ResultSwapped)
8664     assert(Increasing == !IncreasingSwapped &&
8665            "monotonicity should flip as we flip the predicate");
8666 #endif
8667 
8668   return Result;
8669 }
8670 
8671 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS,
8672                                                ICmpInst::Predicate Pred,
8673                                                bool &Increasing) {
8674 
8675   // A zero step value for LHS means the induction variable is essentially a
8676   // loop invariant value. We don't really depend on the predicate actually
8677   // flipping from false to true (for increasing predicates, and the other way
8678   // around for decreasing predicates), all we care about is that *if* the
8679   // predicate changes then it only changes from false to true.
8680   //
8681   // A zero step value in itself is not very useful, but there may be places
8682   // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
8683   // as general as possible.
8684 
8685   switch (Pred) {
8686   default:
8687     return false; // Conservative answer
8688 
8689   case ICmpInst::ICMP_UGT:
8690   case ICmpInst::ICMP_UGE:
8691   case ICmpInst::ICMP_ULT:
8692   case ICmpInst::ICMP_ULE:
8693     if (!LHS->hasNoUnsignedWrap())
8694       return false;
8695 
8696     Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE;
8697     return true;
8698 
8699   case ICmpInst::ICMP_SGT:
8700   case ICmpInst::ICMP_SGE:
8701   case ICmpInst::ICMP_SLT:
8702   case ICmpInst::ICMP_SLE: {
8703     if (!LHS->hasNoSignedWrap())
8704       return false;
8705 
8706     const SCEV *Step = LHS->getStepRecurrence(*this);
8707 
8708     if (isKnownNonNegative(Step)) {
8709       Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE;
8710       return true;
8711     }
8712 
8713     if (isKnownNonPositive(Step)) {
8714       Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE;
8715       return true;
8716     }
8717 
8718     return false;
8719   }
8720 
8721   }
8722 
8723   llvm_unreachable("switch has default clause!");
8724 }
8725 
8726 bool ScalarEvolution::isLoopInvariantPredicate(
8727     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
8728     ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS,
8729     const SCEV *&InvariantRHS) {
8730 
8731   // If there is a loop-invariant, force it into the RHS, otherwise bail out.
8732   if (!isLoopInvariant(RHS, L)) {
8733     if (!isLoopInvariant(LHS, L))
8734       return false;
8735 
8736     std::swap(LHS, RHS);
8737     Pred = ICmpInst::getSwappedPredicate(Pred);
8738   }
8739 
8740   const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
8741   if (!ArLHS || ArLHS->getLoop() != L)
8742     return false;
8743 
8744   bool Increasing;
8745   if (!isMonotonicPredicate(ArLHS, Pred, Increasing))
8746     return false;
8747 
8748   // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
8749   // true as the loop iterates, and the backedge is control dependent on
8750   // "ArLHS `Pred` RHS" == true then we can reason as follows:
8751   //
8752   //   * if the predicate was false in the first iteration then the predicate
8753   //     is never evaluated again, since the loop exits without taking the
8754   //     backedge.
8755   //   * if the predicate was true in the first iteration then it will
8756   //     continue to be true for all future iterations since it is
8757   //     monotonically increasing.
8758   //
8759   // For both the above possibilities, we can replace the loop varying
8760   // predicate with its value on the first iteration of the loop (which is
8761   // loop invariant).
8762   //
8763   // A similar reasoning applies for a monotonically decreasing predicate, by
8764   // replacing true with false and false with true in the above two bullets.
8765 
8766   auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
8767 
8768   if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
8769     return false;
8770 
8771   InvariantPred = Pred;
8772   InvariantLHS = ArLHS->getStart();
8773   InvariantRHS = RHS;
8774   return true;
8775 }
8776 
8777 bool ScalarEvolution::isKnownPredicateViaConstantRanges(
8778     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
8779   if (HasSameValue(LHS, RHS))
8780     return ICmpInst::isTrueWhenEqual(Pred);
8781 
8782   // This code is split out from isKnownPredicate because it is called from
8783   // within isLoopEntryGuardedByCond.
8784 
8785   auto CheckRanges =
8786       [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) {
8787     return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS)
8788         .contains(RangeLHS);
8789   };
8790 
8791   // The check at the top of the function catches the case where the values are
8792   // known to be equal.
8793   if (Pred == CmpInst::ICMP_EQ)
8794     return false;
8795 
8796   if (Pred == CmpInst::ICMP_NE)
8797     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) ||
8798            CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) ||
8799            isKnownNonZero(getMinusSCEV(LHS, RHS));
8800 
8801   if (CmpInst::isSigned(Pred))
8802     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS));
8803 
8804   return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS));
8805 }
8806 
8807 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
8808                                                     const SCEV *LHS,
8809                                                     const SCEV *RHS) {
8810   // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer.
8811   // Return Y via OutY.
8812   auto MatchBinaryAddToConst =
8813       [this](const SCEV *Result, const SCEV *X, APInt &OutY,
8814              SCEV::NoWrapFlags ExpectedFlags) {
8815     const SCEV *NonConstOp, *ConstOp;
8816     SCEV::NoWrapFlags FlagsPresent;
8817 
8818     if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) ||
8819         !isa<SCEVConstant>(ConstOp) || NonConstOp != X)
8820       return false;
8821 
8822     OutY = cast<SCEVConstant>(ConstOp)->getAPInt();
8823     return (FlagsPresent & ExpectedFlags) == ExpectedFlags;
8824   };
8825 
8826   APInt C;
8827 
8828   switch (Pred) {
8829   default:
8830     break;
8831 
8832   case ICmpInst::ICMP_SGE:
8833     std::swap(LHS, RHS);
8834     LLVM_FALLTHROUGH;
8835   case ICmpInst::ICMP_SLE:
8836     // X s<= (X + C)<nsw> if C >= 0
8837     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative())
8838       return true;
8839 
8840     // (X + C)<nsw> s<= X if C <= 0
8841     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) &&
8842         !C.isStrictlyPositive())
8843       return true;
8844     break;
8845 
8846   case ICmpInst::ICMP_SGT:
8847     std::swap(LHS, RHS);
8848     LLVM_FALLTHROUGH;
8849   case ICmpInst::ICMP_SLT:
8850     // X s< (X + C)<nsw> if C > 0
8851     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) &&
8852         C.isStrictlyPositive())
8853       return true;
8854 
8855     // (X + C)<nsw> s< X if C < 0
8856     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative())
8857       return true;
8858     break;
8859   }
8860 
8861   return false;
8862 }
8863 
8864 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
8865                                                    const SCEV *LHS,
8866                                                    const SCEV *RHS) {
8867   if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
8868     return false;
8869 
8870   // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
8871   // the stack can result in exponential time complexity.
8872   SaveAndRestore<bool> Restore(ProvingSplitPredicate, true);
8873 
8874   // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
8875   //
8876   // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
8877   // isKnownPredicate.  isKnownPredicate is more powerful, but also more
8878   // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
8879   // interesting cases seen in practice.  We can consider "upgrading" L >= 0 to
8880   // use isKnownPredicate later if needed.
8881   return isKnownNonNegative(RHS) &&
8882          isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
8883          isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
8884 }
8885 
8886 bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB,
8887                                         ICmpInst::Predicate Pred,
8888                                         const SCEV *LHS, const SCEV *RHS) {
8889   // No need to even try if we know the module has no guards.
8890   if (!HasGuards)
8891     return false;
8892 
8893   return any_of(*BB, [&](Instruction &I) {
8894     using namespace llvm::PatternMatch;
8895 
8896     Value *Condition;
8897     return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
8898                          m_Value(Condition))) &&
8899            isImpliedCond(Pred, LHS, RHS, Condition, false);
8900   });
8901 }
8902 
8903 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
8904 /// protected by a conditional between LHS and RHS.  This is used to
8905 /// to eliminate casts.
8906 bool
8907 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
8908                                              ICmpInst::Predicate Pred,
8909                                              const SCEV *LHS, const SCEV *RHS) {
8910   // Interpret a null as meaning no loop, where there is obviously no guard
8911   // (interprocedural conditions notwithstanding).
8912   if (!L) return true;
8913 
8914   if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS))
8915     return true;
8916 
8917   BasicBlock *Latch = L->getLoopLatch();
8918   if (!Latch)
8919     return false;
8920 
8921   BranchInst *LoopContinuePredicate =
8922     dyn_cast<BranchInst>(Latch->getTerminator());
8923   if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
8924       isImpliedCond(Pred, LHS, RHS,
8925                     LoopContinuePredicate->getCondition(),
8926                     LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
8927     return true;
8928 
8929   // We don't want more than one activation of the following loops on the stack
8930   // -- that can lead to O(n!) time complexity.
8931   if (WalkingBEDominatingConds)
8932     return false;
8933 
8934   SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true);
8935 
8936   // See if we can exploit a trip count to prove the predicate.
8937   const auto &BETakenInfo = getBackedgeTakenInfo(L);
8938   const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
8939   if (LatchBECount != getCouldNotCompute()) {
8940     // We know that Latch branches back to the loop header exactly
8941     // LatchBECount times.  This means the backdege condition at Latch is
8942     // equivalent to  "{0,+,1} u< LatchBECount".
8943     Type *Ty = LatchBECount->getType();
8944     auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
8945     const SCEV *LoopCounter =
8946       getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
8947     if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
8948                       LatchBECount))
8949       return true;
8950   }
8951 
8952   // Check conditions due to any @llvm.assume intrinsics.
8953   for (auto &AssumeVH : AC.assumptions()) {
8954     if (!AssumeVH)
8955       continue;
8956     auto *CI = cast<CallInst>(AssumeVH);
8957     if (!DT.dominates(CI, Latch->getTerminator()))
8958       continue;
8959 
8960     if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
8961       return true;
8962   }
8963 
8964   // If the loop is not reachable from the entry block, we risk running into an
8965   // infinite loop as we walk up into the dom tree.  These loops do not matter
8966   // anyway, so we just return a conservative answer when we see them.
8967   if (!DT.isReachableFromEntry(L->getHeader()))
8968     return false;
8969 
8970   if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
8971     return true;
8972 
8973   for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
8974        DTN != HeaderDTN; DTN = DTN->getIDom()) {
8975     assert(DTN && "should reach the loop header before reaching the root!");
8976 
8977     BasicBlock *BB = DTN->getBlock();
8978     if (isImpliedViaGuard(BB, Pred, LHS, RHS))
8979       return true;
8980 
8981     BasicBlock *PBB = BB->getSinglePredecessor();
8982     if (!PBB)
8983       continue;
8984 
8985     BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
8986     if (!ContinuePredicate || !ContinuePredicate->isConditional())
8987       continue;
8988 
8989     Value *Condition = ContinuePredicate->getCondition();
8990 
8991     // If we have an edge `E` within the loop body that dominates the only
8992     // latch, the condition guarding `E` also guards the backedge.  This
8993     // reasoning works only for loops with a single latch.
8994 
8995     BasicBlockEdge DominatingEdge(PBB, BB);
8996     if (DominatingEdge.isSingleEdge()) {
8997       // We're constructively (and conservatively) enumerating edges within the
8998       // loop body that dominate the latch.  The dominator tree better agree
8999       // with us on this:
9000       assert(DT.dominates(DominatingEdge, Latch) && "should be!");
9001 
9002       if (isImpliedCond(Pred, LHS, RHS, Condition,
9003                         BB != ContinuePredicate->getSuccessor(0)))
9004         return true;
9005     }
9006   }
9007 
9008   return false;
9009 }
9010 
9011 bool
9012 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
9013                                           ICmpInst::Predicate Pred,
9014                                           const SCEV *LHS, const SCEV *RHS) {
9015   // Interpret a null as meaning no loop, where there is obviously no guard
9016   // (interprocedural conditions notwithstanding).
9017   if (!L) return false;
9018 
9019   if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS))
9020     return true;
9021 
9022   // Starting at the loop predecessor, climb up the predecessor chain, as long
9023   // as there are predecessors that can be found that have unique successors
9024   // leading to the original header.
9025   for (std::pair<BasicBlock *, BasicBlock *>
9026          Pair(L->getLoopPredecessor(), L->getHeader());
9027        Pair.first;
9028        Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
9029 
9030     if (isImpliedViaGuard(Pair.first, Pred, LHS, RHS))
9031       return true;
9032 
9033     BranchInst *LoopEntryPredicate =
9034       dyn_cast<BranchInst>(Pair.first->getTerminator());
9035     if (!LoopEntryPredicate ||
9036         LoopEntryPredicate->isUnconditional())
9037       continue;
9038 
9039     if (isImpliedCond(Pred, LHS, RHS,
9040                       LoopEntryPredicate->getCondition(),
9041                       LoopEntryPredicate->getSuccessor(0) != Pair.second))
9042       return true;
9043   }
9044 
9045   // Check conditions due to any @llvm.assume intrinsics.
9046   for (auto &AssumeVH : AC.assumptions()) {
9047     if (!AssumeVH)
9048       continue;
9049     auto *CI = cast<CallInst>(AssumeVH);
9050     if (!DT.dominates(CI, L->getHeader()))
9051       continue;
9052 
9053     if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
9054       return true;
9055   }
9056 
9057   return false;
9058 }
9059 
9060 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
9061                                     const SCEV *LHS, const SCEV *RHS,
9062                                     Value *FoundCondValue,
9063                                     bool Inverse) {
9064   if (!PendingLoopPredicates.insert(FoundCondValue).second)
9065     return false;
9066 
9067   auto ClearOnExit =
9068       make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
9069 
9070   // Recursively handle And and Or conditions.
9071   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
9072     if (BO->getOpcode() == Instruction::And) {
9073       if (!Inverse)
9074         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
9075                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
9076     } else if (BO->getOpcode() == Instruction::Or) {
9077       if (Inverse)
9078         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
9079                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
9080     }
9081   }
9082 
9083   ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
9084   if (!ICI) return false;
9085 
9086   // Now that we found a conditional branch that dominates the loop or controls
9087   // the loop latch. Check to see if it is the comparison we are looking for.
9088   ICmpInst::Predicate FoundPred;
9089   if (Inverse)
9090     FoundPred = ICI->getInversePredicate();
9091   else
9092     FoundPred = ICI->getPredicate();
9093 
9094   const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
9095   const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
9096 
9097   return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS);
9098 }
9099 
9100 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
9101                                     const SCEV *RHS,
9102                                     ICmpInst::Predicate FoundPred,
9103                                     const SCEV *FoundLHS,
9104                                     const SCEV *FoundRHS) {
9105   // Balance the types.
9106   if (getTypeSizeInBits(LHS->getType()) <
9107       getTypeSizeInBits(FoundLHS->getType())) {
9108     if (CmpInst::isSigned(Pred)) {
9109       LHS = getSignExtendExpr(LHS, FoundLHS->getType());
9110       RHS = getSignExtendExpr(RHS, FoundLHS->getType());
9111     } else {
9112       LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
9113       RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
9114     }
9115   } else if (getTypeSizeInBits(LHS->getType()) >
9116       getTypeSizeInBits(FoundLHS->getType())) {
9117     if (CmpInst::isSigned(FoundPred)) {
9118       FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
9119       FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
9120     } else {
9121       FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
9122       FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
9123     }
9124   }
9125 
9126   // Canonicalize the query to match the way instcombine will have
9127   // canonicalized the comparison.
9128   if (SimplifyICmpOperands(Pred, LHS, RHS))
9129     if (LHS == RHS)
9130       return CmpInst::isTrueWhenEqual(Pred);
9131   if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
9132     if (FoundLHS == FoundRHS)
9133       return CmpInst::isFalseWhenEqual(FoundPred);
9134 
9135   // Check to see if we can make the LHS or RHS match.
9136   if (LHS == FoundRHS || RHS == FoundLHS) {
9137     if (isa<SCEVConstant>(RHS)) {
9138       std::swap(FoundLHS, FoundRHS);
9139       FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
9140     } else {
9141       std::swap(LHS, RHS);
9142       Pred = ICmpInst::getSwappedPredicate(Pred);
9143     }
9144   }
9145 
9146   // Check whether the found predicate is the same as the desired predicate.
9147   if (FoundPred == Pred)
9148     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
9149 
9150   // Check whether swapping the found predicate makes it the same as the
9151   // desired predicate.
9152   if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
9153     if (isa<SCEVConstant>(RHS))
9154       return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
9155     else
9156       return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
9157                                    RHS, LHS, FoundLHS, FoundRHS);
9158   }
9159 
9160   // Unsigned comparison is the same as signed comparison when both the operands
9161   // are non-negative.
9162   if (CmpInst::isUnsigned(FoundPred) &&
9163       CmpInst::getSignedPredicate(FoundPred) == Pred &&
9164       isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS))
9165     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
9166 
9167   // Check if we can make progress by sharpening ranges.
9168   if (FoundPred == ICmpInst::ICMP_NE &&
9169       (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
9170 
9171     const SCEVConstant *C = nullptr;
9172     const SCEV *V = nullptr;
9173 
9174     if (isa<SCEVConstant>(FoundLHS)) {
9175       C = cast<SCEVConstant>(FoundLHS);
9176       V = FoundRHS;
9177     } else {
9178       C = cast<SCEVConstant>(FoundRHS);
9179       V = FoundLHS;
9180     }
9181 
9182     // The guarding predicate tells us that C != V. If the known range
9183     // of V is [C, t), we can sharpen the range to [C + 1, t).  The
9184     // range we consider has to correspond to same signedness as the
9185     // predicate we're interested in folding.
9186 
9187     APInt Min = ICmpInst::isSigned(Pred) ?
9188         getSignedRangeMin(V) : getUnsignedRangeMin(V);
9189 
9190     if (Min == C->getAPInt()) {
9191       // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
9192       // This is true even if (Min + 1) wraps around -- in case of
9193       // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
9194 
9195       APInt SharperMin = Min + 1;
9196 
9197       switch (Pred) {
9198         case ICmpInst::ICMP_SGE:
9199         case ICmpInst::ICMP_UGE:
9200           // We know V `Pred` SharperMin.  If this implies LHS `Pred`
9201           // RHS, we're done.
9202           if (isImpliedCondOperands(Pred, LHS, RHS, V,
9203                                     getConstant(SharperMin)))
9204             return true;
9205           LLVM_FALLTHROUGH;
9206 
9207         case ICmpInst::ICMP_SGT:
9208         case ICmpInst::ICMP_UGT:
9209           // We know from the range information that (V `Pred` Min ||
9210           // V == Min).  We know from the guarding condition that !(V
9211           // == Min).  This gives us
9212           //
9213           //       V `Pred` Min || V == Min && !(V == Min)
9214           //   =>  V `Pred` Min
9215           //
9216           // If V `Pred` Min implies LHS `Pred` RHS, we're done.
9217 
9218           if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min)))
9219             return true;
9220           LLVM_FALLTHROUGH;
9221 
9222         default:
9223           // No change
9224           break;
9225       }
9226     }
9227   }
9228 
9229   // Check whether the actual condition is beyond sufficient.
9230   if (FoundPred == ICmpInst::ICMP_EQ)
9231     if (ICmpInst::isTrueWhenEqual(Pred))
9232       if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
9233         return true;
9234   if (Pred == ICmpInst::ICMP_NE)
9235     if (!ICmpInst::isTrueWhenEqual(FoundPred))
9236       if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
9237         return true;
9238 
9239   // Otherwise assume the worst.
9240   return false;
9241 }
9242 
9243 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
9244                                      const SCEV *&L, const SCEV *&R,
9245                                      SCEV::NoWrapFlags &Flags) {
9246   const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
9247   if (!AE || AE->getNumOperands() != 2)
9248     return false;
9249 
9250   L = AE->getOperand(0);
9251   R = AE->getOperand(1);
9252   Flags = AE->getNoWrapFlags();
9253   return true;
9254 }
9255 
9256 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More,
9257                                                            const SCEV *Less) {
9258   // We avoid subtracting expressions here because this function is usually
9259   // fairly deep in the call stack (i.e. is called many times).
9260 
9261   if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
9262     const auto *LAR = cast<SCEVAddRecExpr>(Less);
9263     const auto *MAR = cast<SCEVAddRecExpr>(More);
9264 
9265     if (LAR->getLoop() != MAR->getLoop())
9266       return None;
9267 
9268     // We look at affine expressions only; not for correctness but to keep
9269     // getStepRecurrence cheap.
9270     if (!LAR->isAffine() || !MAR->isAffine())
9271       return None;
9272 
9273     if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
9274       return None;
9275 
9276     Less = LAR->getStart();
9277     More = MAR->getStart();
9278 
9279     // fall through
9280   }
9281 
9282   if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
9283     const auto &M = cast<SCEVConstant>(More)->getAPInt();
9284     const auto &L = cast<SCEVConstant>(Less)->getAPInt();
9285     return M - L;
9286   }
9287 
9288   const SCEV *L, *R;
9289   SCEV::NoWrapFlags Flags;
9290   if (splitBinaryAdd(Less, L, R, Flags))
9291     if (const auto *LC = dyn_cast<SCEVConstant>(L))
9292       if (R == More)
9293         return -(LC->getAPInt());
9294 
9295   if (splitBinaryAdd(More, L, R, Flags))
9296     if (const auto *LC = dyn_cast<SCEVConstant>(L))
9297       if (R == Less)
9298         return LC->getAPInt();
9299 
9300   return None;
9301 }
9302 
9303 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
9304     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
9305     const SCEV *FoundLHS, const SCEV *FoundRHS) {
9306   if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
9307     return false;
9308 
9309   const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
9310   if (!AddRecLHS)
9311     return false;
9312 
9313   const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
9314   if (!AddRecFoundLHS)
9315     return false;
9316 
9317   // We'd like to let SCEV reason about control dependencies, so we constrain
9318   // both the inequalities to be about add recurrences on the same loop.  This
9319   // way we can use isLoopEntryGuardedByCond later.
9320 
9321   const Loop *L = AddRecFoundLHS->getLoop();
9322   if (L != AddRecLHS->getLoop())
9323     return false;
9324 
9325   //  FoundLHS u< FoundRHS u< -C =>  (FoundLHS + C) u< (FoundRHS + C) ... (1)
9326   //
9327   //  FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
9328   //                                                                  ... (2)
9329   //
9330   // Informal proof for (2), assuming (1) [*]:
9331   //
9332   // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
9333   //
9334   // Then
9335   //
9336   //       FoundLHS s< FoundRHS s< INT_MIN - C
9337   // <=>  (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C   [ using (3) ]
9338   // <=>  (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
9339   // <=>  (FoundLHS + INT_MIN + C + INT_MIN) s<
9340   //                        (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
9341   // <=>  FoundLHS + C s< FoundRHS + C
9342   //
9343   // [*]: (1) can be proved by ruling out overflow.
9344   //
9345   // [**]: This can be proved by analyzing all the four possibilities:
9346   //    (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
9347   //    (A s>= 0, B s>= 0).
9348   //
9349   // Note:
9350   // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
9351   // will not sign underflow.  For instance, say FoundLHS = (i8 -128), FoundRHS
9352   // = (i8 -127) and C = (i8 -100).  Then INT_MIN - C = (i8 -28), and FoundRHS
9353   // s< (INT_MIN - C).  Lack of sign overflow / underflow in "FoundRHS + C" is
9354   // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
9355   // C)".
9356 
9357   Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
9358   Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
9359   if (!LDiff || !RDiff || *LDiff != *RDiff)
9360     return false;
9361 
9362   if (LDiff->isMinValue())
9363     return true;
9364 
9365   APInt FoundRHSLimit;
9366 
9367   if (Pred == CmpInst::ICMP_ULT) {
9368     FoundRHSLimit = -(*RDiff);
9369   } else {
9370     assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
9371     FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
9372   }
9373 
9374   // Try to prove (1) or (2), as needed.
9375   return isLoopEntryGuardedByCond(L, Pred, FoundRHS,
9376                                   getConstant(FoundRHSLimit));
9377 }
9378 
9379 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
9380                                             const SCEV *LHS, const SCEV *RHS,
9381                                             const SCEV *FoundLHS,
9382                                             const SCEV *FoundRHS) {
9383   if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
9384     return true;
9385 
9386   if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
9387     return true;
9388 
9389   return isImpliedCondOperandsHelper(Pred, LHS, RHS,
9390                                      FoundLHS, FoundRHS) ||
9391          // ~x < ~y --> x > y
9392          isImpliedCondOperandsHelper(Pred, LHS, RHS,
9393                                      getNotSCEV(FoundRHS),
9394                                      getNotSCEV(FoundLHS));
9395 }
9396 
9397 /// If Expr computes ~A, return A else return nullptr
9398 static const SCEV *MatchNotExpr(const SCEV *Expr) {
9399   const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
9400   if (!Add || Add->getNumOperands() != 2 ||
9401       !Add->getOperand(0)->isAllOnesValue())
9402     return nullptr;
9403 
9404   const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
9405   if (!AddRHS || AddRHS->getNumOperands() != 2 ||
9406       !AddRHS->getOperand(0)->isAllOnesValue())
9407     return nullptr;
9408 
9409   return AddRHS->getOperand(1);
9410 }
9411 
9412 /// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values?
9413 template<typename MaxExprType>
9414 static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr,
9415                               const SCEV *Candidate) {
9416   const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr);
9417   if (!MaxExpr) return false;
9418 
9419   return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end();
9420 }
9421 
9422 /// Is MaybeMinExpr an SMin or UMin of Candidate and some other values?
9423 template<typename MaxExprType>
9424 static bool IsMinConsistingOf(ScalarEvolution &SE,
9425                               const SCEV *MaybeMinExpr,
9426                               const SCEV *Candidate) {
9427   const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr);
9428   if (!MaybeMaxExpr)
9429     return false;
9430 
9431   return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate));
9432 }
9433 
9434 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
9435                                            ICmpInst::Predicate Pred,
9436                                            const SCEV *LHS, const SCEV *RHS) {
9437   // If both sides are affine addrecs for the same loop, with equal
9438   // steps, and we know the recurrences don't wrap, then we only
9439   // need to check the predicate on the starting values.
9440 
9441   if (!ICmpInst::isRelational(Pred))
9442     return false;
9443 
9444   const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
9445   if (!LAR)
9446     return false;
9447   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
9448   if (!RAR)
9449     return false;
9450   if (LAR->getLoop() != RAR->getLoop())
9451     return false;
9452   if (!LAR->isAffine() || !RAR->isAffine())
9453     return false;
9454 
9455   if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
9456     return false;
9457 
9458   SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
9459                          SCEV::FlagNSW : SCEV::FlagNUW;
9460   if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
9461     return false;
9462 
9463   return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
9464 }
9465 
9466 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
9467 /// expression?
9468 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
9469                                         ICmpInst::Predicate Pred,
9470                                         const SCEV *LHS, const SCEV *RHS) {
9471   switch (Pred) {
9472   default:
9473     return false;
9474 
9475   case ICmpInst::ICMP_SGE:
9476     std::swap(LHS, RHS);
9477     LLVM_FALLTHROUGH;
9478   case ICmpInst::ICMP_SLE:
9479     return
9480       // min(A, ...) <= A
9481       IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) ||
9482       // A <= max(A, ...)
9483       IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
9484 
9485   case ICmpInst::ICMP_UGE:
9486     std::swap(LHS, RHS);
9487     LLVM_FALLTHROUGH;
9488   case ICmpInst::ICMP_ULE:
9489     return
9490       // min(A, ...) <= A
9491       IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) ||
9492       // A <= max(A, ...)
9493       IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
9494   }
9495 
9496   llvm_unreachable("covered switch fell through?!");
9497 }
9498 
9499 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred,
9500                                              const SCEV *LHS, const SCEV *RHS,
9501                                              const SCEV *FoundLHS,
9502                                              const SCEV *FoundRHS,
9503                                              unsigned Depth) {
9504   assert(getTypeSizeInBits(LHS->getType()) ==
9505              getTypeSizeInBits(RHS->getType()) &&
9506          "LHS and RHS have different sizes?");
9507   assert(getTypeSizeInBits(FoundLHS->getType()) ==
9508              getTypeSizeInBits(FoundRHS->getType()) &&
9509          "FoundLHS and FoundRHS have different sizes?");
9510   // We want to avoid hurting the compile time with analysis of too big trees.
9511   if (Depth > MaxSCEVOperationsImplicationDepth)
9512     return false;
9513   // We only want to work with ICMP_SGT comparison so far.
9514   // TODO: Extend to ICMP_UGT?
9515   if (Pred == ICmpInst::ICMP_SLT) {
9516     Pred = ICmpInst::ICMP_SGT;
9517     std::swap(LHS, RHS);
9518     std::swap(FoundLHS, FoundRHS);
9519   }
9520   if (Pred != ICmpInst::ICMP_SGT)
9521     return false;
9522 
9523   auto GetOpFromSExt = [&](const SCEV *S) {
9524     if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
9525       return Ext->getOperand();
9526     // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
9527     // the constant in some cases.
9528     return S;
9529   };
9530 
9531   // Acquire values from extensions.
9532   auto *OrigFoundLHS = FoundLHS;
9533   LHS = GetOpFromSExt(LHS);
9534   FoundLHS = GetOpFromSExt(FoundLHS);
9535 
9536   // Is the SGT predicate can be proved trivially or using the found context.
9537   auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
9538     return isKnownViaSimpleReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
9539            isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
9540                                   FoundRHS, Depth + 1);
9541   };
9542 
9543   if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
9544     // We want to avoid creation of any new non-constant SCEV. Since we are
9545     // going to compare the operands to RHS, we should be certain that we don't
9546     // need any size extensions for this. So let's decline all cases when the
9547     // sizes of types of LHS and RHS do not match.
9548     // TODO: Maybe try to get RHS from sext to catch more cases?
9549     if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType()))
9550       return false;
9551 
9552     // Should not overflow.
9553     if (!LHSAddExpr->hasNoSignedWrap())
9554       return false;
9555 
9556     auto *LL = LHSAddExpr->getOperand(0);
9557     auto *LR = LHSAddExpr->getOperand(1);
9558     auto *MinusOne = getNegativeSCEV(getOne(RHS->getType()));
9559 
9560     // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
9561     auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
9562       return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
9563     };
9564     // Try to prove the following rule:
9565     // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
9566     // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
9567     if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
9568       return true;
9569   } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
9570     Value *LL, *LR;
9571     // FIXME: Once we have SDiv implemented, we can get rid of this matching.
9572 
9573     using namespace llvm::PatternMatch;
9574 
9575     if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
9576       // Rules for division.
9577       // We are going to perform some comparisons with Denominator and its
9578       // derivative expressions. In general case, creating a SCEV for it may
9579       // lead to a complex analysis of the entire graph, and in particular it
9580       // can request trip count recalculation for the same loop. This would
9581       // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
9582       // this, we only want to create SCEVs that are constants in this section.
9583       // So we bail if Denominator is not a constant.
9584       if (!isa<ConstantInt>(LR))
9585         return false;
9586 
9587       auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
9588 
9589       // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
9590       // then a SCEV for the numerator already exists and matches with FoundLHS.
9591       auto *Numerator = getExistingSCEV(LL);
9592       if (!Numerator || Numerator->getType() != FoundLHS->getType())
9593         return false;
9594 
9595       // Make sure that the numerator matches with FoundLHS and the denominator
9596       // is positive.
9597       if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
9598         return false;
9599 
9600       auto *DTy = Denominator->getType();
9601       auto *FRHSTy = FoundRHS->getType();
9602       if (DTy->isPointerTy() != FRHSTy->isPointerTy())
9603         // One of types is a pointer and another one is not. We cannot extend
9604         // them properly to a wider type, so let us just reject this case.
9605         // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
9606         // to avoid this check.
9607         return false;
9608 
9609       // Given that:
9610       // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
9611       auto *WTy = getWiderType(DTy, FRHSTy);
9612       auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
9613       auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
9614 
9615       // Try to prove the following rule:
9616       // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
9617       // For example, given that FoundLHS > 2. It means that FoundLHS is at
9618       // least 3. If we divide it by Denominator < 4, we will have at least 1.
9619       auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
9620       if (isKnownNonPositive(RHS) &&
9621           IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
9622         return true;
9623 
9624       // Try to prove the following rule:
9625       // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
9626       // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
9627       // If we divide it by Denominator > 2, then:
9628       // 1. If FoundLHS is negative, then the result is 0.
9629       // 2. If FoundLHS is non-negative, then the result is non-negative.
9630       // Anyways, the result is non-negative.
9631       auto *MinusOne = getNegativeSCEV(getOne(WTy));
9632       auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
9633       if (isKnownNegative(RHS) &&
9634           IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
9635         return true;
9636     }
9637   }
9638 
9639   return false;
9640 }
9641 
9642 bool
9643 ScalarEvolution::isKnownViaSimpleReasoning(ICmpInst::Predicate Pred,
9644                                            const SCEV *LHS, const SCEV *RHS) {
9645   return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
9646          IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
9647          IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
9648          isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
9649 }
9650 
9651 bool
9652 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
9653                                              const SCEV *LHS, const SCEV *RHS,
9654                                              const SCEV *FoundLHS,
9655                                              const SCEV *FoundRHS) {
9656   switch (Pred) {
9657   default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
9658   case ICmpInst::ICMP_EQ:
9659   case ICmpInst::ICMP_NE:
9660     if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
9661       return true;
9662     break;
9663   case ICmpInst::ICMP_SLT:
9664   case ICmpInst::ICMP_SLE:
9665     if (isKnownViaSimpleReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
9666         isKnownViaSimpleReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS))
9667       return true;
9668     break;
9669   case ICmpInst::ICMP_SGT:
9670   case ICmpInst::ICMP_SGE:
9671     if (isKnownViaSimpleReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
9672         isKnownViaSimpleReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS))
9673       return true;
9674     break;
9675   case ICmpInst::ICMP_ULT:
9676   case ICmpInst::ICMP_ULE:
9677     if (isKnownViaSimpleReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
9678         isKnownViaSimpleReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS))
9679       return true;
9680     break;
9681   case ICmpInst::ICMP_UGT:
9682   case ICmpInst::ICMP_UGE:
9683     if (isKnownViaSimpleReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
9684         isKnownViaSimpleReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS))
9685       return true;
9686     break;
9687   }
9688 
9689   // Maybe it can be proved via operations?
9690   if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
9691     return true;
9692 
9693   return false;
9694 }
9695 
9696 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
9697                                                      const SCEV *LHS,
9698                                                      const SCEV *RHS,
9699                                                      const SCEV *FoundLHS,
9700                                                      const SCEV *FoundRHS) {
9701   if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
9702     // The restriction on `FoundRHS` be lifted easily -- it exists only to
9703     // reduce the compile time impact of this optimization.
9704     return false;
9705 
9706   Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
9707   if (!Addend)
9708     return false;
9709 
9710   const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
9711 
9712   // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
9713   // antecedent "`FoundLHS` `Pred` `FoundRHS`".
9714   ConstantRange FoundLHSRange =
9715       ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS);
9716 
9717   // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
9718   ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
9719 
9720   // We can also compute the range of values for `LHS` that satisfy the
9721   // consequent, "`LHS` `Pred` `RHS`":
9722   const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
9723   ConstantRange SatisfyingLHSRange =
9724       ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS);
9725 
9726   // The antecedent implies the consequent if every value of `LHS` that
9727   // satisfies the antecedent also satisfies the consequent.
9728   return SatisfyingLHSRange.contains(LHSRange);
9729 }
9730 
9731 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
9732                                          bool IsSigned, bool NoWrap) {
9733   assert(isKnownPositive(Stride) && "Positive stride expected!");
9734 
9735   if (NoWrap) return false;
9736 
9737   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
9738   const SCEV *One = getOne(Stride->getType());
9739 
9740   if (IsSigned) {
9741     APInt MaxRHS = getSignedRangeMax(RHS);
9742     APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
9743     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
9744 
9745     // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
9746     return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS);
9747   }
9748 
9749   APInt MaxRHS = getUnsignedRangeMax(RHS);
9750   APInt MaxValue = APInt::getMaxValue(BitWidth);
9751   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
9752 
9753   // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
9754   return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS);
9755 }
9756 
9757 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
9758                                          bool IsSigned, bool NoWrap) {
9759   if (NoWrap) return false;
9760 
9761   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
9762   const SCEV *One = getOne(Stride->getType());
9763 
9764   if (IsSigned) {
9765     APInt MinRHS = getSignedRangeMin(RHS);
9766     APInt MinValue = APInt::getSignedMinValue(BitWidth);
9767     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
9768 
9769     // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
9770     return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS);
9771   }
9772 
9773   APInt MinRHS = getUnsignedRangeMin(RHS);
9774   APInt MinValue = APInt::getMinValue(BitWidth);
9775   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
9776 
9777   // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
9778   return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS);
9779 }
9780 
9781 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step,
9782                                             bool Equality) {
9783   const SCEV *One = getOne(Step->getType());
9784   Delta = Equality ? getAddExpr(Delta, Step)
9785                    : getAddExpr(Delta, getMinusSCEV(Step, One));
9786   return getUDivExpr(Delta, Step);
9787 }
9788 
9789 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start,
9790                                                     const SCEV *Stride,
9791                                                     const SCEV *End,
9792                                                     unsigned BitWidth,
9793                                                     bool IsSigned) {
9794 
9795   assert(!isKnownNonPositive(Stride) &&
9796          "Stride is expected strictly positive!");
9797   // Calculate the maximum backedge count based on the range of values
9798   // permitted by Start, End, and Stride.
9799   const SCEV *MaxBECount;
9800   APInt MinStart =
9801       IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start);
9802 
9803   APInt StrideForMaxBECount =
9804       IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride);
9805 
9806   // We already know that the stride is positive, so we paper over conservatism
9807   // in our range computation by forcing StrideForMaxBECount to be at least one.
9808   // In theory this is unnecessary, but we expect MaxBECount to be a
9809   // SCEVConstant, and (udiv <constant> 0) is not constant folded by SCEV (there
9810   // is nothing to constant fold it to).
9811   APInt One(BitWidth, 1, IsSigned);
9812   StrideForMaxBECount = APIntOps::smax(One, StrideForMaxBECount);
9813 
9814   APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth)
9815                             : APInt::getMaxValue(BitWidth);
9816   APInt Limit = MaxValue - (StrideForMaxBECount - 1);
9817 
9818   // Although End can be a MAX expression we estimate MaxEnd considering only
9819   // the case End = RHS of the loop termination condition. This is safe because
9820   // in the other case (End - Start) is zero, leading to a zero maximum backedge
9821   // taken count.
9822   APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit)
9823                           : APIntOps::umin(getUnsignedRangeMax(End), Limit);
9824 
9825   MaxBECount = computeBECount(getConstant(MaxEnd - MinStart) /* Delta */,
9826                               getConstant(StrideForMaxBECount) /* Step */,
9827                               false /* Equality */);
9828 
9829   return MaxBECount;
9830 }
9831 
9832 ScalarEvolution::ExitLimit
9833 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
9834                                   const Loop *L, bool IsSigned,
9835                                   bool ControlsExit, bool AllowPredicates) {
9836   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
9837 
9838   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
9839   bool PredicatedIV = false;
9840 
9841   if (!IV && AllowPredicates) {
9842     // Try to make this an AddRec using runtime tests, in the first X
9843     // iterations of this loop, where X is the SCEV expression found by the
9844     // algorithm below.
9845     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
9846     PredicatedIV = true;
9847   }
9848 
9849   // Avoid weird loops
9850   if (!IV || IV->getLoop() != L || !IV->isAffine())
9851     return getCouldNotCompute();
9852 
9853   bool NoWrap = ControlsExit &&
9854                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
9855 
9856   const SCEV *Stride = IV->getStepRecurrence(*this);
9857 
9858   bool PositiveStride = isKnownPositive(Stride);
9859 
9860   // Avoid negative or zero stride values.
9861   if (!PositiveStride) {
9862     // We can compute the correct backedge taken count for loops with unknown
9863     // strides if we can prove that the loop is not an infinite loop with side
9864     // effects. Here's the loop structure we are trying to handle -
9865     //
9866     // i = start
9867     // do {
9868     //   A[i] = i;
9869     //   i += s;
9870     // } while (i < end);
9871     //
9872     // The backedge taken count for such loops is evaluated as -
9873     // (max(end, start + stride) - start - 1) /u stride
9874     //
9875     // The additional preconditions that we need to check to prove correctness
9876     // of the above formula is as follows -
9877     //
9878     // a) IV is either nuw or nsw depending upon signedness (indicated by the
9879     //    NoWrap flag).
9880     // b) loop is single exit with no side effects.
9881     //
9882     //
9883     // Precondition a) implies that if the stride is negative, this is a single
9884     // trip loop. The backedge taken count formula reduces to zero in this case.
9885     //
9886     // Precondition b) implies that the unknown stride cannot be zero otherwise
9887     // we have UB.
9888     //
9889     // The positive stride case is the same as isKnownPositive(Stride) returning
9890     // true (original behavior of the function).
9891     //
9892     // We want to make sure that the stride is truly unknown as there are edge
9893     // cases where ScalarEvolution propagates no wrap flags to the
9894     // post-increment/decrement IV even though the increment/decrement operation
9895     // itself is wrapping. The computed backedge taken count may be wrong in
9896     // such cases. This is prevented by checking that the stride is not known to
9897     // be either positive or non-positive. For example, no wrap flags are
9898     // propagated to the post-increment IV of this loop with a trip count of 2 -
9899     //
9900     // unsigned char i;
9901     // for(i=127; i<128; i+=129)
9902     //   A[i] = i;
9903     //
9904     if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) ||
9905         !loopHasNoSideEffects(L))
9906       return getCouldNotCompute();
9907   } else if (!Stride->isOne() &&
9908              doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap))
9909     // Avoid proven overflow cases: this will ensure that the backedge taken
9910     // count will not generate any unsigned overflow. Relaxed no-overflow
9911     // conditions exploit NoWrapFlags, allowing to optimize in presence of
9912     // undefined behaviors like the case of C language.
9913     return getCouldNotCompute();
9914 
9915   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT
9916                                       : ICmpInst::ICMP_ULT;
9917   const SCEV *Start = IV->getStart();
9918   const SCEV *End = RHS;
9919   // When the RHS is not invariant, we do not know the end bound of the loop and
9920   // cannot calculate the ExactBECount needed by ExitLimit. However, we can
9921   // calculate the MaxBECount, given the start, stride and max value for the end
9922   // bound of the loop (RHS), and the fact that IV does not overflow (which is
9923   // checked above).
9924   if (!isLoopInvariant(RHS, L)) {
9925     const SCEV *MaxBECount = computeMaxBECountForLT(
9926         Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
9927     return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount,
9928                      false /*MaxOrZero*/, Predicates);
9929   }
9930   // If the backedge is taken at least once, then it will be taken
9931   // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start
9932   // is the LHS value of the less-than comparison the first time it is evaluated
9933   // and End is the RHS.
9934   const SCEV *BECountIfBackedgeTaken =
9935     computeBECount(getMinusSCEV(End, Start), Stride, false);
9936   // If the loop entry is guarded by the result of the backedge test of the
9937   // first loop iteration, then we know the backedge will be taken at least
9938   // once and so the backedge taken count is as above. If not then we use the
9939   // expression (max(End,Start)-Start)/Stride to describe the backedge count,
9940   // as if the backedge is taken at least once max(End,Start) is End and so the
9941   // result is as above, and if not max(End,Start) is Start so we get a backedge
9942   // count of zero.
9943   const SCEV *BECount;
9944   if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS))
9945     BECount = BECountIfBackedgeTaken;
9946   else {
9947     End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
9948     BECount = computeBECount(getMinusSCEV(End, Start), Stride, false);
9949   }
9950 
9951   const SCEV *MaxBECount;
9952   bool MaxOrZero = false;
9953   if (isa<SCEVConstant>(BECount))
9954     MaxBECount = BECount;
9955   else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) {
9956     // If we know exactly how many times the backedge will be taken if it's
9957     // taken at least once, then the backedge count will either be that or
9958     // zero.
9959     MaxBECount = BECountIfBackedgeTaken;
9960     MaxOrZero = true;
9961   } else {
9962     MaxBECount = computeMaxBECountForLT(
9963         Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
9964   }
9965 
9966   if (isa<SCEVCouldNotCompute>(MaxBECount) &&
9967       !isa<SCEVCouldNotCompute>(BECount))
9968     MaxBECount = getConstant(getUnsignedRangeMax(BECount));
9969 
9970   return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates);
9971 }
9972 
9973 ScalarEvolution::ExitLimit
9974 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
9975                                      const Loop *L, bool IsSigned,
9976                                      bool ControlsExit, bool AllowPredicates) {
9977   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
9978   // We handle only IV > Invariant
9979   if (!isLoopInvariant(RHS, L))
9980     return getCouldNotCompute();
9981 
9982   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
9983   if (!IV && AllowPredicates)
9984     // Try to make this an AddRec using runtime tests, in the first X
9985     // iterations of this loop, where X is the SCEV expression found by the
9986     // algorithm below.
9987     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
9988 
9989   // Avoid weird loops
9990   if (!IV || IV->getLoop() != L || !IV->isAffine())
9991     return getCouldNotCompute();
9992 
9993   bool NoWrap = ControlsExit &&
9994                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
9995 
9996   const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
9997 
9998   // Avoid negative or zero stride values
9999   if (!isKnownPositive(Stride))
10000     return getCouldNotCompute();
10001 
10002   // Avoid proven overflow cases: this will ensure that the backedge taken count
10003   // will not generate any unsigned overflow. Relaxed no-overflow conditions
10004   // exploit NoWrapFlags, allowing to optimize in presence of undefined
10005   // behaviors like the case of C language.
10006   if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap))
10007     return getCouldNotCompute();
10008 
10009   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT
10010                                       : ICmpInst::ICMP_UGT;
10011 
10012   const SCEV *Start = IV->getStart();
10013   const SCEV *End = RHS;
10014   if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS))
10015     End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
10016 
10017   const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false);
10018 
10019   APInt MaxStart = IsSigned ? getSignedRangeMax(Start)
10020                             : getUnsignedRangeMax(Start);
10021 
10022   APInt MinStride = IsSigned ? getSignedRangeMin(Stride)
10023                              : getUnsignedRangeMin(Stride);
10024 
10025   unsigned BitWidth = getTypeSizeInBits(LHS->getType());
10026   APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
10027                          : APInt::getMinValue(BitWidth) + (MinStride - 1);
10028 
10029   // Although End can be a MIN expression we estimate MinEnd considering only
10030   // the case End = RHS. This is safe because in the other case (Start - End)
10031   // is zero, leading to a zero maximum backedge taken count.
10032   APInt MinEnd =
10033     IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit)
10034              : APIntOps::umax(getUnsignedRangeMin(RHS), Limit);
10035 
10036 
10037   const SCEV *MaxBECount = getCouldNotCompute();
10038   if (isa<SCEVConstant>(BECount))
10039     MaxBECount = BECount;
10040   else
10041     MaxBECount = computeBECount(getConstant(MaxStart - MinEnd),
10042                                 getConstant(MinStride), false);
10043 
10044   if (isa<SCEVCouldNotCompute>(MaxBECount))
10045     MaxBECount = BECount;
10046 
10047   return ExitLimit(BECount, MaxBECount, false, Predicates);
10048 }
10049 
10050 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range,
10051                                                     ScalarEvolution &SE) const {
10052   if (Range.isFullSet())  // Infinite loop.
10053     return SE.getCouldNotCompute();
10054 
10055   // If the start is a non-zero constant, shift the range to simplify things.
10056   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
10057     if (!SC->getValue()->isZero()) {
10058       SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
10059       Operands[0] = SE.getZero(SC->getType());
10060       const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
10061                                              getNoWrapFlags(FlagNW));
10062       if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
10063         return ShiftedAddRec->getNumIterationsInRange(
10064             Range.subtract(SC->getAPInt()), SE);
10065       // This is strange and shouldn't happen.
10066       return SE.getCouldNotCompute();
10067     }
10068 
10069   // The only time we can solve this is when we have all constant indices.
10070   // Otherwise, we cannot determine the overflow conditions.
10071   if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
10072     return SE.getCouldNotCompute();
10073 
10074   // Okay at this point we know that all elements of the chrec are constants and
10075   // that the start element is zero.
10076 
10077   // First check to see if the range contains zero.  If not, the first
10078   // iteration exits.
10079   unsigned BitWidth = SE.getTypeSizeInBits(getType());
10080   if (!Range.contains(APInt(BitWidth, 0)))
10081     return SE.getZero(getType());
10082 
10083   if (isAffine()) {
10084     // If this is an affine expression then we have this situation:
10085     //   Solve {0,+,A} in Range  ===  Ax in Range
10086 
10087     // We know that zero is in the range.  If A is positive then we know that
10088     // the upper value of the range must be the first possible exit value.
10089     // If A is negative then the lower of the range is the last possible loop
10090     // value.  Also note that we already checked for a full range.
10091     APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
10092     APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower();
10093 
10094     // The exit value should be (End+A)/A.
10095     APInt ExitVal = (End + A).udiv(A);
10096     ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
10097 
10098     // Evaluate at the exit value.  If we really did fall out of the valid
10099     // range, then we computed our trip count, otherwise wrap around or other
10100     // things must have happened.
10101     ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
10102     if (Range.contains(Val->getValue()))
10103       return SE.getCouldNotCompute();  // Something strange happened
10104 
10105     // Ensure that the previous value is in the range.  This is a sanity check.
10106     assert(Range.contains(
10107            EvaluateConstantChrecAtConstant(this,
10108            ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&
10109            "Linear scev computation is off in a bad way!");
10110     return SE.getConstant(ExitValue);
10111   } else if (isQuadratic()) {
10112     // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
10113     // quadratic equation to solve it.  To do this, we must frame our problem in
10114     // terms of figuring out when zero is crossed, instead of when
10115     // Range.getUpper() is crossed.
10116     SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
10117     NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
10118     const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(), FlagAnyWrap);
10119 
10120     // Next, solve the constructed addrec
10121     if (auto Roots =
10122             SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE)) {
10123       const SCEVConstant *R1 = Roots->first;
10124       const SCEVConstant *R2 = Roots->second;
10125       // Pick the smallest positive root value.
10126       if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
10127               ICmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
10128         if (!CB->getZExtValue())
10129           std::swap(R1, R2); // R1 is the minimum root now.
10130 
10131         // Make sure the root is not off by one.  The returned iteration should
10132         // not be in the range, but the previous one should be.  When solving
10133         // for "X*X < 5", for example, we should not return a root of 2.
10134         ConstantInt *R1Val =
10135             EvaluateConstantChrecAtConstant(this, R1->getValue(), SE);
10136         if (Range.contains(R1Val->getValue())) {
10137           // The next iteration must be out of the range...
10138           ConstantInt *NextVal =
10139               ConstantInt::get(SE.getContext(), R1->getAPInt() + 1);
10140 
10141           R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
10142           if (!Range.contains(R1Val->getValue()))
10143             return SE.getConstant(NextVal);
10144           return SE.getCouldNotCompute(); // Something strange happened
10145         }
10146 
10147         // If R1 was not in the range, then it is a good return value.  Make
10148         // sure that R1-1 WAS in the range though, just in case.
10149         ConstantInt *NextVal =
10150             ConstantInt::get(SE.getContext(), R1->getAPInt() - 1);
10151         R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
10152         if (Range.contains(R1Val->getValue()))
10153           return R1;
10154         return SE.getCouldNotCompute(); // Something strange happened
10155       }
10156     }
10157   }
10158 
10159   return SE.getCouldNotCompute();
10160 }
10161 
10162 // Return true when S contains at least an undef value.
10163 static inline bool containsUndefs(const SCEV *S) {
10164   return SCEVExprContains(S, [](const SCEV *S) {
10165     if (const auto *SU = dyn_cast<SCEVUnknown>(S))
10166       return isa<UndefValue>(SU->getValue());
10167     else if (const auto *SC = dyn_cast<SCEVConstant>(S))
10168       return isa<UndefValue>(SC->getValue());
10169     return false;
10170   });
10171 }
10172 
10173 namespace {
10174 
10175 // Collect all steps of SCEV expressions.
10176 struct SCEVCollectStrides {
10177   ScalarEvolution &SE;
10178   SmallVectorImpl<const SCEV *> &Strides;
10179 
10180   SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S)
10181       : SE(SE), Strides(S) {}
10182 
10183   bool follow(const SCEV *S) {
10184     if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
10185       Strides.push_back(AR->getStepRecurrence(SE));
10186     return true;
10187   }
10188 
10189   bool isDone() const { return false; }
10190 };
10191 
10192 // Collect all SCEVUnknown and SCEVMulExpr expressions.
10193 struct SCEVCollectTerms {
10194   SmallVectorImpl<const SCEV *> &Terms;
10195 
10196   SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) : Terms(T) {}
10197 
10198   bool follow(const SCEV *S) {
10199     if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) ||
10200         isa<SCEVSignExtendExpr>(S)) {
10201       if (!containsUndefs(S))
10202         Terms.push_back(S);
10203 
10204       // Stop recursion: once we collected a term, do not walk its operands.
10205       return false;
10206     }
10207 
10208     // Keep looking.
10209     return true;
10210   }
10211 
10212   bool isDone() const { return false; }
10213 };
10214 
10215 // Check if a SCEV contains an AddRecExpr.
10216 struct SCEVHasAddRec {
10217   bool &ContainsAddRec;
10218 
10219   SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) {
10220     ContainsAddRec = false;
10221   }
10222 
10223   bool follow(const SCEV *S) {
10224     if (isa<SCEVAddRecExpr>(S)) {
10225       ContainsAddRec = true;
10226 
10227       // Stop recursion: once we collected a term, do not walk its operands.
10228       return false;
10229     }
10230 
10231     // Keep looking.
10232     return true;
10233   }
10234 
10235   bool isDone() const { return false; }
10236 };
10237 
10238 // Find factors that are multiplied with an expression that (possibly as a
10239 // subexpression) contains an AddRecExpr. In the expression:
10240 //
10241 //  8 * (100 +  %p * %q * (%a + {0, +, 1}_loop))
10242 //
10243 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)"
10244 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size
10245 // parameters as they form a product with an induction variable.
10246 //
10247 // This collector expects all array size parameters to be in the same MulExpr.
10248 // It might be necessary to later add support for collecting parameters that are
10249 // spread over different nested MulExpr.
10250 struct SCEVCollectAddRecMultiplies {
10251   SmallVectorImpl<const SCEV *> &Terms;
10252   ScalarEvolution &SE;
10253 
10254   SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE)
10255       : Terms(T), SE(SE) {}
10256 
10257   bool follow(const SCEV *S) {
10258     if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) {
10259       bool HasAddRec = false;
10260       SmallVector<const SCEV *, 0> Operands;
10261       for (auto Op : Mul->operands()) {
10262         const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op);
10263         if (Unknown && !isa<CallInst>(Unknown->getValue())) {
10264           Operands.push_back(Op);
10265         } else if (Unknown) {
10266           HasAddRec = true;
10267         } else {
10268           bool ContainsAddRec;
10269           SCEVHasAddRec ContiansAddRec(ContainsAddRec);
10270           visitAll(Op, ContiansAddRec);
10271           HasAddRec |= ContainsAddRec;
10272         }
10273       }
10274       if (Operands.size() == 0)
10275         return true;
10276 
10277       if (!HasAddRec)
10278         return false;
10279 
10280       Terms.push_back(SE.getMulExpr(Operands));
10281       // Stop recursion: once we collected a term, do not walk its operands.
10282       return false;
10283     }
10284 
10285     // Keep looking.
10286     return true;
10287   }
10288 
10289   bool isDone() const { return false; }
10290 };
10291 
10292 } // end anonymous namespace
10293 
10294 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in
10295 /// two places:
10296 ///   1) The strides of AddRec expressions.
10297 ///   2) Unknowns that are multiplied with AddRec expressions.
10298 void ScalarEvolution::collectParametricTerms(const SCEV *Expr,
10299     SmallVectorImpl<const SCEV *> &Terms) {
10300   SmallVector<const SCEV *, 4> Strides;
10301   SCEVCollectStrides StrideCollector(*this, Strides);
10302   visitAll(Expr, StrideCollector);
10303 
10304   DEBUG({
10305       dbgs() << "Strides:\n";
10306       for (const SCEV *S : Strides)
10307         dbgs() << *S << "\n";
10308     });
10309 
10310   for (const SCEV *S : Strides) {
10311     SCEVCollectTerms TermCollector(Terms);
10312     visitAll(S, TermCollector);
10313   }
10314 
10315   DEBUG({
10316       dbgs() << "Terms:\n";
10317       for (const SCEV *T : Terms)
10318         dbgs() << *T << "\n";
10319     });
10320 
10321   SCEVCollectAddRecMultiplies MulCollector(Terms, *this);
10322   visitAll(Expr, MulCollector);
10323 }
10324 
10325 static bool findArrayDimensionsRec(ScalarEvolution &SE,
10326                                    SmallVectorImpl<const SCEV *> &Terms,
10327                                    SmallVectorImpl<const SCEV *> &Sizes) {
10328   int Last = Terms.size() - 1;
10329   const SCEV *Step = Terms[Last];
10330 
10331   // End of recursion.
10332   if (Last == 0) {
10333     if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) {
10334       SmallVector<const SCEV *, 2> Qs;
10335       for (const SCEV *Op : M->operands())
10336         if (!isa<SCEVConstant>(Op))
10337           Qs.push_back(Op);
10338 
10339       Step = SE.getMulExpr(Qs);
10340     }
10341 
10342     Sizes.push_back(Step);
10343     return true;
10344   }
10345 
10346   for (const SCEV *&Term : Terms) {
10347     // Normalize the terms before the next call to findArrayDimensionsRec.
10348     const SCEV *Q, *R;
10349     SCEVDivision::divide(SE, Term, Step, &Q, &R);
10350 
10351     // Bail out when GCD does not evenly divide one of the terms.
10352     if (!R->isZero())
10353       return false;
10354 
10355     Term = Q;
10356   }
10357 
10358   // Remove all SCEVConstants.
10359   Terms.erase(
10360       remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }),
10361       Terms.end());
10362 
10363   if (Terms.size() > 0)
10364     if (!findArrayDimensionsRec(SE, Terms, Sizes))
10365       return false;
10366 
10367   Sizes.push_back(Step);
10368   return true;
10369 }
10370 
10371 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter.
10372 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) {
10373   for (const SCEV *T : Terms)
10374     if (SCEVExprContains(T, isa<SCEVUnknown, const SCEV *>))
10375       return true;
10376   return false;
10377 }
10378 
10379 // Return the number of product terms in S.
10380 static inline int numberOfTerms(const SCEV *S) {
10381   if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S))
10382     return Expr->getNumOperands();
10383   return 1;
10384 }
10385 
10386 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) {
10387   if (isa<SCEVConstant>(T))
10388     return nullptr;
10389 
10390   if (isa<SCEVUnknown>(T))
10391     return T;
10392 
10393   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) {
10394     SmallVector<const SCEV *, 2> Factors;
10395     for (const SCEV *Op : M->operands())
10396       if (!isa<SCEVConstant>(Op))
10397         Factors.push_back(Op);
10398 
10399     return SE.getMulExpr(Factors);
10400   }
10401 
10402   return T;
10403 }
10404 
10405 /// Return the size of an element read or written by Inst.
10406 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
10407   Type *Ty;
10408   if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
10409     Ty = Store->getValueOperand()->getType();
10410   else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
10411     Ty = Load->getType();
10412   else
10413     return nullptr;
10414 
10415   Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
10416   return getSizeOfExpr(ETy, Ty);
10417 }
10418 
10419 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
10420                                           SmallVectorImpl<const SCEV *> &Sizes,
10421                                           const SCEV *ElementSize) {
10422   if (Terms.size() < 1 || !ElementSize)
10423     return;
10424 
10425   // Early return when Terms do not contain parameters: we do not delinearize
10426   // non parametric SCEVs.
10427   if (!containsParameters(Terms))
10428     return;
10429 
10430   DEBUG({
10431       dbgs() << "Terms:\n";
10432       for (const SCEV *T : Terms)
10433         dbgs() << *T << "\n";
10434     });
10435 
10436   // Remove duplicates.
10437   array_pod_sort(Terms.begin(), Terms.end());
10438   Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end());
10439 
10440   // Put larger terms first.
10441   std::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) {
10442     return numberOfTerms(LHS) > numberOfTerms(RHS);
10443   });
10444 
10445   // Try to divide all terms by the element size. If term is not divisible by
10446   // element size, proceed with the original term.
10447   for (const SCEV *&Term : Terms) {
10448     const SCEV *Q, *R;
10449     SCEVDivision::divide(*this, Term, ElementSize, &Q, &R);
10450     if (!Q->isZero())
10451       Term = Q;
10452   }
10453 
10454   SmallVector<const SCEV *, 4> NewTerms;
10455 
10456   // Remove constant factors.
10457   for (const SCEV *T : Terms)
10458     if (const SCEV *NewT = removeConstantFactors(*this, T))
10459       NewTerms.push_back(NewT);
10460 
10461   DEBUG({
10462       dbgs() << "Terms after sorting:\n";
10463       for (const SCEV *T : NewTerms)
10464         dbgs() << *T << "\n";
10465     });
10466 
10467   if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) {
10468     Sizes.clear();
10469     return;
10470   }
10471 
10472   // The last element to be pushed into Sizes is the size of an element.
10473   Sizes.push_back(ElementSize);
10474 
10475   DEBUG({
10476       dbgs() << "Sizes:\n";
10477       for (const SCEV *S : Sizes)
10478         dbgs() << *S << "\n";
10479     });
10480 }
10481 
10482 void ScalarEvolution::computeAccessFunctions(
10483     const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts,
10484     SmallVectorImpl<const SCEV *> &Sizes) {
10485   // Early exit in case this SCEV is not an affine multivariate function.
10486   if (Sizes.empty())
10487     return;
10488 
10489   if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr))
10490     if (!AR->isAffine())
10491       return;
10492 
10493   const SCEV *Res = Expr;
10494   int Last = Sizes.size() - 1;
10495   for (int i = Last; i >= 0; i--) {
10496     const SCEV *Q, *R;
10497     SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R);
10498 
10499     DEBUG({
10500         dbgs() << "Res: " << *Res << "\n";
10501         dbgs() << "Sizes[i]: " << *Sizes[i] << "\n";
10502         dbgs() << "Res divided by Sizes[i]:\n";
10503         dbgs() << "Quotient: " << *Q << "\n";
10504         dbgs() << "Remainder: " << *R << "\n";
10505       });
10506 
10507     Res = Q;
10508 
10509     // Do not record the last subscript corresponding to the size of elements in
10510     // the array.
10511     if (i == Last) {
10512 
10513       // Bail out if the remainder is too complex.
10514       if (isa<SCEVAddRecExpr>(R)) {
10515         Subscripts.clear();
10516         Sizes.clear();
10517         return;
10518       }
10519 
10520       continue;
10521     }
10522 
10523     // Record the access function for the current subscript.
10524     Subscripts.push_back(R);
10525   }
10526 
10527   // Also push in last position the remainder of the last division: it will be
10528   // the access function of the innermost dimension.
10529   Subscripts.push_back(Res);
10530 
10531   std::reverse(Subscripts.begin(), Subscripts.end());
10532 
10533   DEBUG({
10534       dbgs() << "Subscripts:\n";
10535       for (const SCEV *S : Subscripts)
10536         dbgs() << *S << "\n";
10537     });
10538 }
10539 
10540 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and
10541 /// sizes of an array access. Returns the remainder of the delinearization that
10542 /// is the offset start of the array.  The SCEV->delinearize algorithm computes
10543 /// the multiples of SCEV coefficients: that is a pattern matching of sub
10544 /// expressions in the stride and base of a SCEV corresponding to the
10545 /// computation of a GCD (greatest common divisor) of base and stride.  When
10546 /// SCEV->delinearize fails, it returns the SCEV unchanged.
10547 ///
10548 /// For example: when analyzing the memory access A[i][j][k] in this loop nest
10549 ///
10550 ///  void foo(long n, long m, long o, double A[n][m][o]) {
10551 ///
10552 ///    for (long i = 0; i < n; i++)
10553 ///      for (long j = 0; j < m; j++)
10554 ///        for (long k = 0; k < o; k++)
10555 ///          A[i][j][k] = 1.0;
10556 ///  }
10557 ///
10558 /// the delinearization input is the following AddRec SCEV:
10559 ///
10560 ///  AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k>
10561 ///
10562 /// From this SCEV, we are able to say that the base offset of the access is %A
10563 /// because it appears as an offset that does not divide any of the strides in
10564 /// the loops:
10565 ///
10566 ///  CHECK: Base offset: %A
10567 ///
10568 /// and then SCEV->delinearize determines the size of some of the dimensions of
10569 /// the array as these are the multiples by which the strides are happening:
10570 ///
10571 ///  CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes.
10572 ///
10573 /// Note that the outermost dimension remains of UnknownSize because there are
10574 /// no strides that would help identifying the size of the last dimension: when
10575 /// the array has been statically allocated, one could compute the size of that
10576 /// dimension by dividing the overall size of the array by the size of the known
10577 /// dimensions: %m * %o * 8.
10578 ///
10579 /// Finally delinearize provides the access functions for the array reference
10580 /// that does correspond to A[i][j][k] of the above C testcase:
10581 ///
10582 ///  CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>]
10583 ///
10584 /// The testcases are checking the output of a function pass:
10585 /// DelinearizationPass that walks through all loads and stores of a function
10586 /// asking for the SCEV of the memory access with respect to all enclosing
10587 /// loops, calling SCEV->delinearize on that and printing the results.
10588 void ScalarEvolution::delinearize(const SCEV *Expr,
10589                                  SmallVectorImpl<const SCEV *> &Subscripts,
10590                                  SmallVectorImpl<const SCEV *> &Sizes,
10591                                  const SCEV *ElementSize) {
10592   // First step: collect parametric terms.
10593   SmallVector<const SCEV *, 4> Terms;
10594   collectParametricTerms(Expr, Terms);
10595 
10596   if (Terms.empty())
10597     return;
10598 
10599   // Second step: find subscript sizes.
10600   findArrayDimensions(Terms, Sizes, ElementSize);
10601 
10602   if (Sizes.empty())
10603     return;
10604 
10605   // Third step: compute the access functions for each subscript.
10606   computeAccessFunctions(Expr, Subscripts, Sizes);
10607 
10608   if (Subscripts.empty())
10609     return;
10610 
10611   DEBUG({
10612       dbgs() << "succeeded to delinearize " << *Expr << "\n";
10613       dbgs() << "ArrayDecl[UnknownSize]";
10614       for (const SCEV *S : Sizes)
10615         dbgs() << "[" << *S << "]";
10616 
10617       dbgs() << "\nArrayRef";
10618       for (const SCEV *S : Subscripts)
10619         dbgs() << "[" << *S << "]";
10620       dbgs() << "\n";
10621     });
10622 }
10623 
10624 //===----------------------------------------------------------------------===//
10625 //                   SCEVCallbackVH Class Implementation
10626 //===----------------------------------------------------------------------===//
10627 
10628 void ScalarEvolution::SCEVCallbackVH::deleted() {
10629   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
10630   if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
10631     SE->ConstantEvolutionLoopExitValue.erase(PN);
10632   SE->eraseValueFromMap(getValPtr());
10633   // this now dangles!
10634 }
10635 
10636 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
10637   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
10638 
10639   // Forget all the expressions associated with users of the old value,
10640   // so that future queries will recompute the expressions using the new
10641   // value.
10642   Value *Old = getValPtr();
10643   SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end());
10644   SmallPtrSet<User *, 8> Visited;
10645   while (!Worklist.empty()) {
10646     User *U = Worklist.pop_back_val();
10647     // Deleting the Old value will cause this to dangle. Postpone
10648     // that until everything else is done.
10649     if (U == Old)
10650       continue;
10651     if (!Visited.insert(U).second)
10652       continue;
10653     if (PHINode *PN = dyn_cast<PHINode>(U))
10654       SE->ConstantEvolutionLoopExitValue.erase(PN);
10655     SE->eraseValueFromMap(U);
10656     Worklist.insert(Worklist.end(), U->user_begin(), U->user_end());
10657   }
10658   // Delete the Old value.
10659   if (PHINode *PN = dyn_cast<PHINode>(Old))
10660     SE->ConstantEvolutionLoopExitValue.erase(PN);
10661   SE->eraseValueFromMap(Old);
10662   // this now dangles!
10663 }
10664 
10665 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
10666   : CallbackVH(V), SE(se) {}
10667 
10668 //===----------------------------------------------------------------------===//
10669 //                   ScalarEvolution Class Implementation
10670 //===----------------------------------------------------------------------===//
10671 
10672 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
10673                                  AssumptionCache &AC, DominatorTree &DT,
10674                                  LoopInfo &LI)
10675     : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
10676       CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64),
10677       LoopDispositions(64), BlockDispositions(64) {
10678   // To use guards for proving predicates, we need to scan every instruction in
10679   // relevant basic blocks, and not just terminators.  Doing this is a waste of
10680   // time if the IR does not actually contain any calls to
10681   // @llvm.experimental.guard, so do a quick check and remember this beforehand.
10682   //
10683   // This pessimizes the case where a pass that preserves ScalarEvolution wants
10684   // to _add_ guards to the module when there weren't any before, and wants
10685   // ScalarEvolution to optimize based on those guards.  For now we prefer to be
10686   // efficient in lieu of being smart in that rather obscure case.
10687 
10688   auto *GuardDecl = F.getParent()->getFunction(
10689       Intrinsic::getName(Intrinsic::experimental_guard));
10690   HasGuards = GuardDecl && !GuardDecl->use_empty();
10691 }
10692 
10693 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
10694     : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT),
10695       LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
10696       ValueExprMap(std::move(Arg.ValueExprMap)),
10697       PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
10698       MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)),
10699       BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
10700       PredicatedBackedgeTakenCounts(
10701           std::move(Arg.PredicatedBackedgeTakenCounts)),
10702       ConstantEvolutionLoopExitValue(
10703           std::move(Arg.ConstantEvolutionLoopExitValue)),
10704       ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
10705       LoopDispositions(std::move(Arg.LoopDispositions)),
10706       LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
10707       BlockDispositions(std::move(Arg.BlockDispositions)),
10708       UnsignedRanges(std::move(Arg.UnsignedRanges)),
10709       SignedRanges(std::move(Arg.SignedRanges)),
10710       UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
10711       UniquePreds(std::move(Arg.UniquePreds)),
10712       SCEVAllocator(std::move(Arg.SCEVAllocator)),
10713       LoopUsers(std::move(Arg.LoopUsers)),
10714       PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)),
10715       FirstUnknown(Arg.FirstUnknown) {
10716   Arg.FirstUnknown = nullptr;
10717 }
10718 
10719 ScalarEvolution::~ScalarEvolution() {
10720   // Iterate through all the SCEVUnknown instances and call their
10721   // destructors, so that they release their references to their values.
10722   for (SCEVUnknown *U = FirstUnknown; U;) {
10723     SCEVUnknown *Tmp = U;
10724     U = U->Next;
10725     Tmp->~SCEVUnknown();
10726   }
10727   FirstUnknown = nullptr;
10728 
10729   ExprValueMap.clear();
10730   ValueExprMap.clear();
10731   HasRecMap.clear();
10732 
10733   // Free any extra memory created for ExitNotTakenInfo in the unlikely event
10734   // that a loop had multiple computable exits.
10735   for (auto &BTCI : BackedgeTakenCounts)
10736     BTCI.second.clear();
10737   for (auto &BTCI : PredicatedBackedgeTakenCounts)
10738     BTCI.second.clear();
10739 
10740   assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
10741   assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
10742   assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
10743 }
10744 
10745 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
10746   return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
10747 }
10748 
10749 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
10750                           const Loop *L) {
10751   // Print all inner loops first
10752   for (Loop *I : *L)
10753     PrintLoopInfo(OS, SE, I);
10754 
10755   OS << "Loop ";
10756   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
10757   OS << ": ";
10758 
10759   SmallVector<BasicBlock *, 8> ExitBlocks;
10760   L->getExitBlocks(ExitBlocks);
10761   if (ExitBlocks.size() != 1)
10762     OS << "<multiple exits> ";
10763 
10764   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
10765     OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
10766   } else {
10767     OS << "Unpredictable backedge-taken count. ";
10768   }
10769 
10770   OS << "\n"
10771         "Loop ";
10772   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
10773   OS << ": ";
10774 
10775   if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
10776     OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
10777     if (SE->isBackedgeTakenCountMaxOrZero(L))
10778       OS << ", actual taken count either this or zero.";
10779   } else {
10780     OS << "Unpredictable max backedge-taken count. ";
10781   }
10782 
10783   OS << "\n"
10784         "Loop ";
10785   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
10786   OS << ": ";
10787 
10788   SCEVUnionPredicate Pred;
10789   auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred);
10790   if (!isa<SCEVCouldNotCompute>(PBT)) {
10791     OS << "Predicated backedge-taken count is " << *PBT << "\n";
10792     OS << " Predicates:\n";
10793     Pred.print(OS, 4);
10794   } else {
10795     OS << "Unpredictable predicated backedge-taken count. ";
10796   }
10797   OS << "\n";
10798 
10799   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
10800     OS << "Loop ";
10801     L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
10802     OS << ": ";
10803     OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
10804   }
10805 }
10806 
10807 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) {
10808   switch (LD) {
10809   case ScalarEvolution::LoopVariant:
10810     return "Variant";
10811   case ScalarEvolution::LoopInvariant:
10812     return "Invariant";
10813   case ScalarEvolution::LoopComputable:
10814     return "Computable";
10815   }
10816   llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!");
10817 }
10818 
10819 void ScalarEvolution::print(raw_ostream &OS) const {
10820   // ScalarEvolution's implementation of the print method is to print
10821   // out SCEV values of all instructions that are interesting. Doing
10822   // this potentially causes it to create new SCEV objects though,
10823   // which technically conflicts with the const qualifier. This isn't
10824   // observable from outside the class though, so casting away the
10825   // const isn't dangerous.
10826   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
10827 
10828   OS << "Classifying expressions for: ";
10829   F.printAsOperand(OS, /*PrintType=*/false);
10830   OS << "\n";
10831   for (Instruction &I : instructions(F))
10832     if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
10833       OS << I << '\n';
10834       OS << "  -->  ";
10835       const SCEV *SV = SE.getSCEV(&I);
10836       SV->print(OS);
10837       if (!isa<SCEVCouldNotCompute>(SV)) {
10838         OS << " U: ";
10839         SE.getUnsignedRange(SV).print(OS);
10840         OS << " S: ";
10841         SE.getSignedRange(SV).print(OS);
10842       }
10843 
10844       const Loop *L = LI.getLoopFor(I.getParent());
10845 
10846       const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
10847       if (AtUse != SV) {
10848         OS << "  -->  ";
10849         AtUse->print(OS);
10850         if (!isa<SCEVCouldNotCompute>(AtUse)) {
10851           OS << " U: ";
10852           SE.getUnsignedRange(AtUse).print(OS);
10853           OS << " S: ";
10854           SE.getSignedRange(AtUse).print(OS);
10855         }
10856       }
10857 
10858       if (L) {
10859         OS << "\t\t" "Exits: ";
10860         const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
10861         if (!SE.isLoopInvariant(ExitValue, L)) {
10862           OS << "<<Unknown>>";
10863         } else {
10864           OS << *ExitValue;
10865         }
10866 
10867         bool First = true;
10868         for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
10869           if (First) {
10870             OS << "\t\t" "LoopDispositions: { ";
10871             First = false;
10872           } else {
10873             OS << ", ";
10874           }
10875 
10876           Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
10877           OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter));
10878         }
10879 
10880         for (auto *InnerL : depth_first(L)) {
10881           if (InnerL == L)
10882             continue;
10883           if (First) {
10884             OS << "\t\t" "LoopDispositions: { ";
10885             First = false;
10886           } else {
10887             OS << ", ";
10888           }
10889 
10890           InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
10891           OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL));
10892         }
10893 
10894         OS << " }";
10895       }
10896 
10897       OS << "\n";
10898     }
10899 
10900   OS << "Determining loop execution counts for: ";
10901   F.printAsOperand(OS, /*PrintType=*/false);
10902   OS << "\n";
10903   for (Loop *I : LI)
10904     PrintLoopInfo(OS, &SE, I);
10905 }
10906 
10907 ScalarEvolution::LoopDisposition
10908 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
10909   auto &Values = LoopDispositions[S];
10910   for (auto &V : Values) {
10911     if (V.getPointer() == L)
10912       return V.getInt();
10913   }
10914   Values.emplace_back(L, LoopVariant);
10915   LoopDisposition D = computeLoopDisposition(S, L);
10916   auto &Values2 = LoopDispositions[S];
10917   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
10918     if (V.getPointer() == L) {
10919       V.setInt(D);
10920       break;
10921     }
10922   }
10923   return D;
10924 }
10925 
10926 ScalarEvolution::LoopDisposition
10927 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
10928   switch (static_cast<SCEVTypes>(S->getSCEVType())) {
10929   case scConstant:
10930     return LoopInvariant;
10931   case scTruncate:
10932   case scZeroExtend:
10933   case scSignExtend:
10934     return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
10935   case scAddRecExpr: {
10936     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
10937 
10938     // If L is the addrec's loop, it's computable.
10939     if (AR->getLoop() == L)
10940       return LoopComputable;
10941 
10942     // Add recurrences are never invariant in the function-body (null loop).
10943     if (!L)
10944       return LoopVariant;
10945 
10946     // Everything that is not defined at loop entry is variant.
10947     if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader()))
10948       return LoopVariant;
10949     assert(!L->contains(AR->getLoop()) && "Containing loop's header does not"
10950            " dominate the contained loop's header?");
10951 
10952     // This recurrence is invariant w.r.t. L if AR's loop contains L.
10953     if (AR->getLoop()->contains(L))
10954       return LoopInvariant;
10955 
10956     // This recurrence is variant w.r.t. L if any of its operands
10957     // are variant.
10958     for (auto *Op : AR->operands())
10959       if (!isLoopInvariant(Op, L))
10960         return LoopVariant;
10961 
10962     // Otherwise it's loop-invariant.
10963     return LoopInvariant;
10964   }
10965   case scAddExpr:
10966   case scMulExpr:
10967   case scUMaxExpr:
10968   case scSMaxExpr: {
10969     bool HasVarying = false;
10970     for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) {
10971       LoopDisposition D = getLoopDisposition(Op, L);
10972       if (D == LoopVariant)
10973         return LoopVariant;
10974       if (D == LoopComputable)
10975         HasVarying = true;
10976     }
10977     return HasVarying ? LoopComputable : LoopInvariant;
10978   }
10979   case scUDivExpr: {
10980     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
10981     LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
10982     if (LD == LoopVariant)
10983       return LoopVariant;
10984     LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
10985     if (RD == LoopVariant)
10986       return LoopVariant;
10987     return (LD == LoopInvariant && RD == LoopInvariant) ?
10988            LoopInvariant : LoopComputable;
10989   }
10990   case scUnknown:
10991     // All non-instruction values are loop invariant.  All instructions are loop
10992     // invariant if they are not contained in the specified loop.
10993     // Instructions are never considered invariant in the function body
10994     // (null loop) because they are defined within the "loop".
10995     if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
10996       return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
10997     return LoopInvariant;
10998   case scCouldNotCompute:
10999     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
11000   }
11001   llvm_unreachable("Unknown SCEV kind!");
11002 }
11003 
11004 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
11005   return getLoopDisposition(S, L) == LoopInvariant;
11006 }
11007 
11008 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
11009   return getLoopDisposition(S, L) == LoopComputable;
11010 }
11011 
11012 ScalarEvolution::BlockDisposition
11013 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
11014   auto &Values = BlockDispositions[S];
11015   for (auto &V : Values) {
11016     if (V.getPointer() == BB)
11017       return V.getInt();
11018   }
11019   Values.emplace_back(BB, DoesNotDominateBlock);
11020   BlockDisposition D = computeBlockDisposition(S, BB);
11021   auto &Values2 = BlockDispositions[S];
11022   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
11023     if (V.getPointer() == BB) {
11024       V.setInt(D);
11025       break;
11026     }
11027   }
11028   return D;
11029 }
11030 
11031 ScalarEvolution::BlockDisposition
11032 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
11033   switch (static_cast<SCEVTypes>(S->getSCEVType())) {
11034   case scConstant:
11035     return ProperlyDominatesBlock;
11036   case scTruncate:
11037   case scZeroExtend:
11038   case scSignExtend:
11039     return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
11040   case scAddRecExpr: {
11041     // This uses a "dominates" query instead of "properly dominates" query
11042     // to test for proper dominance too, because the instruction which
11043     // produces the addrec's value is a PHI, and a PHI effectively properly
11044     // dominates its entire containing block.
11045     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
11046     if (!DT.dominates(AR->getLoop()->getHeader(), BB))
11047       return DoesNotDominateBlock;
11048 
11049     // Fall through into SCEVNAryExpr handling.
11050     LLVM_FALLTHROUGH;
11051   }
11052   case scAddExpr:
11053   case scMulExpr:
11054   case scUMaxExpr:
11055   case scSMaxExpr: {
11056     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
11057     bool Proper = true;
11058     for (const SCEV *NAryOp : NAry->operands()) {
11059       BlockDisposition D = getBlockDisposition(NAryOp, BB);
11060       if (D == DoesNotDominateBlock)
11061         return DoesNotDominateBlock;
11062       if (D == DominatesBlock)
11063         Proper = false;
11064     }
11065     return Proper ? ProperlyDominatesBlock : DominatesBlock;
11066   }
11067   case scUDivExpr: {
11068     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
11069     const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
11070     BlockDisposition LD = getBlockDisposition(LHS, BB);
11071     if (LD == DoesNotDominateBlock)
11072       return DoesNotDominateBlock;
11073     BlockDisposition RD = getBlockDisposition(RHS, BB);
11074     if (RD == DoesNotDominateBlock)
11075       return DoesNotDominateBlock;
11076     return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
11077       ProperlyDominatesBlock : DominatesBlock;
11078   }
11079   case scUnknown:
11080     if (Instruction *I =
11081           dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
11082       if (I->getParent() == BB)
11083         return DominatesBlock;
11084       if (DT.properlyDominates(I->getParent(), BB))
11085         return ProperlyDominatesBlock;
11086       return DoesNotDominateBlock;
11087     }
11088     return ProperlyDominatesBlock;
11089   case scCouldNotCompute:
11090     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
11091   }
11092   llvm_unreachable("Unknown SCEV kind!");
11093 }
11094 
11095 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
11096   return getBlockDisposition(S, BB) >= DominatesBlock;
11097 }
11098 
11099 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
11100   return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
11101 }
11102 
11103 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
11104   return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; });
11105 }
11106 
11107 bool ScalarEvolution::ExitLimit::hasOperand(const SCEV *S) const {
11108   auto IsS = [&](const SCEV *X) { return S == X; };
11109   auto ContainsS = [&](const SCEV *X) {
11110     return !isa<SCEVCouldNotCompute>(X) && SCEVExprContains(X, IsS);
11111   };
11112   return ContainsS(ExactNotTaken) || ContainsS(MaxNotTaken);
11113 }
11114 
11115 void
11116 ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
11117   ValuesAtScopes.erase(S);
11118   LoopDispositions.erase(S);
11119   BlockDispositions.erase(S);
11120   UnsignedRanges.erase(S);
11121   SignedRanges.erase(S);
11122   ExprValueMap.erase(S);
11123   HasRecMap.erase(S);
11124   MinTrailingZerosCache.erase(S);
11125 
11126   for (auto I = PredicatedSCEVRewrites.begin();
11127        I != PredicatedSCEVRewrites.end();) {
11128     std::pair<const SCEV *, const Loop *> Entry = I->first;
11129     if (Entry.first == S)
11130       PredicatedSCEVRewrites.erase(I++);
11131     else
11132       ++I;
11133   }
11134 
11135   auto RemoveSCEVFromBackedgeMap =
11136       [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
11137         for (auto I = Map.begin(), E = Map.end(); I != E;) {
11138           BackedgeTakenInfo &BEInfo = I->second;
11139           if (BEInfo.hasOperand(S, this)) {
11140             BEInfo.clear();
11141             Map.erase(I++);
11142           } else
11143             ++I;
11144         }
11145       };
11146 
11147   RemoveSCEVFromBackedgeMap(BackedgeTakenCounts);
11148   RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts);
11149 }
11150 
11151 void ScalarEvolution::addToLoopUseLists(const SCEV *S) {
11152   struct FindUsedLoops {
11153     SmallPtrSet<const Loop *, 8> LoopsUsed;
11154     bool follow(const SCEV *S) {
11155       if (auto *AR = dyn_cast<SCEVAddRecExpr>(S))
11156         LoopsUsed.insert(AR->getLoop());
11157       return true;
11158     }
11159 
11160     bool isDone() const { return false; }
11161   };
11162 
11163   FindUsedLoops F;
11164   SCEVTraversal<FindUsedLoops>(F).visitAll(S);
11165 
11166   for (auto *L : F.LoopsUsed)
11167     LoopUsers[L].push_back(S);
11168 }
11169 
11170 void ScalarEvolution::verify() const {
11171   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
11172   ScalarEvolution SE2(F, TLI, AC, DT, LI);
11173 
11174   SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end());
11175 
11176   // Map's SCEV expressions from one ScalarEvolution "universe" to another.
11177   struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> {
11178     SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {}
11179 
11180     const SCEV *visitConstant(const SCEVConstant *Constant) {
11181       return SE.getConstant(Constant->getAPInt());
11182     }
11183 
11184     const SCEV *visitUnknown(const SCEVUnknown *Expr) {
11185       return SE.getUnknown(Expr->getValue());
11186     }
11187 
11188     const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
11189       return SE.getCouldNotCompute();
11190     }
11191   };
11192 
11193   SCEVMapper SCM(SE2);
11194 
11195   while (!LoopStack.empty()) {
11196     auto *L = LoopStack.pop_back_val();
11197     LoopStack.insert(LoopStack.end(), L->begin(), L->end());
11198 
11199     auto *CurBECount = SCM.visit(
11200         const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L));
11201     auto *NewBECount = SE2.getBackedgeTakenCount(L);
11202 
11203     if (CurBECount == SE2.getCouldNotCompute() ||
11204         NewBECount == SE2.getCouldNotCompute()) {
11205       // NB! This situation is legal, but is very suspicious -- whatever pass
11206       // change the loop to make a trip count go from could not compute to
11207       // computable or vice-versa *should have* invalidated SCEV.  However, we
11208       // choose not to assert here (for now) since we don't want false
11209       // positives.
11210       continue;
11211     }
11212 
11213     if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) {
11214       // SCEV treats "undef" as an unknown but consistent value (i.e. it does
11215       // not propagate undef aggressively).  This means we can (and do) fail
11216       // verification in cases where a transform makes the trip count of a loop
11217       // go from "undef" to "undef+1" (say).  The transform is fine, since in
11218       // both cases the loop iterates "undef" times, but SCEV thinks we
11219       // increased the trip count of the loop by 1 incorrectly.
11220       continue;
11221     }
11222 
11223     if (SE.getTypeSizeInBits(CurBECount->getType()) >
11224         SE.getTypeSizeInBits(NewBECount->getType()))
11225       NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType());
11226     else if (SE.getTypeSizeInBits(CurBECount->getType()) <
11227              SE.getTypeSizeInBits(NewBECount->getType()))
11228       CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType());
11229 
11230     auto *ConstantDelta =
11231         dyn_cast<SCEVConstant>(SE2.getMinusSCEV(CurBECount, NewBECount));
11232 
11233     if (ConstantDelta && ConstantDelta->getAPInt() != 0) {
11234       dbgs() << "Trip Count Changed!\n";
11235       dbgs() << "Old: " << *CurBECount << "\n";
11236       dbgs() << "New: " << *NewBECount << "\n";
11237       dbgs() << "Delta: " << *ConstantDelta << "\n";
11238       std::abort();
11239     }
11240   }
11241 }
11242 
11243 bool ScalarEvolution::invalidate(
11244     Function &F, const PreservedAnalyses &PA,
11245     FunctionAnalysisManager::Invalidator &Inv) {
11246   // Invalidate the ScalarEvolution object whenever it isn't preserved or one
11247   // of its dependencies is invalidated.
11248   auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
11249   return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
11250          Inv.invalidate<AssumptionAnalysis>(F, PA) ||
11251          Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
11252          Inv.invalidate<LoopAnalysis>(F, PA);
11253 }
11254 
11255 AnalysisKey ScalarEvolutionAnalysis::Key;
11256 
11257 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
11258                                              FunctionAnalysisManager &AM) {
11259   return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F),
11260                          AM.getResult<AssumptionAnalysis>(F),
11261                          AM.getResult<DominatorTreeAnalysis>(F),
11262                          AM.getResult<LoopAnalysis>(F));
11263 }
11264 
11265 PreservedAnalyses
11266 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
11267   AM.getResult<ScalarEvolutionAnalysis>(F).print(OS);
11268   return PreservedAnalyses::all();
11269 }
11270 
11271 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
11272                       "Scalar Evolution Analysis", false, true)
11273 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
11274 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
11275 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
11276 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
11277 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
11278                     "Scalar Evolution Analysis", false, true)
11279 
11280 char ScalarEvolutionWrapperPass::ID = 0;
11281 
11282 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
11283   initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
11284 }
11285 
11286 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
11287   SE.reset(new ScalarEvolution(
11288       F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
11289       getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
11290       getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
11291       getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
11292   return false;
11293 }
11294 
11295 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
11296 
11297 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
11298   SE->print(OS);
11299 }
11300 
11301 void ScalarEvolutionWrapperPass::verifyAnalysis() const {
11302   if (!VerifySCEV)
11303     return;
11304 
11305   SE->verify();
11306 }
11307 
11308 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
11309   AU.setPreservesAll();
11310   AU.addRequiredTransitive<AssumptionCacheTracker>();
11311   AU.addRequiredTransitive<LoopInfoWrapperPass>();
11312   AU.addRequiredTransitive<DominatorTreeWrapperPass>();
11313   AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
11314 }
11315 
11316 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS,
11317                                                         const SCEV *RHS) {
11318   FoldingSetNodeID ID;
11319   assert(LHS->getType() == RHS->getType() &&
11320          "Type mismatch between LHS and RHS");
11321   // Unique this node based on the arguments
11322   ID.AddInteger(SCEVPredicate::P_Equal);
11323   ID.AddPointer(LHS);
11324   ID.AddPointer(RHS);
11325   void *IP = nullptr;
11326   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
11327     return S;
11328   SCEVEqualPredicate *Eq = new (SCEVAllocator)
11329       SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS);
11330   UniquePreds.InsertNode(Eq, IP);
11331   return Eq;
11332 }
11333 
11334 const SCEVPredicate *ScalarEvolution::getWrapPredicate(
11335     const SCEVAddRecExpr *AR,
11336     SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
11337   FoldingSetNodeID ID;
11338   // Unique this node based on the arguments
11339   ID.AddInteger(SCEVPredicate::P_Wrap);
11340   ID.AddPointer(AR);
11341   ID.AddInteger(AddedFlags);
11342   void *IP = nullptr;
11343   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
11344     return S;
11345   auto *OF = new (SCEVAllocator)
11346       SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
11347   UniquePreds.InsertNode(OF, IP);
11348   return OF;
11349 }
11350 
11351 namespace {
11352 
11353 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
11354 public:
11355 
11356   /// Rewrites \p S in the context of a loop L and the SCEV predication
11357   /// infrastructure.
11358   ///
11359   /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
11360   /// equivalences present in \p Pred.
11361   ///
11362   /// If \p NewPreds is non-null, rewrite is free to add further predicates to
11363   /// \p NewPreds such that the result will be an AddRecExpr.
11364   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
11365                              SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
11366                              SCEVUnionPredicate *Pred) {
11367     SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
11368     return Rewriter.visit(S);
11369   }
11370 
11371   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
11372     if (Pred) {
11373       auto ExprPreds = Pred->getPredicatesForExpr(Expr);
11374       for (auto *Pred : ExprPreds)
11375         if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred))
11376           if (IPred->getLHS() == Expr)
11377             return IPred->getRHS();
11378     }
11379     return convertToAddRecWithPreds(Expr);
11380   }
11381 
11382   const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
11383     const SCEV *Operand = visit(Expr->getOperand());
11384     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
11385     if (AR && AR->getLoop() == L && AR->isAffine()) {
11386       // This couldn't be folded because the operand didn't have the nuw
11387       // flag. Add the nusw flag as an assumption that we could make.
11388       const SCEV *Step = AR->getStepRecurrence(SE);
11389       Type *Ty = Expr->getType();
11390       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
11391         return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
11392                                 SE.getSignExtendExpr(Step, Ty), L,
11393                                 AR->getNoWrapFlags());
11394     }
11395     return SE.getZeroExtendExpr(Operand, Expr->getType());
11396   }
11397 
11398   const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
11399     const SCEV *Operand = visit(Expr->getOperand());
11400     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
11401     if (AR && AR->getLoop() == L && AR->isAffine()) {
11402       // This couldn't be folded because the operand didn't have the nsw
11403       // flag. Add the nssw flag as an assumption that we could make.
11404       const SCEV *Step = AR->getStepRecurrence(SE);
11405       Type *Ty = Expr->getType();
11406       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
11407         return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
11408                                 SE.getSignExtendExpr(Step, Ty), L,
11409                                 AR->getNoWrapFlags());
11410     }
11411     return SE.getSignExtendExpr(Operand, Expr->getType());
11412   }
11413 
11414 private:
11415   explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE,
11416                         SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
11417                         SCEVUnionPredicate *Pred)
11418       : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
11419 
11420   bool addOverflowAssumption(const SCEVPredicate *P) {
11421     if (!NewPreds) {
11422       // Check if we've already made this assumption.
11423       return Pred && Pred->implies(P);
11424     }
11425     NewPreds->insert(P);
11426     return true;
11427   }
11428 
11429   bool addOverflowAssumption(const SCEVAddRecExpr *AR,
11430                              SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
11431     auto *A = SE.getWrapPredicate(AR, AddedFlags);
11432     return addOverflowAssumption(A);
11433   }
11434 
11435   // If \p Expr represents a PHINode, we try to see if it can be represented
11436   // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible
11437   // to add this predicate as a runtime overflow check, we return the AddRec.
11438   // If \p Expr does not meet these conditions (is not a PHI node, or we
11439   // couldn't create an AddRec for it, or couldn't add the predicate), we just
11440   // return \p Expr.
11441   const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) {
11442     if (!isa<PHINode>(Expr->getValue()))
11443       return Expr;
11444     Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
11445     PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr);
11446     if (!PredicatedRewrite)
11447       return Expr;
11448     for (auto *P : PredicatedRewrite->second){
11449       if (!addOverflowAssumption(P))
11450         return Expr;
11451     }
11452     return PredicatedRewrite->first;
11453   }
11454 
11455   SmallPtrSetImpl<const SCEVPredicate *> *NewPreds;
11456   SCEVUnionPredicate *Pred;
11457   const Loop *L;
11458 };
11459 
11460 } // end anonymous namespace
11461 
11462 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
11463                                                    SCEVUnionPredicate &Preds) {
11464   return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
11465 }
11466 
11467 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates(
11468     const SCEV *S, const Loop *L,
11469     SmallPtrSetImpl<const SCEVPredicate *> &Preds) {
11470   SmallPtrSet<const SCEVPredicate *, 4> TransformPreds;
11471   S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
11472   auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
11473 
11474   if (!AddRec)
11475     return nullptr;
11476 
11477   // Since the transformation was successful, we can now transfer the SCEV
11478   // predicates.
11479   for (auto *P : TransformPreds)
11480     Preds.insert(P);
11481 
11482   return AddRec;
11483 }
11484 
11485 /// SCEV predicates
11486 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
11487                              SCEVPredicateKind Kind)
11488     : FastID(ID), Kind(Kind) {}
11489 
11490 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID,
11491                                        const SCEV *LHS, const SCEV *RHS)
11492     : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {
11493   assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match");
11494   assert(LHS != RHS && "LHS and RHS are the same SCEV");
11495 }
11496 
11497 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const {
11498   const auto *Op = dyn_cast<SCEVEqualPredicate>(N);
11499 
11500   if (!Op)
11501     return false;
11502 
11503   return Op->LHS == LHS && Op->RHS == RHS;
11504 }
11505 
11506 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; }
11507 
11508 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; }
11509 
11510 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const {
11511   OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
11512 }
11513 
11514 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
11515                                      const SCEVAddRecExpr *AR,
11516                                      IncrementWrapFlags Flags)
11517     : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
11518 
11519 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; }
11520 
11521 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const {
11522   const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
11523 
11524   return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags;
11525 }
11526 
11527 bool SCEVWrapPredicate::isAlwaysTrue() const {
11528   SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
11529   IncrementWrapFlags IFlags = Flags;
11530 
11531   if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
11532     IFlags = clearFlags(IFlags, IncrementNSSW);
11533 
11534   return IFlags == IncrementAnyWrap;
11535 }
11536 
11537 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
11538   OS.indent(Depth) << *getExpr() << " Added Flags: ";
11539   if (SCEVWrapPredicate::IncrementNUSW & getFlags())
11540     OS << "<nusw>";
11541   if (SCEVWrapPredicate::IncrementNSSW & getFlags())
11542     OS << "<nssw>";
11543   OS << "\n";
11544 }
11545 
11546 SCEVWrapPredicate::IncrementWrapFlags
11547 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR,
11548                                    ScalarEvolution &SE) {
11549   IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
11550   SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
11551 
11552   // We can safely transfer the NSW flag as NSSW.
11553   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
11554     ImpliedFlags = IncrementNSSW;
11555 
11556   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
11557     // If the increment is positive, the SCEV NUW flag will also imply the
11558     // WrapPredicate NUSW flag.
11559     if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
11560       if (Step->getValue()->getValue().isNonNegative())
11561         ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
11562   }
11563 
11564   return ImpliedFlags;
11565 }
11566 
11567 /// Union predicates don't get cached so create a dummy set ID for it.
11568 SCEVUnionPredicate::SCEVUnionPredicate()
11569     : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {}
11570 
11571 bool SCEVUnionPredicate::isAlwaysTrue() const {
11572   return all_of(Preds,
11573                 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
11574 }
11575 
11576 ArrayRef<const SCEVPredicate *>
11577 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) {
11578   auto I = SCEVToPreds.find(Expr);
11579   if (I == SCEVToPreds.end())
11580     return ArrayRef<const SCEVPredicate *>();
11581   return I->second;
11582 }
11583 
11584 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
11585   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
11586     return all_of(Set->Preds,
11587                   [this](const SCEVPredicate *I) { return this->implies(I); });
11588 
11589   auto ScevPredsIt = SCEVToPreds.find(N->getExpr());
11590   if (ScevPredsIt == SCEVToPreds.end())
11591     return false;
11592   auto &SCEVPreds = ScevPredsIt->second;
11593 
11594   return any_of(SCEVPreds,
11595                 [N](const SCEVPredicate *I) { return I->implies(N); });
11596 }
11597 
11598 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; }
11599 
11600 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
11601   for (auto Pred : Preds)
11602     Pred->print(OS, Depth);
11603 }
11604 
11605 void SCEVUnionPredicate::add(const SCEVPredicate *N) {
11606   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
11607     for (auto Pred : Set->Preds)
11608       add(Pred);
11609     return;
11610   }
11611 
11612   if (implies(N))
11613     return;
11614 
11615   const SCEV *Key = N->getExpr();
11616   assert(Key && "Only SCEVUnionPredicate doesn't have an "
11617                 " associated expression!");
11618 
11619   SCEVToPreds[Key].push_back(N);
11620   Preds.push_back(N);
11621 }
11622 
11623 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
11624                                                      Loop &L)
11625     : SE(SE), L(L) {}
11626 
11627 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
11628   const SCEV *Expr = SE.getSCEV(V);
11629   RewriteEntry &Entry = RewriteMap[Expr];
11630 
11631   // If we already have an entry and the version matches, return it.
11632   if (Entry.second && Generation == Entry.first)
11633     return Entry.second;
11634 
11635   // We found an entry but it's stale. Rewrite the stale entry
11636   // according to the current predicate.
11637   if (Entry.second)
11638     Expr = Entry.second;
11639 
11640   const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds);
11641   Entry = {Generation, NewSCEV};
11642 
11643   return NewSCEV;
11644 }
11645 
11646 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() {
11647   if (!BackedgeCount) {
11648     SCEVUnionPredicate BackedgePred;
11649     BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred);
11650     addPredicate(BackedgePred);
11651   }
11652   return BackedgeCount;
11653 }
11654 
11655 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
11656   if (Preds.implies(&Pred))
11657     return;
11658   Preds.add(&Pred);
11659   updateGeneration();
11660 }
11661 
11662 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const {
11663   return Preds;
11664 }
11665 
11666 void PredicatedScalarEvolution::updateGeneration() {
11667   // If the generation number wrapped recompute everything.
11668   if (++Generation == 0) {
11669     for (auto &II : RewriteMap) {
11670       const SCEV *Rewritten = II.second.second;
11671       II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)};
11672     }
11673   }
11674 }
11675 
11676 void PredicatedScalarEvolution::setNoOverflow(
11677     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
11678   const SCEV *Expr = getSCEV(V);
11679   const auto *AR = cast<SCEVAddRecExpr>(Expr);
11680 
11681   auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE);
11682 
11683   // Clear the statically implied flags.
11684   Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags);
11685   addPredicate(*SE.getWrapPredicate(AR, Flags));
11686 
11687   auto II = FlagsMap.insert({V, Flags});
11688   if (!II.second)
11689     II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second);
11690 }
11691 
11692 bool PredicatedScalarEvolution::hasNoOverflow(
11693     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
11694   const SCEV *Expr = getSCEV(V);
11695   const auto *AR = cast<SCEVAddRecExpr>(Expr);
11696 
11697   Flags = SCEVWrapPredicate::clearFlags(
11698       Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
11699 
11700   auto II = FlagsMap.find(V);
11701 
11702   if (II != FlagsMap.end())
11703     Flags = SCEVWrapPredicate::clearFlags(Flags, II->second);
11704 
11705   return Flags == SCEVWrapPredicate::IncrementAnyWrap;
11706 }
11707 
11708 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) {
11709   const SCEV *Expr = this->getSCEV(V);
11710   SmallPtrSet<const SCEVPredicate *, 4> NewPreds;
11711   auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
11712 
11713   if (!New)
11714     return nullptr;
11715 
11716   for (auto *P : NewPreds)
11717     Preds.add(P);
11718 
11719   updateGeneration();
11720   RewriteMap[SE.getSCEV(V)] = {Generation, New};
11721   return New;
11722 }
11723 
11724 PredicatedScalarEvolution::PredicatedScalarEvolution(
11725     const PredicatedScalarEvolution &Init)
11726     : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds),
11727       Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
11728   for (const auto &I : Init.FlagsMap)
11729     FlagsMap.insert(I);
11730 }
11731 
11732 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const {
11733   // For each block.
11734   for (auto *BB : L.getBlocks())
11735     for (auto &I : *BB) {
11736       if (!SE.isSCEVable(I.getType()))
11737         continue;
11738 
11739       auto *Expr = SE.getSCEV(&I);
11740       auto II = RewriteMap.find(Expr);
11741 
11742       if (II == RewriteMap.end())
11743         continue;
11744 
11745       // Don't print things that are not interesting.
11746       if (II->second.second == Expr)
11747         continue;
11748 
11749       OS.indent(Depth) << "[PSE]" << I << ":\n";
11750       OS.indent(Depth + 2) << *Expr << "\n";
11751       OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
11752     }
11753 }
11754