1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains the implementation of the scalar evolution analysis
10 // engine, which is used primarily to analyze expressions involving induction
11 // variables in loops.
12 //
13 // There are several aspects to this library.  First is the representation of
14 // scalar expressions, which are represented as subclasses of the SCEV class.
15 // These classes are used to represent certain types of subexpressions that we
16 // can handle. We only create one SCEV of a particular shape, so
17 // pointer-comparisons for equality are legal.
18 //
19 // One important aspect of the SCEV objects is that they are never cyclic, even
20 // if there is a cycle in the dataflow for an expression (ie, a PHI node).  If
21 // the PHI node is one of the idioms that we can represent (e.g., a polynomial
22 // recurrence) then we represent it directly as a recurrence node, otherwise we
23 // represent it as a SCEVUnknown node.
24 //
25 // In addition to being able to represent expressions of various types, we also
26 // have folders that are used to build the *canonical* representation for a
27 // particular expression.  These folders are capable of using a variety of
28 // rewrite rules to simplify the expressions.
29 //
30 // Once the folders are defined, we can implement the more interesting
31 // higher-level code, such as the code that recognizes PHI nodes of various
32 // types, computes the execution count of a loop, etc.
33 //
34 // TODO: We should use these routines and value representations to implement
35 // dependence analysis!
36 //
37 //===----------------------------------------------------------------------===//
38 //
39 // There are several good references for the techniques used in this analysis.
40 //
41 //  Chains of recurrences -- a method to expedite the evaluation
42 //  of closed-form functions
43 //  Olaf Bachmann, Paul S. Wang, Eugene V. Zima
44 //
45 //  On computational properties of chains of recurrences
46 //  Eugene V. Zima
47 //
48 //  Symbolic Evaluation of Chains of Recurrences for Loop Optimization
49 //  Robert A. van Engelen
50 //
51 //  Efficient Symbolic Analysis for Optimizing Compilers
52 //  Robert A. van Engelen
53 //
54 //  Using the chains of recurrences algebra for data dependence testing and
55 //  induction variable substitution
56 //  MS Thesis, Johnie Birch
57 //
58 //===----------------------------------------------------------------------===//
59 
60 #include "llvm/Analysis/ScalarEvolution.h"
61 #include "llvm/ADT/APInt.h"
62 #include "llvm/ADT/ArrayRef.h"
63 #include "llvm/ADT/DenseMap.h"
64 #include "llvm/ADT/DepthFirstIterator.h"
65 #include "llvm/ADT/EquivalenceClasses.h"
66 #include "llvm/ADT/FoldingSet.h"
67 #include "llvm/ADT/None.h"
68 #include "llvm/ADT/Optional.h"
69 #include "llvm/ADT/STLExtras.h"
70 #include "llvm/ADT/ScopeExit.h"
71 #include "llvm/ADT/Sequence.h"
72 #include "llvm/ADT/SetVector.h"
73 #include "llvm/ADT/SmallPtrSet.h"
74 #include "llvm/ADT/SmallSet.h"
75 #include "llvm/ADT/SmallVector.h"
76 #include "llvm/ADT/Statistic.h"
77 #include "llvm/ADT/StringRef.h"
78 #include "llvm/Analysis/AssumptionCache.h"
79 #include "llvm/Analysis/ConstantFolding.h"
80 #include "llvm/Analysis/InstructionSimplify.h"
81 #include "llvm/Analysis/LoopInfo.h"
82 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
83 #include "llvm/Analysis/TargetLibraryInfo.h"
84 #include "llvm/Analysis/ValueTracking.h"
85 #include "llvm/Config/llvm-config.h"
86 #include "llvm/IR/Argument.h"
87 #include "llvm/IR/BasicBlock.h"
88 #include "llvm/IR/CFG.h"
89 #include "llvm/IR/Constant.h"
90 #include "llvm/IR/ConstantRange.h"
91 #include "llvm/IR/Constants.h"
92 #include "llvm/IR/DataLayout.h"
93 #include "llvm/IR/DerivedTypes.h"
94 #include "llvm/IR/Dominators.h"
95 #include "llvm/IR/Function.h"
96 #include "llvm/IR/GlobalAlias.h"
97 #include "llvm/IR/GlobalValue.h"
98 #include "llvm/IR/InstIterator.h"
99 #include "llvm/IR/InstrTypes.h"
100 #include "llvm/IR/Instruction.h"
101 #include "llvm/IR/Instructions.h"
102 #include "llvm/IR/IntrinsicInst.h"
103 #include "llvm/IR/Intrinsics.h"
104 #include "llvm/IR/LLVMContext.h"
105 #include "llvm/IR/Operator.h"
106 #include "llvm/IR/PatternMatch.h"
107 #include "llvm/IR/Type.h"
108 #include "llvm/IR/Use.h"
109 #include "llvm/IR/User.h"
110 #include "llvm/IR/Value.h"
111 #include "llvm/IR/Verifier.h"
112 #include "llvm/InitializePasses.h"
113 #include "llvm/Pass.h"
114 #include "llvm/Support/Casting.h"
115 #include "llvm/Support/CommandLine.h"
116 #include "llvm/Support/Compiler.h"
117 #include "llvm/Support/Debug.h"
118 #include "llvm/Support/ErrorHandling.h"
119 #include "llvm/Support/KnownBits.h"
120 #include "llvm/Support/SaveAndRestore.h"
121 #include "llvm/Support/raw_ostream.h"
122 #include <algorithm>
123 #include <cassert>
124 #include <climits>
125 #include <cstdint>
126 #include <cstdlib>
127 #include <map>
128 #include <memory>
129 #include <tuple>
130 #include <utility>
131 #include <vector>
132 
133 using namespace llvm;
134 using namespace PatternMatch;
135 
136 #define DEBUG_TYPE "scalar-evolution"
137 
138 STATISTIC(NumTripCountsComputed,
139           "Number of loops with predictable loop counts");
140 STATISTIC(NumTripCountsNotComputed,
141           "Number of loops without predictable loop counts");
142 STATISTIC(NumBruteForceTripCountsComputed,
143           "Number of loops with trip counts computed by force");
144 
145 #ifdef EXPENSIVE_CHECKS
146 bool llvm::VerifySCEV = true;
147 #else
148 bool llvm::VerifySCEV = false;
149 #endif
150 
151 static cl::opt<unsigned>
152 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
153                         cl::ZeroOrMore,
154                         cl::desc("Maximum number of iterations SCEV will "
155                                  "symbolically execute a constant "
156                                  "derived loop"),
157                         cl::init(100));
158 
159 static cl::opt<bool, true> VerifySCEVOpt(
160     "verify-scev", cl::Hidden, cl::location(VerifySCEV),
161     cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
162 static cl::opt<bool> VerifySCEVStrict(
163     "verify-scev-strict", cl::Hidden,
164     cl::desc("Enable stricter verification with -verify-scev is passed"));
165 static cl::opt<bool>
166     VerifySCEVMap("verify-scev-maps", cl::Hidden,
167                   cl::desc("Verify no dangling value in ScalarEvolution's "
168                            "ExprValueMap (slow)"));
169 
170 static cl::opt<bool> VerifyIR(
171     "scev-verify-ir", cl::Hidden,
172     cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"),
173     cl::init(false));
174 
175 static cl::opt<unsigned> MulOpsInlineThreshold(
176     "scev-mulops-inline-threshold", cl::Hidden,
177     cl::desc("Threshold for inlining multiplication operands into a SCEV"),
178     cl::init(32));
179 
180 static cl::opt<unsigned> AddOpsInlineThreshold(
181     "scev-addops-inline-threshold", cl::Hidden,
182     cl::desc("Threshold for inlining addition operands into a SCEV"),
183     cl::init(500));
184 
185 static cl::opt<unsigned> MaxSCEVCompareDepth(
186     "scalar-evolution-max-scev-compare-depth", cl::Hidden,
187     cl::desc("Maximum depth of recursive SCEV complexity comparisons"),
188     cl::init(32));
189 
190 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth(
191     "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden,
192     cl::desc("Maximum depth of recursive SCEV operations implication analysis"),
193     cl::init(2));
194 
195 static cl::opt<unsigned> MaxValueCompareDepth(
196     "scalar-evolution-max-value-compare-depth", cl::Hidden,
197     cl::desc("Maximum depth of recursive value complexity comparisons"),
198     cl::init(2));
199 
200 static cl::opt<unsigned>
201     MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden,
202                   cl::desc("Maximum depth of recursive arithmetics"),
203                   cl::init(32));
204 
205 static cl::opt<unsigned> MaxConstantEvolvingDepth(
206     "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
207     cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
208 
209 static cl::opt<unsigned>
210     MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden,
211                  cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"),
212                  cl::init(8));
213 
214 static cl::opt<unsigned>
215     MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden,
216                   cl::desc("Max coefficients in AddRec during evolving"),
217                   cl::init(8));
218 
219 static cl::opt<unsigned>
220     HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden,
221                   cl::desc("Size of the expression which is considered huge"),
222                   cl::init(4096));
223 
224 static cl::opt<bool>
225 ClassifyExpressions("scalar-evolution-classify-expressions",
226     cl::Hidden, cl::init(true),
227     cl::desc("When printing analysis, include information on every instruction"));
228 
229 static cl::opt<bool> UseExpensiveRangeSharpening(
230     "scalar-evolution-use-expensive-range-sharpening", cl::Hidden,
231     cl::init(false),
232     cl::desc("Use more powerful methods of sharpening expression ranges. May "
233              "be costly in terms of compile time"));
234 
235 static cl::opt<unsigned> MaxPhiSCCAnalysisSize(
236     "scalar-evolution-max-scc-analysis-depth", cl::Hidden,
237     cl::desc("Maximum amount of nodes to process while searching SCEVUnknown "
238              "Phi strongly connected components"),
239     cl::init(8));
240 
241 static cl::opt<bool>
242     EnableFiniteLoopControl("scalar-evolution-finite-loop", cl::Hidden,
243                             cl::desc("Handle <= and >= in finite loops"),
244                             cl::init(true));
245 
246 //===----------------------------------------------------------------------===//
247 //                           SCEV class definitions
248 //===----------------------------------------------------------------------===//
249 
250 //===----------------------------------------------------------------------===//
251 // Implementation of the SCEV class.
252 //
253 
254 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
255 LLVM_DUMP_METHOD void SCEV::dump() const {
256   print(dbgs());
257   dbgs() << '\n';
258 }
259 #endif
260 
261 void SCEV::print(raw_ostream &OS) const {
262   switch (getSCEVType()) {
263   case scConstant:
264     cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
265     return;
266   case scPtrToInt: {
267     const SCEVPtrToIntExpr *PtrToInt = cast<SCEVPtrToIntExpr>(this);
268     const SCEV *Op = PtrToInt->getOperand();
269     OS << "(ptrtoint " << *Op->getType() << " " << *Op << " to "
270        << *PtrToInt->getType() << ")";
271     return;
272   }
273   case scTruncate: {
274     const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
275     const SCEV *Op = Trunc->getOperand();
276     OS << "(trunc " << *Op->getType() << " " << *Op << " to "
277        << *Trunc->getType() << ")";
278     return;
279   }
280   case scZeroExtend: {
281     const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
282     const SCEV *Op = ZExt->getOperand();
283     OS << "(zext " << *Op->getType() << " " << *Op << " to "
284        << *ZExt->getType() << ")";
285     return;
286   }
287   case scSignExtend: {
288     const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
289     const SCEV *Op = SExt->getOperand();
290     OS << "(sext " << *Op->getType() << " " << *Op << " to "
291        << *SExt->getType() << ")";
292     return;
293   }
294   case scAddRecExpr: {
295     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
296     OS << "{" << *AR->getOperand(0);
297     for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
298       OS << ",+," << *AR->getOperand(i);
299     OS << "}<";
300     if (AR->hasNoUnsignedWrap())
301       OS << "nuw><";
302     if (AR->hasNoSignedWrap())
303       OS << "nsw><";
304     if (AR->hasNoSelfWrap() &&
305         !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
306       OS << "nw><";
307     AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
308     OS << ">";
309     return;
310   }
311   case scAddExpr:
312   case scMulExpr:
313   case scUMaxExpr:
314   case scSMaxExpr:
315   case scUMinExpr:
316   case scSMinExpr:
317   case scSequentialUMinExpr: {
318     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
319     const char *OpStr = nullptr;
320     switch (NAry->getSCEVType()) {
321     case scAddExpr: OpStr = " + "; break;
322     case scMulExpr: OpStr = " * "; break;
323     case scUMaxExpr: OpStr = " umax "; break;
324     case scSMaxExpr: OpStr = " smax "; break;
325     case scUMinExpr:
326       OpStr = " umin ";
327       break;
328     case scSMinExpr:
329       OpStr = " smin ";
330       break;
331     case scSequentialUMinExpr:
332       OpStr = " umin_seq ";
333       break;
334     default:
335       llvm_unreachable("There are no other nary expression types.");
336     }
337     OS << "(";
338     ListSeparator LS(OpStr);
339     for (const SCEV *Op : NAry->operands())
340       OS << LS << *Op;
341     OS << ")";
342     switch (NAry->getSCEVType()) {
343     case scAddExpr:
344     case scMulExpr:
345       if (NAry->hasNoUnsignedWrap())
346         OS << "<nuw>";
347       if (NAry->hasNoSignedWrap())
348         OS << "<nsw>";
349       break;
350     default:
351       // Nothing to print for other nary expressions.
352       break;
353     }
354     return;
355   }
356   case scUDivExpr: {
357     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
358     OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
359     return;
360   }
361   case scUnknown: {
362     const SCEVUnknown *U = cast<SCEVUnknown>(this);
363     Type *AllocTy;
364     if (U->isSizeOf(AllocTy)) {
365       OS << "sizeof(" << *AllocTy << ")";
366       return;
367     }
368     if (U->isAlignOf(AllocTy)) {
369       OS << "alignof(" << *AllocTy << ")";
370       return;
371     }
372 
373     Type *CTy;
374     Constant *FieldNo;
375     if (U->isOffsetOf(CTy, FieldNo)) {
376       OS << "offsetof(" << *CTy << ", ";
377       FieldNo->printAsOperand(OS, false);
378       OS << ")";
379       return;
380     }
381 
382     // Otherwise just print it normally.
383     U->getValue()->printAsOperand(OS, false);
384     return;
385   }
386   case scCouldNotCompute:
387     OS << "***COULDNOTCOMPUTE***";
388     return;
389   }
390   llvm_unreachable("Unknown SCEV kind!");
391 }
392 
393 Type *SCEV::getType() const {
394   switch (getSCEVType()) {
395   case scConstant:
396     return cast<SCEVConstant>(this)->getType();
397   case scPtrToInt:
398   case scTruncate:
399   case scZeroExtend:
400   case scSignExtend:
401     return cast<SCEVCastExpr>(this)->getType();
402   case scAddRecExpr:
403     return cast<SCEVAddRecExpr>(this)->getType();
404   case scMulExpr:
405     return cast<SCEVMulExpr>(this)->getType();
406   case scUMaxExpr:
407   case scSMaxExpr:
408   case scUMinExpr:
409   case scSMinExpr:
410     return cast<SCEVMinMaxExpr>(this)->getType();
411   case scSequentialUMinExpr:
412     return cast<SCEVSequentialMinMaxExpr>(this)->getType();
413   case scAddExpr:
414     return cast<SCEVAddExpr>(this)->getType();
415   case scUDivExpr:
416     return cast<SCEVUDivExpr>(this)->getType();
417   case scUnknown:
418     return cast<SCEVUnknown>(this)->getType();
419   case scCouldNotCompute:
420     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
421   }
422   llvm_unreachable("Unknown SCEV kind!");
423 }
424 
425 bool SCEV::isZero() const {
426   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
427     return SC->getValue()->isZero();
428   return false;
429 }
430 
431 bool SCEV::isOne() const {
432   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
433     return SC->getValue()->isOne();
434   return false;
435 }
436 
437 bool SCEV::isAllOnesValue() const {
438   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
439     return SC->getValue()->isMinusOne();
440   return false;
441 }
442 
443 bool SCEV::isNonConstantNegative() const {
444   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
445   if (!Mul) return false;
446 
447   // If there is a constant factor, it will be first.
448   const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
449   if (!SC) return false;
450 
451   // Return true if the value is negative, this matches things like (-42 * V).
452   return SC->getAPInt().isNegative();
453 }
454 
455 SCEVCouldNotCompute::SCEVCouldNotCompute() :
456   SCEV(FoldingSetNodeIDRef(), scCouldNotCompute, 0) {}
457 
458 bool SCEVCouldNotCompute::classof(const SCEV *S) {
459   return S->getSCEVType() == scCouldNotCompute;
460 }
461 
462 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
463   FoldingSetNodeID ID;
464   ID.AddInteger(scConstant);
465   ID.AddPointer(V);
466   void *IP = nullptr;
467   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
468   SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
469   UniqueSCEVs.InsertNode(S, IP);
470   return S;
471 }
472 
473 const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
474   return getConstant(ConstantInt::get(getContext(), Val));
475 }
476 
477 const SCEV *
478 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
479   IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
480   return getConstant(ConstantInt::get(ITy, V, isSigned));
481 }
482 
483 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy,
484                            const SCEV *op, Type *ty)
485     : SCEV(ID, SCEVTy, computeExpressionSize(op)), Ty(ty) {
486   Operands[0] = op;
487 }
488 
489 SCEVPtrToIntExpr::SCEVPtrToIntExpr(const FoldingSetNodeIDRef ID, const SCEV *Op,
490                                    Type *ITy)
491     : SCEVCastExpr(ID, scPtrToInt, Op, ITy) {
492   assert(getOperand()->getType()->isPointerTy() && Ty->isIntegerTy() &&
493          "Must be a non-bit-width-changing pointer-to-integer cast!");
494 }
495 
496 SCEVIntegralCastExpr::SCEVIntegralCastExpr(const FoldingSetNodeIDRef ID,
497                                            SCEVTypes SCEVTy, const SCEV *op,
498                                            Type *ty)
499     : SCEVCastExpr(ID, SCEVTy, op, ty) {}
500 
501 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, const SCEV *op,
502                                    Type *ty)
503     : SCEVIntegralCastExpr(ID, scTruncate, op, ty) {
504   assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
505          "Cannot truncate non-integer value!");
506 }
507 
508 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
509                                        const SCEV *op, Type *ty)
510     : SCEVIntegralCastExpr(ID, scZeroExtend, op, ty) {
511   assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
512          "Cannot zero extend non-integer value!");
513 }
514 
515 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
516                                        const SCEV *op, Type *ty)
517     : SCEVIntegralCastExpr(ID, scSignExtend, op, ty) {
518   assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
519          "Cannot sign extend non-integer value!");
520 }
521 
522 void SCEVUnknown::deleted() {
523   // Clear this SCEVUnknown from various maps.
524   SE->forgetMemoizedResults(this);
525 
526   // Remove this SCEVUnknown from the uniquing map.
527   SE->UniqueSCEVs.RemoveNode(this);
528 
529   // Release the value.
530   setValPtr(nullptr);
531 }
532 
533 void SCEVUnknown::allUsesReplacedWith(Value *New) {
534   // Clear this SCEVUnknown from various maps.
535   SE->forgetMemoizedResults(this);
536 
537   // Remove this SCEVUnknown from the uniquing map.
538   SE->UniqueSCEVs.RemoveNode(this);
539 
540   // Replace the value pointer in case someone is still using this SCEVUnknown.
541   setValPtr(New);
542 }
543 
544 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
545   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
546     if (VCE->getOpcode() == Instruction::PtrToInt)
547       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
548         if (CE->getOpcode() == Instruction::GetElementPtr &&
549             CE->getOperand(0)->isNullValue() &&
550             CE->getNumOperands() == 2)
551           if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
552             if (CI->isOne()) {
553               AllocTy = cast<GEPOperator>(CE)->getSourceElementType();
554               return true;
555             }
556 
557   return false;
558 }
559 
560 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
561   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
562     if (VCE->getOpcode() == Instruction::PtrToInt)
563       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
564         if (CE->getOpcode() == Instruction::GetElementPtr &&
565             CE->getOperand(0)->isNullValue()) {
566           Type *Ty = cast<GEPOperator>(CE)->getSourceElementType();
567           if (StructType *STy = dyn_cast<StructType>(Ty))
568             if (!STy->isPacked() &&
569                 CE->getNumOperands() == 3 &&
570                 CE->getOperand(1)->isNullValue()) {
571               if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
572                 if (CI->isOne() &&
573                     STy->getNumElements() == 2 &&
574                     STy->getElementType(0)->isIntegerTy(1)) {
575                   AllocTy = STy->getElementType(1);
576                   return true;
577                 }
578             }
579         }
580 
581   return false;
582 }
583 
584 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
585   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
586     if (VCE->getOpcode() == Instruction::PtrToInt)
587       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
588         if (CE->getOpcode() == Instruction::GetElementPtr &&
589             CE->getNumOperands() == 3 &&
590             CE->getOperand(0)->isNullValue() &&
591             CE->getOperand(1)->isNullValue()) {
592           Type *Ty = cast<GEPOperator>(CE)->getSourceElementType();
593           // Ignore vector types here so that ScalarEvolutionExpander doesn't
594           // emit getelementptrs that index into vectors.
595           if (Ty->isStructTy() || Ty->isArrayTy()) {
596             CTy = Ty;
597             FieldNo = CE->getOperand(2);
598             return true;
599           }
600         }
601 
602   return false;
603 }
604 
605 //===----------------------------------------------------------------------===//
606 //                               SCEV Utilities
607 //===----------------------------------------------------------------------===//
608 
609 /// Compare the two values \p LV and \p RV in terms of their "complexity" where
610 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order
611 /// operands in SCEV expressions.  \p EqCache is a set of pairs of values that
612 /// have been previously deemed to be "equally complex" by this routine.  It is
613 /// intended to avoid exponential time complexity in cases like:
614 ///
615 ///   %a = f(%x, %y)
616 ///   %b = f(%a, %a)
617 ///   %c = f(%b, %b)
618 ///
619 ///   %d = f(%x, %y)
620 ///   %e = f(%d, %d)
621 ///   %f = f(%e, %e)
622 ///
623 ///   CompareValueComplexity(%f, %c)
624 ///
625 /// Since we do not continue running this routine on expression trees once we
626 /// have seen unequal values, there is no need to track them in the cache.
627 static int
628 CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue,
629                        const LoopInfo *const LI, Value *LV, Value *RV,
630                        unsigned Depth) {
631   if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV))
632     return 0;
633 
634   // Order pointer values after integer values. This helps SCEVExpander form
635   // GEPs.
636   bool LIsPointer = LV->getType()->isPointerTy(),
637        RIsPointer = RV->getType()->isPointerTy();
638   if (LIsPointer != RIsPointer)
639     return (int)LIsPointer - (int)RIsPointer;
640 
641   // Compare getValueID values.
642   unsigned LID = LV->getValueID(), RID = RV->getValueID();
643   if (LID != RID)
644     return (int)LID - (int)RID;
645 
646   // Sort arguments by their position.
647   if (const auto *LA = dyn_cast<Argument>(LV)) {
648     const auto *RA = cast<Argument>(RV);
649     unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
650     return (int)LArgNo - (int)RArgNo;
651   }
652 
653   if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
654     const auto *RGV = cast<GlobalValue>(RV);
655 
656     const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
657       auto LT = GV->getLinkage();
658       return !(GlobalValue::isPrivateLinkage(LT) ||
659                GlobalValue::isInternalLinkage(LT));
660     };
661 
662     // Use the names to distinguish the two values, but only if the
663     // names are semantically important.
664     if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
665       return LGV->getName().compare(RGV->getName());
666   }
667 
668   // For instructions, compare their loop depth, and their operand count.  This
669   // is pretty loose.
670   if (const auto *LInst = dyn_cast<Instruction>(LV)) {
671     const auto *RInst = cast<Instruction>(RV);
672 
673     // Compare loop depths.
674     const BasicBlock *LParent = LInst->getParent(),
675                      *RParent = RInst->getParent();
676     if (LParent != RParent) {
677       unsigned LDepth = LI->getLoopDepth(LParent),
678                RDepth = LI->getLoopDepth(RParent);
679       if (LDepth != RDepth)
680         return (int)LDepth - (int)RDepth;
681     }
682 
683     // Compare the number of operands.
684     unsigned LNumOps = LInst->getNumOperands(),
685              RNumOps = RInst->getNumOperands();
686     if (LNumOps != RNumOps)
687       return (int)LNumOps - (int)RNumOps;
688 
689     for (unsigned Idx : seq(0u, LNumOps)) {
690       int Result =
691           CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx),
692                                  RInst->getOperand(Idx), Depth + 1);
693       if (Result != 0)
694         return Result;
695     }
696   }
697 
698   EqCacheValue.unionSets(LV, RV);
699   return 0;
700 }
701 
702 // Return negative, zero, or positive, if LHS is less than, equal to, or greater
703 // than RHS, respectively. A three-way result allows recursive comparisons to be
704 // more efficient.
705 // If the max analysis depth was reached, return None, assuming we do not know
706 // if they are equivalent for sure.
707 static Optional<int>
708 CompareSCEVComplexity(EquivalenceClasses<const SCEV *> &EqCacheSCEV,
709                       EquivalenceClasses<const Value *> &EqCacheValue,
710                       const LoopInfo *const LI, const SCEV *LHS,
711                       const SCEV *RHS, DominatorTree &DT, unsigned Depth = 0) {
712   // Fast-path: SCEVs are uniqued so we can do a quick equality check.
713   if (LHS == RHS)
714     return 0;
715 
716   // Primarily, sort the SCEVs by their getSCEVType().
717   SCEVTypes LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
718   if (LType != RType)
719     return (int)LType - (int)RType;
720 
721   if (EqCacheSCEV.isEquivalent(LHS, RHS))
722     return 0;
723 
724   if (Depth > MaxSCEVCompareDepth)
725     return None;
726 
727   // Aside from the getSCEVType() ordering, the particular ordering
728   // isn't very important except that it's beneficial to be consistent,
729   // so that (a + b) and (b + a) don't end up as different expressions.
730   switch (LType) {
731   case scUnknown: {
732     const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
733     const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
734 
735     int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(),
736                                    RU->getValue(), Depth + 1);
737     if (X == 0)
738       EqCacheSCEV.unionSets(LHS, RHS);
739     return X;
740   }
741 
742   case scConstant: {
743     const SCEVConstant *LC = cast<SCEVConstant>(LHS);
744     const SCEVConstant *RC = cast<SCEVConstant>(RHS);
745 
746     // Compare constant values.
747     const APInt &LA = LC->getAPInt();
748     const APInt &RA = RC->getAPInt();
749     unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
750     if (LBitWidth != RBitWidth)
751       return (int)LBitWidth - (int)RBitWidth;
752     return LA.ult(RA) ? -1 : 1;
753   }
754 
755   case scAddRecExpr: {
756     const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
757     const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
758 
759     // There is always a dominance between two recs that are used by one SCEV,
760     // so we can safely sort recs by loop header dominance. We require such
761     // order in getAddExpr.
762     const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
763     if (LLoop != RLoop) {
764       const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
765       assert(LHead != RHead && "Two loops share the same header?");
766       if (DT.dominates(LHead, RHead))
767         return 1;
768       else
769         assert(DT.dominates(RHead, LHead) &&
770                "No dominance between recurrences used by one SCEV?");
771       return -1;
772     }
773 
774     // Addrec complexity grows with operand count.
775     unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
776     if (LNumOps != RNumOps)
777       return (int)LNumOps - (int)RNumOps;
778 
779     // Lexicographically compare.
780     for (unsigned i = 0; i != LNumOps; ++i) {
781       auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
782                                      LA->getOperand(i), RA->getOperand(i), DT,
783                                      Depth + 1);
784       if (X != 0)
785         return X;
786     }
787     EqCacheSCEV.unionSets(LHS, RHS);
788     return 0;
789   }
790 
791   case scAddExpr:
792   case scMulExpr:
793   case scSMaxExpr:
794   case scUMaxExpr:
795   case scSMinExpr:
796   case scUMinExpr:
797   case scSequentialUMinExpr: {
798     const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
799     const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
800 
801     // Lexicographically compare n-ary expressions.
802     unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
803     if (LNumOps != RNumOps)
804       return (int)LNumOps - (int)RNumOps;
805 
806     for (unsigned i = 0; i != LNumOps; ++i) {
807       auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
808                                      LC->getOperand(i), RC->getOperand(i), DT,
809                                      Depth + 1);
810       if (X != 0)
811         return X;
812     }
813     EqCacheSCEV.unionSets(LHS, RHS);
814     return 0;
815   }
816 
817   case scUDivExpr: {
818     const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
819     const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
820 
821     // Lexicographically compare udiv expressions.
822     auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(),
823                                    RC->getLHS(), DT, Depth + 1);
824     if (X != 0)
825       return X;
826     X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(),
827                               RC->getRHS(), DT, Depth + 1);
828     if (X == 0)
829       EqCacheSCEV.unionSets(LHS, RHS);
830     return X;
831   }
832 
833   case scPtrToInt:
834   case scTruncate:
835   case scZeroExtend:
836   case scSignExtend: {
837     const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
838     const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
839 
840     // Compare cast expressions by operand.
841     auto X =
842         CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getOperand(),
843                               RC->getOperand(), DT, Depth + 1);
844     if (X == 0)
845       EqCacheSCEV.unionSets(LHS, RHS);
846     return X;
847   }
848 
849   case scCouldNotCompute:
850     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
851   }
852   llvm_unreachable("Unknown SCEV kind!");
853 }
854 
855 /// Given a list of SCEV objects, order them by their complexity, and group
856 /// objects of the same complexity together by value.  When this routine is
857 /// finished, we know that any duplicates in the vector are consecutive and that
858 /// complexity is monotonically increasing.
859 ///
860 /// Note that we go take special precautions to ensure that we get deterministic
861 /// results from this routine.  In other words, we don't want the results of
862 /// this to depend on where the addresses of various SCEV objects happened to
863 /// land in memory.
864 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
865                               LoopInfo *LI, DominatorTree &DT) {
866   if (Ops.size() < 2) return;  // Noop
867 
868   EquivalenceClasses<const SCEV *> EqCacheSCEV;
869   EquivalenceClasses<const Value *> EqCacheValue;
870 
871   // Whether LHS has provably less complexity than RHS.
872   auto IsLessComplex = [&](const SCEV *LHS, const SCEV *RHS) {
873     auto Complexity =
874         CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LHS, RHS, DT);
875     return Complexity && *Complexity < 0;
876   };
877   if (Ops.size() == 2) {
878     // This is the common case, which also happens to be trivially simple.
879     // Special case it.
880     const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
881     if (IsLessComplex(RHS, LHS))
882       std::swap(LHS, RHS);
883     return;
884   }
885 
886   // Do the rough sort by complexity.
887   llvm::stable_sort(Ops, [&](const SCEV *LHS, const SCEV *RHS) {
888     return IsLessComplex(LHS, RHS);
889   });
890 
891   // Now that we are sorted by complexity, group elements of the same
892   // complexity.  Note that this is, at worst, N^2, but the vector is likely to
893   // be extremely short in practice.  Note that we take this approach because we
894   // do not want to depend on the addresses of the objects we are grouping.
895   for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
896     const SCEV *S = Ops[i];
897     unsigned Complexity = S->getSCEVType();
898 
899     // If there are any objects of the same complexity and same value as this
900     // one, group them.
901     for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
902       if (Ops[j] == S) { // Found a duplicate.
903         // Move it to immediately after i'th element.
904         std::swap(Ops[i+1], Ops[j]);
905         ++i;   // no need to rescan it.
906         if (i == e-2) return;  // Done!
907       }
908     }
909   }
910 }
911 
912 /// Returns true if \p Ops contains a huge SCEV (the subtree of S contains at
913 /// least HugeExprThreshold nodes).
914 static bool hasHugeExpression(ArrayRef<const SCEV *> Ops) {
915   return any_of(Ops, [](const SCEV *S) {
916     return S->getExpressionSize() >= HugeExprThreshold;
917   });
918 }
919 
920 //===----------------------------------------------------------------------===//
921 //                      Simple SCEV method implementations
922 //===----------------------------------------------------------------------===//
923 
924 /// Compute BC(It, K).  The result has width W.  Assume, K > 0.
925 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
926                                        ScalarEvolution &SE,
927                                        Type *ResultTy) {
928   // Handle the simplest case efficiently.
929   if (K == 1)
930     return SE.getTruncateOrZeroExtend(It, ResultTy);
931 
932   // We are using the following formula for BC(It, K):
933   //
934   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
935   //
936   // Suppose, W is the bitwidth of the return value.  We must be prepared for
937   // overflow.  Hence, we must assure that the result of our computation is
938   // equal to the accurate one modulo 2^W.  Unfortunately, division isn't
939   // safe in modular arithmetic.
940   //
941   // However, this code doesn't use exactly that formula; the formula it uses
942   // is something like the following, where T is the number of factors of 2 in
943   // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
944   // exponentiation:
945   //
946   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
947   //
948   // This formula is trivially equivalent to the previous formula.  However,
949   // this formula can be implemented much more efficiently.  The trick is that
950   // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
951   // arithmetic.  To do exact division in modular arithmetic, all we have
952   // to do is multiply by the inverse.  Therefore, this step can be done at
953   // width W.
954   //
955   // The next issue is how to safely do the division by 2^T.  The way this
956   // is done is by doing the multiplication step at a width of at least W + T
957   // bits.  This way, the bottom W+T bits of the product are accurate. Then,
958   // when we perform the division by 2^T (which is equivalent to a right shift
959   // by T), the bottom W bits are accurate.  Extra bits are okay; they'll get
960   // truncated out after the division by 2^T.
961   //
962   // In comparison to just directly using the first formula, this technique
963   // is much more efficient; using the first formula requires W * K bits,
964   // but this formula less than W + K bits. Also, the first formula requires
965   // a division step, whereas this formula only requires multiplies and shifts.
966   //
967   // It doesn't matter whether the subtraction step is done in the calculation
968   // width or the input iteration count's width; if the subtraction overflows,
969   // the result must be zero anyway.  We prefer here to do it in the width of
970   // the induction variable because it helps a lot for certain cases; CodeGen
971   // isn't smart enough to ignore the overflow, which leads to much less
972   // efficient code if the width of the subtraction is wider than the native
973   // register width.
974   //
975   // (It's possible to not widen at all by pulling out factors of 2 before
976   // the multiplication; for example, K=2 can be calculated as
977   // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
978   // extra arithmetic, so it's not an obvious win, and it gets
979   // much more complicated for K > 3.)
980 
981   // Protection from insane SCEVs; this bound is conservative,
982   // but it probably doesn't matter.
983   if (K > 1000)
984     return SE.getCouldNotCompute();
985 
986   unsigned W = SE.getTypeSizeInBits(ResultTy);
987 
988   // Calculate K! / 2^T and T; we divide out the factors of two before
989   // multiplying for calculating K! / 2^T to avoid overflow.
990   // Other overflow doesn't matter because we only care about the bottom
991   // W bits of the result.
992   APInt OddFactorial(W, 1);
993   unsigned T = 1;
994   for (unsigned i = 3; i <= K; ++i) {
995     APInt Mult(W, i);
996     unsigned TwoFactors = Mult.countTrailingZeros();
997     T += TwoFactors;
998     Mult.lshrInPlace(TwoFactors);
999     OddFactorial *= Mult;
1000   }
1001 
1002   // We need at least W + T bits for the multiplication step
1003   unsigned CalculationBits = W + T;
1004 
1005   // Calculate 2^T, at width T+W.
1006   APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
1007 
1008   // Calculate the multiplicative inverse of K! / 2^T;
1009   // this multiplication factor will perform the exact division by
1010   // K! / 2^T.
1011   APInt Mod = APInt::getSignedMinValue(W+1);
1012   APInt MultiplyFactor = OddFactorial.zext(W+1);
1013   MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
1014   MultiplyFactor = MultiplyFactor.trunc(W);
1015 
1016   // Calculate the product, at width T+W
1017   IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
1018                                                       CalculationBits);
1019   const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
1020   for (unsigned i = 1; i != K; ++i) {
1021     const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
1022     Dividend = SE.getMulExpr(Dividend,
1023                              SE.getTruncateOrZeroExtend(S, CalculationTy));
1024   }
1025 
1026   // Divide by 2^T
1027   const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
1028 
1029   // Truncate the result, and divide by K! / 2^T.
1030 
1031   return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1032                        SE.getTruncateOrZeroExtend(DivResult, ResultTy));
1033 }
1034 
1035 /// Return the value of this chain of recurrences at the specified iteration
1036 /// number.  We can evaluate this recurrence by multiplying each element in the
1037 /// chain by the binomial coefficient corresponding to it.  In other words, we
1038 /// can evaluate {A,+,B,+,C,+,D} as:
1039 ///
1040 ///   A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
1041 ///
1042 /// where BC(It, k) stands for binomial coefficient.
1043 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
1044                                                 ScalarEvolution &SE) const {
1045   return evaluateAtIteration(makeArrayRef(op_begin(), op_end()), It, SE);
1046 }
1047 
1048 const SCEV *
1049 SCEVAddRecExpr::evaluateAtIteration(ArrayRef<const SCEV *> Operands,
1050                                     const SCEV *It, ScalarEvolution &SE) {
1051   assert(Operands.size() > 0);
1052   const SCEV *Result = Operands[0];
1053   for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
1054     // The computation is correct in the face of overflow provided that the
1055     // multiplication is performed _after_ the evaluation of the binomial
1056     // coefficient.
1057     const SCEV *Coeff = BinomialCoefficient(It, i, SE, Result->getType());
1058     if (isa<SCEVCouldNotCompute>(Coeff))
1059       return Coeff;
1060 
1061     Result = SE.getAddExpr(Result, SE.getMulExpr(Operands[i], Coeff));
1062   }
1063   return Result;
1064 }
1065 
1066 //===----------------------------------------------------------------------===//
1067 //                    SCEV Expression folder implementations
1068 //===----------------------------------------------------------------------===//
1069 
1070 const SCEV *ScalarEvolution::getLosslessPtrToIntExpr(const SCEV *Op,
1071                                                      unsigned Depth) {
1072   assert(Depth <= 1 &&
1073          "getLosslessPtrToIntExpr() should self-recurse at most once.");
1074 
1075   // We could be called with an integer-typed operands during SCEV rewrites.
1076   // Since the operand is an integer already, just perform zext/trunc/self cast.
1077   if (!Op->getType()->isPointerTy())
1078     return Op;
1079 
1080   // What would be an ID for such a SCEV cast expression?
1081   FoldingSetNodeID ID;
1082   ID.AddInteger(scPtrToInt);
1083   ID.AddPointer(Op);
1084 
1085   void *IP = nullptr;
1086 
1087   // Is there already an expression for such a cast?
1088   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1089     return S;
1090 
1091   // It isn't legal for optimizations to construct new ptrtoint expressions
1092   // for non-integral pointers.
1093   if (getDataLayout().isNonIntegralPointerType(Op->getType()))
1094     return getCouldNotCompute();
1095 
1096   Type *IntPtrTy = getDataLayout().getIntPtrType(Op->getType());
1097 
1098   // We can only trivially model ptrtoint if SCEV's effective (integer) type
1099   // is sufficiently wide to represent all possible pointer values.
1100   // We could theoretically teach SCEV to truncate wider pointers, but
1101   // that isn't implemented for now.
1102   if (getDataLayout().getTypeSizeInBits(getEffectiveSCEVType(Op->getType())) !=
1103       getDataLayout().getTypeSizeInBits(IntPtrTy))
1104     return getCouldNotCompute();
1105 
1106   // If not, is this expression something we can't reduce any further?
1107   if (auto *U = dyn_cast<SCEVUnknown>(Op)) {
1108     // Perform some basic constant folding. If the operand of the ptr2int cast
1109     // is a null pointer, don't create a ptr2int SCEV expression (that will be
1110     // left as-is), but produce a zero constant.
1111     // NOTE: We could handle a more general case, but lack motivational cases.
1112     if (isa<ConstantPointerNull>(U->getValue()))
1113       return getZero(IntPtrTy);
1114 
1115     // Create an explicit cast node.
1116     // We can reuse the existing insert position since if we get here,
1117     // we won't have made any changes which would invalidate it.
1118     SCEV *S = new (SCEVAllocator)
1119         SCEVPtrToIntExpr(ID.Intern(SCEVAllocator), Op, IntPtrTy);
1120     UniqueSCEVs.InsertNode(S, IP);
1121     registerUser(S, Op);
1122     return S;
1123   }
1124 
1125   assert(Depth == 0 && "getLosslessPtrToIntExpr() should not self-recurse for "
1126                        "non-SCEVUnknown's.");
1127 
1128   // Otherwise, we've got some expression that is more complex than just a
1129   // single SCEVUnknown. But we don't want to have a SCEVPtrToIntExpr of an
1130   // arbitrary expression, we want to have SCEVPtrToIntExpr of an SCEVUnknown
1131   // only, and the expressions must otherwise be integer-typed.
1132   // So sink the cast down to the SCEVUnknown's.
1133 
1134   /// The SCEVPtrToIntSinkingRewriter takes a scalar evolution expression,
1135   /// which computes a pointer-typed value, and rewrites the whole expression
1136   /// tree so that *all* the computations are done on integers, and the only
1137   /// pointer-typed operands in the expression are SCEVUnknown.
1138   class SCEVPtrToIntSinkingRewriter
1139       : public SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter> {
1140     using Base = SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter>;
1141 
1142   public:
1143     SCEVPtrToIntSinkingRewriter(ScalarEvolution &SE) : SCEVRewriteVisitor(SE) {}
1144 
1145     static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE) {
1146       SCEVPtrToIntSinkingRewriter Rewriter(SE);
1147       return Rewriter.visit(Scev);
1148     }
1149 
1150     const SCEV *visit(const SCEV *S) {
1151       Type *STy = S->getType();
1152       // If the expression is not pointer-typed, just keep it as-is.
1153       if (!STy->isPointerTy())
1154         return S;
1155       // Else, recursively sink the cast down into it.
1156       return Base::visit(S);
1157     }
1158 
1159     const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
1160       SmallVector<const SCEV *, 2> Operands;
1161       bool Changed = false;
1162       for (auto *Op : Expr->operands()) {
1163         Operands.push_back(visit(Op));
1164         Changed |= Op != Operands.back();
1165       }
1166       return !Changed ? Expr : SE.getAddExpr(Operands, Expr->getNoWrapFlags());
1167     }
1168 
1169     const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
1170       SmallVector<const SCEV *, 2> Operands;
1171       bool Changed = false;
1172       for (auto *Op : Expr->operands()) {
1173         Operands.push_back(visit(Op));
1174         Changed |= Op != Operands.back();
1175       }
1176       return !Changed ? Expr : SE.getMulExpr(Operands, Expr->getNoWrapFlags());
1177     }
1178 
1179     const SCEV *visitUnknown(const SCEVUnknown *Expr) {
1180       assert(Expr->getType()->isPointerTy() &&
1181              "Should only reach pointer-typed SCEVUnknown's.");
1182       return SE.getLosslessPtrToIntExpr(Expr, /*Depth=*/1);
1183     }
1184   };
1185 
1186   // And actually perform the cast sinking.
1187   const SCEV *IntOp = SCEVPtrToIntSinkingRewriter::rewrite(Op, *this);
1188   assert(IntOp->getType()->isIntegerTy() &&
1189          "We must have succeeded in sinking the cast, "
1190          "and ending up with an integer-typed expression!");
1191   return IntOp;
1192 }
1193 
1194 const SCEV *ScalarEvolution::getPtrToIntExpr(const SCEV *Op, Type *Ty) {
1195   assert(Ty->isIntegerTy() && "Target type must be an integer type!");
1196 
1197   const SCEV *IntOp = getLosslessPtrToIntExpr(Op);
1198   if (isa<SCEVCouldNotCompute>(IntOp))
1199     return IntOp;
1200 
1201   return getTruncateOrZeroExtend(IntOp, Ty);
1202 }
1203 
1204 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, Type *Ty,
1205                                              unsigned Depth) {
1206   assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1207          "This is not a truncating conversion!");
1208   assert(isSCEVable(Ty) &&
1209          "This is not a conversion to a SCEVable type!");
1210   assert(!Op->getType()->isPointerTy() && "Can't truncate pointer!");
1211   Ty = getEffectiveSCEVType(Ty);
1212 
1213   FoldingSetNodeID ID;
1214   ID.AddInteger(scTruncate);
1215   ID.AddPointer(Op);
1216   ID.AddPointer(Ty);
1217   void *IP = nullptr;
1218   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1219 
1220   // Fold if the operand is constant.
1221   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1222     return getConstant(
1223       cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1224 
1225   // trunc(trunc(x)) --> trunc(x)
1226   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
1227     return getTruncateExpr(ST->getOperand(), Ty, Depth + 1);
1228 
1229   // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1230   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1231     return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1);
1232 
1233   // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1234   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1235     return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1);
1236 
1237   if (Depth > MaxCastDepth) {
1238     SCEV *S =
1239         new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty);
1240     UniqueSCEVs.InsertNode(S, IP);
1241     registerUser(S, Op);
1242     return S;
1243   }
1244 
1245   // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and
1246   // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN),
1247   // if after transforming we have at most one truncate, not counting truncates
1248   // that replace other casts.
1249   if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) {
1250     auto *CommOp = cast<SCEVCommutativeExpr>(Op);
1251     SmallVector<const SCEV *, 4> Operands;
1252     unsigned numTruncs = 0;
1253     for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2;
1254          ++i) {
1255       const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1);
1256       if (!isa<SCEVIntegralCastExpr>(CommOp->getOperand(i)) &&
1257           isa<SCEVTruncateExpr>(S))
1258         numTruncs++;
1259       Operands.push_back(S);
1260     }
1261     if (numTruncs < 2) {
1262       if (isa<SCEVAddExpr>(Op))
1263         return getAddExpr(Operands);
1264       else if (isa<SCEVMulExpr>(Op))
1265         return getMulExpr(Operands);
1266       else
1267         llvm_unreachable("Unexpected SCEV type for Op.");
1268     }
1269     // Although we checked in the beginning that ID is not in the cache, it is
1270     // possible that during recursion and different modification ID was inserted
1271     // into the cache. So if we find it, just return it.
1272     if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1273       return S;
1274   }
1275 
1276   // If the input value is a chrec scev, truncate the chrec's operands.
1277   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1278     SmallVector<const SCEV *, 4> Operands;
1279     for (const SCEV *Op : AddRec->operands())
1280       Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1));
1281     return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1282   }
1283 
1284   // Return zero if truncating to known zeros.
1285   uint32_t MinTrailingZeros = GetMinTrailingZeros(Op);
1286   if (MinTrailingZeros >= getTypeSizeInBits(Ty))
1287     return getZero(Ty);
1288 
1289   // The cast wasn't folded; create an explicit cast node. We can reuse
1290   // the existing insert position since if we get here, we won't have
1291   // made any changes which would invalidate it.
1292   SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1293                                                  Op, Ty);
1294   UniqueSCEVs.InsertNode(S, IP);
1295   registerUser(S, Op);
1296   return S;
1297 }
1298 
1299 // Get the limit of a recurrence such that incrementing by Step cannot cause
1300 // signed overflow as long as the value of the recurrence within the
1301 // loop does not exceed this limit before incrementing.
1302 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1303                                                  ICmpInst::Predicate *Pred,
1304                                                  ScalarEvolution *SE) {
1305   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1306   if (SE->isKnownPositive(Step)) {
1307     *Pred = ICmpInst::ICMP_SLT;
1308     return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1309                            SE->getSignedRangeMax(Step));
1310   }
1311   if (SE->isKnownNegative(Step)) {
1312     *Pred = ICmpInst::ICMP_SGT;
1313     return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1314                            SE->getSignedRangeMin(Step));
1315   }
1316   return nullptr;
1317 }
1318 
1319 // Get the limit of a recurrence such that incrementing by Step cannot cause
1320 // unsigned overflow as long as the value of the recurrence within the loop does
1321 // not exceed this limit before incrementing.
1322 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1323                                                    ICmpInst::Predicate *Pred,
1324                                                    ScalarEvolution *SE) {
1325   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1326   *Pred = ICmpInst::ICMP_ULT;
1327 
1328   return SE->getConstant(APInt::getMinValue(BitWidth) -
1329                          SE->getUnsignedRangeMax(Step));
1330 }
1331 
1332 namespace {
1333 
1334 struct ExtendOpTraitsBase {
1335   typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *,
1336                                                           unsigned);
1337 };
1338 
1339 // Used to make code generic over signed and unsigned overflow.
1340 template <typename ExtendOp> struct ExtendOpTraits {
1341   // Members present:
1342   //
1343   // static const SCEV::NoWrapFlags WrapType;
1344   //
1345   // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1346   //
1347   // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1348   //                                           ICmpInst::Predicate *Pred,
1349   //                                           ScalarEvolution *SE);
1350 };
1351 
1352 template <>
1353 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1354   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1355 
1356   static const GetExtendExprTy GetExtendExpr;
1357 
1358   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1359                                              ICmpInst::Predicate *Pred,
1360                                              ScalarEvolution *SE) {
1361     return getSignedOverflowLimitForStep(Step, Pred, SE);
1362   }
1363 };
1364 
1365 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1366     SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr;
1367 
1368 template <>
1369 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1370   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1371 
1372   static const GetExtendExprTy GetExtendExpr;
1373 
1374   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1375                                              ICmpInst::Predicate *Pred,
1376                                              ScalarEvolution *SE) {
1377     return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1378   }
1379 };
1380 
1381 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1382     SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr;
1383 
1384 } // end anonymous namespace
1385 
1386 // The recurrence AR has been shown to have no signed/unsigned wrap or something
1387 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1388 // easily prove NSW/NUW for its preincrement or postincrement sibling. This
1389 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1390 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1391 // expression "Step + sext/zext(PreIncAR)" is congruent with
1392 // "sext/zext(PostIncAR)"
1393 template <typename ExtendOpTy>
1394 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1395                                         ScalarEvolution *SE, unsigned Depth) {
1396   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1397   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1398 
1399   const Loop *L = AR->getLoop();
1400   const SCEV *Start = AR->getStart();
1401   const SCEV *Step = AR->getStepRecurrence(*SE);
1402 
1403   // Check for a simple looking step prior to loop entry.
1404   const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1405   if (!SA)
1406     return nullptr;
1407 
1408   // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1409   // subtraction is expensive. For this purpose, perform a quick and dirty
1410   // difference, by checking for Step in the operand list.
1411   SmallVector<const SCEV *, 4> DiffOps;
1412   for (const SCEV *Op : SA->operands())
1413     if (Op != Step)
1414       DiffOps.push_back(Op);
1415 
1416   if (DiffOps.size() == SA->getNumOperands())
1417     return nullptr;
1418 
1419   // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1420   // `Step`:
1421 
1422   // 1. NSW/NUW flags on the step increment.
1423   auto PreStartFlags =
1424     ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
1425   const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1426   const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1427       SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1428 
1429   // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1430   // "S+X does not sign/unsign-overflow".
1431   //
1432 
1433   const SCEV *BECount = SE->getBackedgeTakenCount(L);
1434   if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1435       !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1436     return PreStart;
1437 
1438   // 2. Direct overflow check on the step operation's expression.
1439   unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1440   Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1441   const SCEV *OperandExtendedStart =
1442       SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
1443                      (SE->*GetExtendExpr)(Step, WideTy, Depth));
1444   if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
1445     if (PreAR && AR->getNoWrapFlags(WrapType)) {
1446       // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1447       // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1448       // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`.  Cache this fact.
1449       SE->setNoWrapFlags(const_cast<SCEVAddRecExpr *>(PreAR), WrapType);
1450     }
1451     return PreStart;
1452   }
1453 
1454   // 3. Loop precondition.
1455   ICmpInst::Predicate Pred;
1456   const SCEV *OverflowLimit =
1457       ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1458 
1459   if (OverflowLimit &&
1460       SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1461     return PreStart;
1462 
1463   return nullptr;
1464 }
1465 
1466 // Get the normalized zero or sign extended expression for this AddRec's Start.
1467 template <typename ExtendOpTy>
1468 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1469                                         ScalarEvolution *SE,
1470                                         unsigned Depth) {
1471   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1472 
1473   const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth);
1474   if (!PreStart)
1475     return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth);
1476 
1477   return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty,
1478                                              Depth),
1479                         (SE->*GetExtendExpr)(PreStart, Ty, Depth));
1480 }
1481 
1482 // Try to prove away overflow by looking at "nearby" add recurrences.  A
1483 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1484 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1485 //
1486 // Formally:
1487 //
1488 //     {S,+,X} == {S-T,+,X} + T
1489 //  => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1490 //
1491 // If ({S-T,+,X} + T) does not overflow  ... (1)
1492 //
1493 //  RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1494 //
1495 // If {S-T,+,X} does not overflow  ... (2)
1496 //
1497 //  RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1498 //      == {Ext(S-T)+Ext(T),+,Ext(X)}
1499 //
1500 // If (S-T)+T does not overflow  ... (3)
1501 //
1502 //  RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1503 //      == {Ext(S),+,Ext(X)} == LHS
1504 //
1505 // Thus, if (1), (2) and (3) are true for some T, then
1506 //   Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1507 //
1508 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1509 // does not overflow" restricted to the 0th iteration.  Therefore we only need
1510 // to check for (1) and (2).
1511 //
1512 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1513 // is `Delta` (defined below).
1514 template <typename ExtendOpTy>
1515 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1516                                                 const SCEV *Step,
1517                                                 const Loop *L) {
1518   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1519 
1520   // We restrict `Start` to a constant to prevent SCEV from spending too much
1521   // time here.  It is correct (but more expensive) to continue with a
1522   // non-constant `Start` and do a general SCEV subtraction to compute
1523   // `PreStart` below.
1524   const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1525   if (!StartC)
1526     return false;
1527 
1528   APInt StartAI = StartC->getAPInt();
1529 
1530   for (unsigned Delta : {-2, -1, 1, 2}) {
1531     const SCEV *PreStart = getConstant(StartAI - Delta);
1532 
1533     FoldingSetNodeID ID;
1534     ID.AddInteger(scAddRecExpr);
1535     ID.AddPointer(PreStart);
1536     ID.AddPointer(Step);
1537     ID.AddPointer(L);
1538     void *IP = nullptr;
1539     const auto *PreAR =
1540       static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1541 
1542     // Give up if we don't already have the add recurrence we need because
1543     // actually constructing an add recurrence is relatively expensive.
1544     if (PreAR && PreAR->getNoWrapFlags(WrapType)) {  // proves (2)
1545       const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1546       ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1547       const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1548           DeltaS, &Pred, this);
1549       if (Limit && isKnownPredicate(Pred, PreAR, Limit))  // proves (1)
1550         return true;
1551     }
1552   }
1553 
1554   return false;
1555 }
1556 
1557 // Finds an integer D for an expression (C + x + y + ...) such that the top
1558 // level addition in (D + (C - D + x + y + ...)) would not wrap (signed or
1559 // unsigned) and the number of trailing zeros of (C - D + x + y + ...) is
1560 // maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and
1561 // the (C + x + y + ...) expression is \p WholeAddExpr.
1562 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE,
1563                                             const SCEVConstant *ConstantTerm,
1564                                             const SCEVAddExpr *WholeAddExpr) {
1565   const APInt &C = ConstantTerm->getAPInt();
1566   const unsigned BitWidth = C.getBitWidth();
1567   // Find number of trailing zeros of (x + y + ...) w/o the C first:
1568   uint32_t TZ = BitWidth;
1569   for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I)
1570     TZ = std::min(TZ, SE.GetMinTrailingZeros(WholeAddExpr->getOperand(I)));
1571   if (TZ) {
1572     // Set D to be as many least significant bits of C as possible while still
1573     // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap:
1574     return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C;
1575   }
1576   return APInt(BitWidth, 0);
1577 }
1578 
1579 // Finds an integer D for an affine AddRec expression {C,+,x} such that the top
1580 // level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the
1581 // number of trailing zeros of (C - D + x * n) is maximized, where C is the \p
1582 // ConstantStart, x is an arbitrary \p Step, and n is the loop trip count.
1583 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE,
1584                                             const APInt &ConstantStart,
1585                                             const SCEV *Step) {
1586   const unsigned BitWidth = ConstantStart.getBitWidth();
1587   const uint32_t TZ = SE.GetMinTrailingZeros(Step);
1588   if (TZ)
1589     return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth)
1590                          : ConstantStart;
1591   return APInt(BitWidth, 0);
1592 }
1593 
1594 const SCEV *
1595 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1596   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1597          "This is not an extending conversion!");
1598   assert(isSCEVable(Ty) &&
1599          "This is not a conversion to a SCEVable type!");
1600   assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1601   Ty = getEffectiveSCEVType(Ty);
1602 
1603   // Fold if the operand is constant.
1604   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1605     return getConstant(
1606       cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
1607 
1608   // zext(zext(x)) --> zext(x)
1609   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1610     return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1611 
1612   // Before doing any expensive analysis, check to see if we've already
1613   // computed a SCEV for this Op and Ty.
1614   FoldingSetNodeID ID;
1615   ID.AddInteger(scZeroExtend);
1616   ID.AddPointer(Op);
1617   ID.AddPointer(Ty);
1618   void *IP = nullptr;
1619   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1620   if (Depth > MaxCastDepth) {
1621     SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1622                                                      Op, Ty);
1623     UniqueSCEVs.InsertNode(S, IP);
1624     registerUser(S, Op);
1625     return S;
1626   }
1627 
1628   // zext(trunc(x)) --> zext(x) or x or trunc(x)
1629   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1630     // It's possible the bits taken off by the truncate were all zero bits. If
1631     // so, we should be able to simplify this further.
1632     const SCEV *X = ST->getOperand();
1633     ConstantRange CR = getUnsignedRange(X);
1634     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1635     unsigned NewBits = getTypeSizeInBits(Ty);
1636     if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1637             CR.zextOrTrunc(NewBits)))
1638       return getTruncateOrZeroExtend(X, Ty, Depth);
1639   }
1640 
1641   // If the input value is a chrec scev, and we can prove that the value
1642   // did not overflow the old, smaller, value, we can zero extend all of the
1643   // operands (often constants).  This allows analysis of something like
1644   // this:  for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1645   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1646     if (AR->isAffine()) {
1647       const SCEV *Start = AR->getStart();
1648       const SCEV *Step = AR->getStepRecurrence(*this);
1649       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1650       const Loop *L = AR->getLoop();
1651 
1652       if (!AR->hasNoUnsignedWrap()) {
1653         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1654         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1655       }
1656 
1657       // If we have special knowledge that this addrec won't overflow,
1658       // we don't need to do any further analysis.
1659       if (AR->hasNoUnsignedWrap())
1660         return getAddRecExpr(
1661             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1662             getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1663 
1664       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1665       // Note that this serves two purposes: It filters out loops that are
1666       // simply not analyzable, and it covers the case where this code is
1667       // being called from within backedge-taken count analysis, such that
1668       // attempting to ask for the backedge-taken count would likely result
1669       // in infinite recursion. In the later case, the analysis code will
1670       // cope with a conservative value, and it will take care to purge
1671       // that value once it has finished.
1672       const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
1673       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1674         // Manually compute the final value for AR, checking for overflow.
1675 
1676         // Check whether the backedge-taken count can be losslessly casted to
1677         // the addrec's type. The count is always unsigned.
1678         const SCEV *CastedMaxBECount =
1679             getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
1680         const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
1681             CastedMaxBECount, MaxBECount->getType(), Depth);
1682         if (MaxBECount == RecastedMaxBECount) {
1683           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1684           // Check whether Start+Step*MaxBECount has no unsigned overflow.
1685           const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step,
1686                                         SCEV::FlagAnyWrap, Depth + 1);
1687           const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul,
1688                                                           SCEV::FlagAnyWrap,
1689                                                           Depth + 1),
1690                                                WideTy, Depth + 1);
1691           const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
1692           const SCEV *WideMaxBECount =
1693             getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1694           const SCEV *OperandExtendedAdd =
1695             getAddExpr(WideStart,
1696                        getMulExpr(WideMaxBECount,
1697                                   getZeroExtendExpr(Step, WideTy, Depth + 1),
1698                                   SCEV::FlagAnyWrap, Depth + 1),
1699                        SCEV::FlagAnyWrap, Depth + 1);
1700           if (ZAdd == OperandExtendedAdd) {
1701             // Cache knowledge of AR NUW, which is propagated to this AddRec.
1702             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1703             // Return the expression with the addrec on the outside.
1704             return getAddRecExpr(getExtendAddRecStart<SCEVZeroExtendExpr>(
1705                                      AR, Ty, this, Depth + 1),
1706                                  getZeroExtendExpr(Step, Ty, Depth + 1), L,
1707                                  AR->getNoWrapFlags());
1708           }
1709           // Similar to above, only this time treat the step value as signed.
1710           // This covers loops that count down.
1711           OperandExtendedAdd =
1712             getAddExpr(WideStart,
1713                        getMulExpr(WideMaxBECount,
1714                                   getSignExtendExpr(Step, WideTy, Depth + 1),
1715                                   SCEV::FlagAnyWrap, Depth + 1),
1716                        SCEV::FlagAnyWrap, Depth + 1);
1717           if (ZAdd == OperandExtendedAdd) {
1718             // Cache knowledge of AR NW, which is propagated to this AddRec.
1719             // Negative step causes unsigned wrap, but it still can't self-wrap.
1720             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1721             // Return the expression with the addrec on the outside.
1722             return getAddRecExpr(getExtendAddRecStart<SCEVZeroExtendExpr>(
1723                                      AR, Ty, this, Depth + 1),
1724                                  getSignExtendExpr(Step, Ty, Depth + 1), L,
1725                                  AR->getNoWrapFlags());
1726           }
1727         }
1728       }
1729 
1730       // Normally, in the cases we can prove no-overflow via a
1731       // backedge guarding condition, we can also compute a backedge
1732       // taken count for the loop.  The exceptions are assumptions and
1733       // guards present in the loop -- SCEV is not great at exploiting
1734       // these to compute max backedge taken counts, but can still use
1735       // these to prove lack of overflow.  Use this fact to avoid
1736       // doing extra work that may not pay off.
1737       if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1738           !AC.assumptions().empty()) {
1739 
1740         auto NewFlags = proveNoUnsignedWrapViaInduction(AR);
1741         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1742         if (AR->hasNoUnsignedWrap()) {
1743           // Same as nuw case above - duplicated here to avoid a compile time
1744           // issue.  It's not clear that the order of checks does matter, but
1745           // it's one of two issue possible causes for a change which was
1746           // reverted.  Be conservative for the moment.
1747           return getAddRecExpr(
1748               getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1749               getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1750         }
1751 
1752         // For a negative step, we can extend the operands iff doing so only
1753         // traverses values in the range zext([0,UINT_MAX]).
1754         if (isKnownNegative(Step)) {
1755           const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1756                                       getSignedRangeMin(Step));
1757           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1758               isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) {
1759             // Cache knowledge of AR NW, which is propagated to this
1760             // AddRec.  Negative step causes unsigned wrap, but it
1761             // still can't self-wrap.
1762             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1763             // Return the expression with the addrec on the outside.
1764             return getAddRecExpr(getExtendAddRecStart<SCEVZeroExtendExpr>(
1765                                      AR, Ty, this, Depth + 1),
1766                                  getSignExtendExpr(Step, Ty, Depth + 1), L,
1767                                  AR->getNoWrapFlags());
1768           }
1769         }
1770       }
1771 
1772       // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw>
1773       // if D + (C - D + Step * n) could be proven to not unsigned wrap
1774       // where D maximizes the number of trailing zeros of (C - D + Step * n)
1775       if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
1776         const APInt &C = SC->getAPInt();
1777         const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
1778         if (D != 0) {
1779           const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1780           const SCEV *SResidual =
1781               getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
1782           const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1783           return getAddExpr(SZExtD, SZExtR,
1784                             (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1785                             Depth + 1);
1786         }
1787       }
1788 
1789       if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1790         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1791         return getAddRecExpr(
1792             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1793             getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1794       }
1795     }
1796 
1797   // zext(A % B) --> zext(A) % zext(B)
1798   {
1799     const SCEV *LHS;
1800     const SCEV *RHS;
1801     if (matchURem(Op, LHS, RHS))
1802       return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1),
1803                          getZeroExtendExpr(RHS, Ty, Depth + 1));
1804   }
1805 
1806   // zext(A / B) --> zext(A) / zext(B).
1807   if (auto *Div = dyn_cast<SCEVUDivExpr>(Op))
1808     return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1),
1809                        getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1));
1810 
1811   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1812     // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1813     if (SA->hasNoUnsignedWrap()) {
1814       // If the addition does not unsign overflow then we can, by definition,
1815       // commute the zero extension with the addition operation.
1816       SmallVector<const SCEV *, 4> Ops;
1817       for (const auto *Op : SA->operands())
1818         Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1819       return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1);
1820     }
1821 
1822     // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...))
1823     // if D + (C - D + x + y + ...) could be proven to not unsigned wrap
1824     // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1825     //
1826     // Often address arithmetics contain expressions like
1827     // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))).
1828     // This transformation is useful while proving that such expressions are
1829     // equal or differ by a small constant amount, see LoadStoreVectorizer pass.
1830     if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1831       const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1832       if (D != 0) {
1833         const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1834         const SCEV *SResidual =
1835             getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth);
1836         const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1837         return getAddExpr(SZExtD, SZExtR,
1838                           (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1839                           Depth + 1);
1840       }
1841     }
1842   }
1843 
1844   if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) {
1845     // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw>
1846     if (SM->hasNoUnsignedWrap()) {
1847       // If the multiply does not unsign overflow then we can, by definition,
1848       // commute the zero extension with the multiply operation.
1849       SmallVector<const SCEV *, 4> Ops;
1850       for (const auto *Op : SM->operands())
1851         Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1852       return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1);
1853     }
1854 
1855     // zext(2^K * (trunc X to iN)) to iM ->
1856     // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw>
1857     //
1858     // Proof:
1859     //
1860     //     zext(2^K * (trunc X to iN)) to iM
1861     //   = zext((trunc X to iN) << K) to iM
1862     //   = zext((trunc X to i{N-K}) << K)<nuw> to iM
1863     //     (because shl removes the top K bits)
1864     //   = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM
1865     //   = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>.
1866     //
1867     if (SM->getNumOperands() == 2)
1868       if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0)))
1869         if (MulLHS->getAPInt().isPowerOf2())
1870           if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) {
1871             int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) -
1872                                MulLHS->getAPInt().logBase2();
1873             Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits);
1874             return getMulExpr(
1875                 getZeroExtendExpr(MulLHS, Ty),
1876                 getZeroExtendExpr(
1877                     getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty),
1878                 SCEV::FlagNUW, Depth + 1);
1879           }
1880   }
1881 
1882   // The cast wasn't folded; create an explicit cast node.
1883   // Recompute the insert position, as it may have been invalidated.
1884   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1885   SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1886                                                    Op, Ty);
1887   UniqueSCEVs.InsertNode(S, IP);
1888   registerUser(S, Op);
1889   return S;
1890 }
1891 
1892 const SCEV *
1893 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1894   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1895          "This is not an extending conversion!");
1896   assert(isSCEVable(Ty) &&
1897          "This is not a conversion to a SCEVable type!");
1898   assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1899   Ty = getEffectiveSCEVType(Ty);
1900 
1901   // Fold if the operand is constant.
1902   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1903     return getConstant(
1904       cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
1905 
1906   // sext(sext(x)) --> sext(x)
1907   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1908     return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1);
1909 
1910   // sext(zext(x)) --> zext(x)
1911   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1912     return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1913 
1914   // Before doing any expensive analysis, check to see if we've already
1915   // computed a SCEV for this Op and Ty.
1916   FoldingSetNodeID ID;
1917   ID.AddInteger(scSignExtend);
1918   ID.AddPointer(Op);
1919   ID.AddPointer(Ty);
1920   void *IP = nullptr;
1921   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1922   // Limit recursion depth.
1923   if (Depth > MaxCastDepth) {
1924     SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1925                                                      Op, Ty);
1926     UniqueSCEVs.InsertNode(S, IP);
1927     registerUser(S, Op);
1928     return S;
1929   }
1930 
1931   // sext(trunc(x)) --> sext(x) or x or trunc(x)
1932   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1933     // It's possible the bits taken off by the truncate were all sign bits. If
1934     // so, we should be able to simplify this further.
1935     const SCEV *X = ST->getOperand();
1936     ConstantRange CR = getSignedRange(X);
1937     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1938     unsigned NewBits = getTypeSizeInBits(Ty);
1939     if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1940             CR.sextOrTrunc(NewBits)))
1941       return getTruncateOrSignExtend(X, Ty, Depth);
1942   }
1943 
1944   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1945     // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1946     if (SA->hasNoSignedWrap()) {
1947       // If the addition does not sign overflow then we can, by definition,
1948       // commute the sign extension with the addition operation.
1949       SmallVector<const SCEV *, 4> Ops;
1950       for (const auto *Op : SA->operands())
1951         Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1));
1952       return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1);
1953     }
1954 
1955     // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...))
1956     // if D + (C - D + x + y + ...) could be proven to not signed wrap
1957     // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1958     //
1959     // For instance, this will bring two seemingly different expressions:
1960     //     1 + sext(5 + 20 * %x + 24 * %y)  and
1961     //         sext(6 + 20 * %x + 24 * %y)
1962     // to the same form:
1963     //     2 + sext(4 + 20 * %x + 24 * %y)
1964     if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1965       const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1966       if (D != 0) {
1967         const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
1968         const SCEV *SResidual =
1969             getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth);
1970         const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
1971         return getAddExpr(SSExtD, SSExtR,
1972                           (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1973                           Depth + 1);
1974       }
1975     }
1976   }
1977   // If the input value is a chrec scev, and we can prove that the value
1978   // did not overflow the old, smaller, value, we can sign extend all of the
1979   // operands (often constants).  This allows analysis of something like
1980   // this:  for (signed char X = 0; X < 100; ++X) { int Y = X; }
1981   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1982     if (AR->isAffine()) {
1983       const SCEV *Start = AR->getStart();
1984       const SCEV *Step = AR->getStepRecurrence(*this);
1985       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1986       const Loop *L = AR->getLoop();
1987 
1988       if (!AR->hasNoSignedWrap()) {
1989         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1990         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1991       }
1992 
1993       // If we have special knowledge that this addrec won't overflow,
1994       // we don't need to do any further analysis.
1995       if (AR->hasNoSignedWrap())
1996         return getAddRecExpr(
1997             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
1998             getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW);
1999 
2000       // Check whether the backedge-taken count is SCEVCouldNotCompute.
2001       // Note that this serves two purposes: It filters out loops that are
2002       // simply not analyzable, and it covers the case where this code is
2003       // being called from within backedge-taken count analysis, such that
2004       // attempting to ask for the backedge-taken count would likely result
2005       // in infinite recursion. In the later case, the analysis code will
2006       // cope with a conservative value, and it will take care to purge
2007       // that value once it has finished.
2008       const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
2009       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
2010         // Manually compute the final value for AR, checking for
2011         // overflow.
2012 
2013         // Check whether the backedge-taken count can be losslessly casted to
2014         // the addrec's type. The count is always unsigned.
2015         const SCEV *CastedMaxBECount =
2016             getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
2017         const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
2018             CastedMaxBECount, MaxBECount->getType(), Depth);
2019         if (MaxBECount == RecastedMaxBECount) {
2020           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
2021           // Check whether Start+Step*MaxBECount has no signed overflow.
2022           const SCEV *SMul = getMulExpr(CastedMaxBECount, Step,
2023                                         SCEV::FlagAnyWrap, Depth + 1);
2024           const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul,
2025                                                           SCEV::FlagAnyWrap,
2026                                                           Depth + 1),
2027                                                WideTy, Depth + 1);
2028           const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
2029           const SCEV *WideMaxBECount =
2030             getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
2031           const SCEV *OperandExtendedAdd =
2032             getAddExpr(WideStart,
2033                        getMulExpr(WideMaxBECount,
2034                                   getSignExtendExpr(Step, WideTy, Depth + 1),
2035                                   SCEV::FlagAnyWrap, Depth + 1),
2036                        SCEV::FlagAnyWrap, Depth + 1);
2037           if (SAdd == OperandExtendedAdd) {
2038             // Cache knowledge of AR NSW, which is propagated to this AddRec.
2039             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2040             // Return the expression with the addrec on the outside.
2041             return getAddRecExpr(getExtendAddRecStart<SCEVSignExtendExpr>(
2042                                      AR, Ty, this, Depth + 1),
2043                                  getSignExtendExpr(Step, Ty, Depth + 1), L,
2044                                  AR->getNoWrapFlags());
2045           }
2046           // Similar to above, only this time treat the step value as unsigned.
2047           // This covers loops that count up with an unsigned step.
2048           OperandExtendedAdd =
2049             getAddExpr(WideStart,
2050                        getMulExpr(WideMaxBECount,
2051                                   getZeroExtendExpr(Step, WideTy, Depth + 1),
2052                                   SCEV::FlagAnyWrap, Depth + 1),
2053                        SCEV::FlagAnyWrap, Depth + 1);
2054           if (SAdd == OperandExtendedAdd) {
2055             // If AR wraps around then
2056             //
2057             //    abs(Step) * MaxBECount > unsigned-max(AR->getType())
2058             // => SAdd != OperandExtendedAdd
2059             //
2060             // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
2061             // (SAdd == OperandExtendedAdd => AR is NW)
2062 
2063             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
2064 
2065             // Return the expression with the addrec on the outside.
2066             return getAddRecExpr(getExtendAddRecStart<SCEVSignExtendExpr>(
2067                                      AR, Ty, this, Depth + 1),
2068                                  getZeroExtendExpr(Step, Ty, Depth + 1), L,
2069                                  AR->getNoWrapFlags());
2070           }
2071         }
2072       }
2073 
2074       auto NewFlags = proveNoSignedWrapViaInduction(AR);
2075       setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
2076       if (AR->hasNoSignedWrap()) {
2077         // Same as nsw case above - duplicated here to avoid a compile time
2078         // issue.  It's not clear that the order of checks does matter, but
2079         // it's one of two issue possible causes for a change which was
2080         // reverted.  Be conservative for the moment.
2081         return getAddRecExpr(
2082             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2083             getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2084       }
2085 
2086       // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw>
2087       // if D + (C - D + Step * n) could be proven to not signed wrap
2088       // where D maximizes the number of trailing zeros of (C - D + Step * n)
2089       if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
2090         const APInt &C = SC->getAPInt();
2091         const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
2092         if (D != 0) {
2093           const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
2094           const SCEV *SResidual =
2095               getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
2096           const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
2097           return getAddExpr(SSExtD, SSExtR,
2098                             (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
2099                             Depth + 1);
2100         }
2101       }
2102 
2103       if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
2104         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2105         return getAddRecExpr(
2106             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2107             getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2108       }
2109     }
2110 
2111   // If the input value is provably positive and we could not simplify
2112   // away the sext build a zext instead.
2113   if (isKnownNonNegative(Op))
2114     return getZeroExtendExpr(Op, Ty, Depth + 1);
2115 
2116   // The cast wasn't folded; create an explicit cast node.
2117   // Recompute the insert position, as it may have been invalidated.
2118   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2119   SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
2120                                                    Op, Ty);
2121   UniqueSCEVs.InsertNode(S, IP);
2122   registerUser(S, { Op });
2123   return S;
2124 }
2125 
2126 const SCEV *ScalarEvolution::getCastExpr(SCEVTypes Kind, const SCEV *Op,
2127                                          Type *Ty) {
2128   switch (Kind) {
2129   case scTruncate:
2130     return getTruncateExpr(Op, Ty);
2131   case scZeroExtend:
2132     return getZeroExtendExpr(Op, Ty);
2133   case scSignExtend:
2134     return getSignExtendExpr(Op, Ty);
2135   case scPtrToInt:
2136     return getPtrToIntExpr(Op, Ty);
2137   default:
2138     llvm_unreachable("Not a SCEV cast expression!");
2139   }
2140 }
2141 
2142 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
2143 /// unspecified bits out to the given type.
2144 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
2145                                               Type *Ty) {
2146   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
2147          "This is not an extending conversion!");
2148   assert(isSCEVable(Ty) &&
2149          "This is not a conversion to a SCEVable type!");
2150   Ty = getEffectiveSCEVType(Ty);
2151 
2152   // Sign-extend negative constants.
2153   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
2154     if (SC->getAPInt().isNegative())
2155       return getSignExtendExpr(Op, Ty);
2156 
2157   // Peel off a truncate cast.
2158   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
2159     const SCEV *NewOp = T->getOperand();
2160     if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
2161       return getAnyExtendExpr(NewOp, Ty);
2162     return getTruncateOrNoop(NewOp, Ty);
2163   }
2164 
2165   // Next try a zext cast. If the cast is folded, use it.
2166   const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2167   if (!isa<SCEVZeroExtendExpr>(ZExt))
2168     return ZExt;
2169 
2170   // Next try a sext cast. If the cast is folded, use it.
2171   const SCEV *SExt = getSignExtendExpr(Op, Ty);
2172   if (!isa<SCEVSignExtendExpr>(SExt))
2173     return SExt;
2174 
2175   // Force the cast to be folded into the operands of an addrec.
2176   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2177     SmallVector<const SCEV *, 4> Ops;
2178     for (const SCEV *Op : AR->operands())
2179       Ops.push_back(getAnyExtendExpr(Op, Ty));
2180     return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2181   }
2182 
2183   // If the expression is obviously signed, use the sext cast value.
2184   if (isa<SCEVSMaxExpr>(Op))
2185     return SExt;
2186 
2187   // Absent any other information, use the zext cast value.
2188   return ZExt;
2189 }
2190 
2191 /// Process the given Ops list, which is a list of operands to be added under
2192 /// the given scale, update the given map. This is a helper function for
2193 /// getAddRecExpr. As an example of what it does, given a sequence of operands
2194 /// that would form an add expression like this:
2195 ///
2196 ///    m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2197 ///
2198 /// where A and B are constants, update the map with these values:
2199 ///
2200 ///    (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2201 ///
2202 /// and add 13 + A*B*29 to AccumulatedConstant.
2203 /// This will allow getAddRecExpr to produce this:
2204 ///
2205 ///    13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2206 ///
2207 /// This form often exposes folding opportunities that are hidden in
2208 /// the original operand list.
2209 ///
2210 /// Return true iff it appears that any interesting folding opportunities
2211 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
2212 /// the common case where no interesting opportunities are present, and
2213 /// is also used as a check to avoid infinite recursion.
2214 static bool
2215 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
2216                              SmallVectorImpl<const SCEV *> &NewOps,
2217                              APInt &AccumulatedConstant,
2218                              const SCEV *const *Ops, size_t NumOperands,
2219                              const APInt &Scale,
2220                              ScalarEvolution &SE) {
2221   bool Interesting = false;
2222 
2223   // Iterate over the add operands. They are sorted, with constants first.
2224   unsigned i = 0;
2225   while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2226     ++i;
2227     // Pull a buried constant out to the outside.
2228     if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2229       Interesting = true;
2230     AccumulatedConstant += Scale * C->getAPInt();
2231   }
2232 
2233   // Next comes everything else. We're especially interested in multiplies
2234   // here, but they're in the middle, so just visit the rest with one loop.
2235   for (; i != NumOperands; ++i) {
2236     const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
2237     if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2238       APInt NewScale =
2239           Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2240       if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2241         // A multiplication of a constant with another add; recurse.
2242         const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2243         Interesting |=
2244           CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2245                                        Add->op_begin(), Add->getNumOperands(),
2246                                        NewScale, SE);
2247       } else {
2248         // A multiplication of a constant with some other value. Update
2249         // the map.
2250         SmallVector<const SCEV *, 4> MulOps(drop_begin(Mul->operands()));
2251         const SCEV *Key = SE.getMulExpr(MulOps);
2252         auto Pair = M.insert({Key, NewScale});
2253         if (Pair.second) {
2254           NewOps.push_back(Pair.first->first);
2255         } else {
2256           Pair.first->second += NewScale;
2257           // The map already had an entry for this value, which may indicate
2258           // a folding opportunity.
2259           Interesting = true;
2260         }
2261       }
2262     } else {
2263       // An ordinary operand. Update the map.
2264       std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
2265           M.insert({Ops[i], Scale});
2266       if (Pair.second) {
2267         NewOps.push_back(Pair.first->first);
2268       } else {
2269         Pair.first->second += Scale;
2270         // The map already had an entry for this value, which may indicate
2271         // a folding opportunity.
2272         Interesting = true;
2273       }
2274     }
2275   }
2276 
2277   return Interesting;
2278 }
2279 
2280 bool ScalarEvolution::willNotOverflow(Instruction::BinaryOps BinOp, bool Signed,
2281                                       const SCEV *LHS, const SCEV *RHS) {
2282   const SCEV *(ScalarEvolution::*Operation)(const SCEV *, const SCEV *,
2283                                             SCEV::NoWrapFlags, unsigned);
2284   switch (BinOp) {
2285   default:
2286     llvm_unreachable("Unsupported binary op");
2287   case Instruction::Add:
2288     Operation = &ScalarEvolution::getAddExpr;
2289     break;
2290   case Instruction::Sub:
2291     Operation = &ScalarEvolution::getMinusSCEV;
2292     break;
2293   case Instruction::Mul:
2294     Operation = &ScalarEvolution::getMulExpr;
2295     break;
2296   }
2297 
2298   const SCEV *(ScalarEvolution::*Extension)(const SCEV *, Type *, unsigned) =
2299       Signed ? &ScalarEvolution::getSignExtendExpr
2300              : &ScalarEvolution::getZeroExtendExpr;
2301 
2302   // Check ext(LHS op RHS) == ext(LHS) op ext(RHS)
2303   auto *NarrowTy = cast<IntegerType>(LHS->getType());
2304   auto *WideTy =
2305       IntegerType::get(NarrowTy->getContext(), NarrowTy->getBitWidth() * 2);
2306 
2307   const SCEV *A = (this->*Extension)(
2308       (this->*Operation)(LHS, RHS, SCEV::FlagAnyWrap, 0), WideTy, 0);
2309   const SCEV *B = (this->*Operation)((this->*Extension)(LHS, WideTy, 0),
2310                                      (this->*Extension)(RHS, WideTy, 0),
2311                                      SCEV::FlagAnyWrap, 0);
2312   return A == B;
2313 }
2314 
2315 std::pair<SCEV::NoWrapFlags, bool /*Deduced*/>
2316 ScalarEvolution::getStrengthenedNoWrapFlagsFromBinOp(
2317     const OverflowingBinaryOperator *OBO) {
2318   SCEV::NoWrapFlags Flags = SCEV::NoWrapFlags::FlagAnyWrap;
2319 
2320   if (OBO->hasNoUnsignedWrap())
2321     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2322   if (OBO->hasNoSignedWrap())
2323     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2324 
2325   bool Deduced = false;
2326 
2327   if (OBO->hasNoUnsignedWrap() && OBO->hasNoSignedWrap())
2328     return {Flags, Deduced};
2329 
2330   if (OBO->getOpcode() != Instruction::Add &&
2331       OBO->getOpcode() != Instruction::Sub &&
2332       OBO->getOpcode() != Instruction::Mul)
2333     return {Flags, Deduced};
2334 
2335   const SCEV *LHS = getSCEV(OBO->getOperand(0));
2336   const SCEV *RHS = getSCEV(OBO->getOperand(1));
2337 
2338   if (!OBO->hasNoUnsignedWrap() &&
2339       willNotOverflow((Instruction::BinaryOps)OBO->getOpcode(),
2340                       /* Signed */ false, LHS, RHS)) {
2341     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2342     Deduced = true;
2343   }
2344 
2345   if (!OBO->hasNoSignedWrap() &&
2346       willNotOverflow((Instruction::BinaryOps)OBO->getOpcode(),
2347                       /* Signed */ true, LHS, RHS)) {
2348     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2349     Deduced = true;
2350   }
2351 
2352   return {Flags, Deduced};
2353 }
2354 
2355 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2356 // `OldFlags' as can't-wrap behavior.  Infer a more aggressive set of
2357 // can't-overflow flags for the operation if possible.
2358 static SCEV::NoWrapFlags
2359 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
2360                       const ArrayRef<const SCEV *> Ops,
2361                       SCEV::NoWrapFlags Flags) {
2362   using namespace std::placeholders;
2363 
2364   using OBO = OverflowingBinaryOperator;
2365 
2366   bool CanAnalyze =
2367       Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
2368   (void)CanAnalyze;
2369   assert(CanAnalyze && "don't call from other places!");
2370 
2371   int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2372   SCEV::NoWrapFlags SignOrUnsignWrap =
2373       ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2374 
2375   // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2376   auto IsKnownNonNegative = [&](const SCEV *S) {
2377     return SE->isKnownNonNegative(S);
2378   };
2379 
2380   if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2381     Flags =
2382         ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
2383 
2384   SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2385 
2386   if (SignOrUnsignWrap != SignOrUnsignMask &&
2387       (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 &&
2388       isa<SCEVConstant>(Ops[0])) {
2389 
2390     auto Opcode = [&] {
2391       switch (Type) {
2392       case scAddExpr:
2393         return Instruction::Add;
2394       case scMulExpr:
2395         return Instruction::Mul;
2396       default:
2397         llvm_unreachable("Unexpected SCEV op.");
2398       }
2399     }();
2400 
2401     const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2402 
2403     // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow.
2404     if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2405       auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2406           Opcode, C, OBO::NoSignedWrap);
2407       if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2408         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2409     }
2410 
2411     // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow.
2412     if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2413       auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2414           Opcode, C, OBO::NoUnsignedWrap);
2415       if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2416         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2417     }
2418   }
2419 
2420   // <0,+,nonnegative><nw> is also nuw
2421   // TODO: Add corresponding nsw case
2422   if (Type == scAddRecExpr && ScalarEvolution::hasFlags(Flags, SCEV::FlagNW) &&
2423       !ScalarEvolution::hasFlags(Flags, SCEV::FlagNUW) && Ops.size() == 2 &&
2424       Ops[0]->isZero() && IsKnownNonNegative(Ops[1]))
2425     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2426 
2427   // both (udiv X, Y) * Y and Y * (udiv X, Y) are always NUW
2428   if (Type == scMulExpr && !ScalarEvolution::hasFlags(Flags, SCEV::FlagNUW) &&
2429       Ops.size() == 2) {
2430     if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[0]))
2431       if (UDiv->getOperand(1) == Ops[1])
2432         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2433     if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[1]))
2434       if (UDiv->getOperand(1) == Ops[0])
2435         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2436   }
2437 
2438   return Flags;
2439 }
2440 
2441 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) {
2442   return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader());
2443 }
2444 
2445 /// Get a canonical add expression, or something simpler if possible.
2446 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2447                                         SCEV::NoWrapFlags OrigFlags,
2448                                         unsigned Depth) {
2449   assert(!(OrigFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2450          "only nuw or nsw allowed");
2451   assert(!Ops.empty() && "Cannot get empty add!");
2452   if (Ops.size() == 1) return Ops[0];
2453 #ifndef NDEBUG
2454   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2455   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2456     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2457            "SCEVAddExpr operand types don't match!");
2458   unsigned NumPtrs = count_if(
2459       Ops, [](const SCEV *Op) { return Op->getType()->isPointerTy(); });
2460   assert(NumPtrs <= 1 && "add has at most one pointer operand");
2461 #endif
2462 
2463   // Sort by complexity, this groups all similar expression types together.
2464   GroupByComplexity(Ops, &LI, DT);
2465 
2466   // If there are any constants, fold them together.
2467   unsigned Idx = 0;
2468   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2469     ++Idx;
2470     assert(Idx < Ops.size());
2471     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2472       // We found two constants, fold them together!
2473       Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
2474       if (Ops.size() == 2) return Ops[0];
2475       Ops.erase(Ops.begin()+1);  // Erase the folded element
2476       LHSC = cast<SCEVConstant>(Ops[0]);
2477     }
2478 
2479     // If we are left with a constant zero being added, strip it off.
2480     if (LHSC->getValue()->isZero()) {
2481       Ops.erase(Ops.begin());
2482       --Idx;
2483     }
2484 
2485     if (Ops.size() == 1) return Ops[0];
2486   }
2487 
2488   // Delay expensive flag strengthening until necessary.
2489   auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) {
2490     return StrengthenNoWrapFlags(this, scAddExpr, Ops, OrigFlags);
2491   };
2492 
2493   // Limit recursion calls depth.
2494   if (Depth > MaxArithDepth || hasHugeExpression(Ops))
2495     return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
2496 
2497   if (SCEV *S = findExistingSCEVInCache(scAddExpr, Ops)) {
2498     // Don't strengthen flags if we have no new information.
2499     SCEVAddExpr *Add = static_cast<SCEVAddExpr *>(S);
2500     if (Add->getNoWrapFlags(OrigFlags) != OrigFlags)
2501       Add->setNoWrapFlags(ComputeFlags(Ops));
2502     return S;
2503   }
2504 
2505   // Okay, check to see if the same value occurs in the operand list more than
2506   // once.  If so, merge them together into an multiply expression.  Since we
2507   // sorted the list, these values are required to be adjacent.
2508   Type *Ty = Ops[0]->getType();
2509   bool FoundMatch = false;
2510   for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2511     if (Ops[i] == Ops[i+1]) {      //  X + Y + Y  -->  X + Y*2
2512       // Scan ahead to count how many equal operands there are.
2513       unsigned Count = 2;
2514       while (i+Count != e && Ops[i+Count] == Ops[i])
2515         ++Count;
2516       // Merge the values into a multiply.
2517       const SCEV *Scale = getConstant(Ty, Count);
2518       const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1);
2519       if (Ops.size() == Count)
2520         return Mul;
2521       Ops[i] = Mul;
2522       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2523       --i; e -= Count - 1;
2524       FoundMatch = true;
2525     }
2526   if (FoundMatch)
2527     return getAddExpr(Ops, OrigFlags, Depth + 1);
2528 
2529   // Check for truncates. If all the operands are truncated from the same
2530   // type, see if factoring out the truncate would permit the result to be
2531   // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
2532   // if the contents of the resulting outer trunc fold to something simple.
2533   auto FindTruncSrcType = [&]() -> Type * {
2534     // We're ultimately looking to fold an addrec of truncs and muls of only
2535     // constants and truncs, so if we find any other types of SCEV
2536     // as operands of the addrec then we bail and return nullptr here.
2537     // Otherwise, we return the type of the operand of a trunc that we find.
2538     if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx]))
2539       return T->getOperand()->getType();
2540     if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2541       const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1);
2542       if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp))
2543         return T->getOperand()->getType();
2544     }
2545     return nullptr;
2546   };
2547   if (auto *SrcType = FindTruncSrcType()) {
2548     SmallVector<const SCEV *, 8> LargeOps;
2549     bool Ok = true;
2550     // Check all the operands to see if they can be represented in the
2551     // source type of the truncate.
2552     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2553       if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2554         if (T->getOperand()->getType() != SrcType) {
2555           Ok = false;
2556           break;
2557         }
2558         LargeOps.push_back(T->getOperand());
2559       } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2560         LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2561       } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
2562         SmallVector<const SCEV *, 8> LargeMulOps;
2563         for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2564           if (const SCEVTruncateExpr *T =
2565                 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2566             if (T->getOperand()->getType() != SrcType) {
2567               Ok = false;
2568               break;
2569             }
2570             LargeMulOps.push_back(T->getOperand());
2571           } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2572             LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2573           } else {
2574             Ok = false;
2575             break;
2576           }
2577         }
2578         if (Ok)
2579           LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1));
2580       } else {
2581         Ok = false;
2582         break;
2583       }
2584     }
2585     if (Ok) {
2586       // Evaluate the expression in the larger type.
2587       const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1);
2588       // If it folds to something simple, use it. Otherwise, don't.
2589       if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2590         return getTruncateExpr(Fold, Ty);
2591     }
2592   }
2593 
2594   if (Ops.size() == 2) {
2595     // Check if we have an expression of the form ((X + C1) - C2), where C1 and
2596     // C2 can be folded in a way that allows retaining wrapping flags of (X +
2597     // C1).
2598     const SCEV *A = Ops[0];
2599     const SCEV *B = Ops[1];
2600     auto *AddExpr = dyn_cast<SCEVAddExpr>(B);
2601     auto *C = dyn_cast<SCEVConstant>(A);
2602     if (AddExpr && C && isa<SCEVConstant>(AddExpr->getOperand(0))) {
2603       auto C1 = cast<SCEVConstant>(AddExpr->getOperand(0))->getAPInt();
2604       auto C2 = C->getAPInt();
2605       SCEV::NoWrapFlags PreservedFlags = SCEV::FlagAnyWrap;
2606 
2607       APInt ConstAdd = C1 + C2;
2608       auto AddFlags = AddExpr->getNoWrapFlags();
2609       // Adding a smaller constant is NUW if the original AddExpr was NUW.
2610       if (ScalarEvolution::hasFlags(AddFlags, SCEV::FlagNUW) &&
2611           ConstAdd.ule(C1)) {
2612         PreservedFlags =
2613             ScalarEvolution::setFlags(PreservedFlags, SCEV::FlagNUW);
2614       }
2615 
2616       // Adding a constant with the same sign and small magnitude is NSW, if the
2617       // original AddExpr was NSW.
2618       if (ScalarEvolution::hasFlags(AddFlags, SCEV::FlagNSW) &&
2619           C1.isSignBitSet() == ConstAdd.isSignBitSet() &&
2620           ConstAdd.abs().ule(C1.abs())) {
2621         PreservedFlags =
2622             ScalarEvolution::setFlags(PreservedFlags, SCEV::FlagNSW);
2623       }
2624 
2625       if (PreservedFlags != SCEV::FlagAnyWrap) {
2626         SmallVector<const SCEV *, 4> NewOps(AddExpr->operands());
2627         NewOps[0] = getConstant(ConstAdd);
2628         return getAddExpr(NewOps, PreservedFlags);
2629       }
2630     }
2631   }
2632 
2633   // Canonicalize (-1 * urem X, Y) + X --> (Y * X/Y)
2634   if (Ops.size() == 2) {
2635     const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[0]);
2636     if (Mul && Mul->getNumOperands() == 2 &&
2637         Mul->getOperand(0)->isAllOnesValue()) {
2638       const SCEV *X;
2639       const SCEV *Y;
2640       if (matchURem(Mul->getOperand(1), X, Y) && X == Ops[1]) {
2641         return getMulExpr(Y, getUDivExpr(X, Y));
2642       }
2643     }
2644   }
2645 
2646   // Skip past any other cast SCEVs.
2647   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2648     ++Idx;
2649 
2650   // If there are add operands they would be next.
2651   if (Idx < Ops.size()) {
2652     bool DeletedAdd = false;
2653     // If the original flags and all inlined SCEVAddExprs are NUW, use the
2654     // common NUW flag for expression after inlining. Other flags cannot be
2655     // preserved, because they may depend on the original order of operations.
2656     SCEV::NoWrapFlags CommonFlags = maskFlags(OrigFlags, SCEV::FlagNUW);
2657     while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2658       if (Ops.size() > AddOpsInlineThreshold ||
2659           Add->getNumOperands() > AddOpsInlineThreshold)
2660         break;
2661       // If we have an add, expand the add operands onto the end of the operands
2662       // list.
2663       Ops.erase(Ops.begin()+Idx);
2664       Ops.append(Add->op_begin(), Add->op_end());
2665       DeletedAdd = true;
2666       CommonFlags = maskFlags(CommonFlags, Add->getNoWrapFlags());
2667     }
2668 
2669     // If we deleted at least one add, we added operands to the end of the list,
2670     // and they are not necessarily sorted.  Recurse to resort and resimplify
2671     // any operands we just acquired.
2672     if (DeletedAdd)
2673       return getAddExpr(Ops, CommonFlags, Depth + 1);
2674   }
2675 
2676   // Skip over the add expression until we get to a multiply.
2677   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2678     ++Idx;
2679 
2680   // Check to see if there are any folding opportunities present with
2681   // operands multiplied by constant values.
2682   if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2683     uint64_t BitWidth = getTypeSizeInBits(Ty);
2684     DenseMap<const SCEV *, APInt> M;
2685     SmallVector<const SCEV *, 8> NewOps;
2686     APInt AccumulatedConstant(BitWidth, 0);
2687     if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2688                                      Ops.data(), Ops.size(),
2689                                      APInt(BitWidth, 1), *this)) {
2690       struct APIntCompare {
2691         bool operator()(const APInt &LHS, const APInt &RHS) const {
2692           return LHS.ult(RHS);
2693         }
2694       };
2695 
2696       // Some interesting folding opportunity is present, so its worthwhile to
2697       // re-generate the operands list. Group the operands by constant scale,
2698       // to avoid multiplying by the same constant scale multiple times.
2699       std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
2700       for (const SCEV *NewOp : NewOps)
2701         MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2702       // Re-generate the operands list.
2703       Ops.clear();
2704       if (AccumulatedConstant != 0)
2705         Ops.push_back(getConstant(AccumulatedConstant));
2706       for (auto &MulOp : MulOpLists) {
2707         if (MulOp.first == 1) {
2708           Ops.push_back(getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1));
2709         } else if (MulOp.first != 0) {
2710           Ops.push_back(getMulExpr(
2711               getConstant(MulOp.first),
2712               getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1),
2713               SCEV::FlagAnyWrap, Depth + 1));
2714         }
2715       }
2716       if (Ops.empty())
2717         return getZero(Ty);
2718       if (Ops.size() == 1)
2719         return Ops[0];
2720       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2721     }
2722   }
2723 
2724   // If we are adding something to a multiply expression, make sure the
2725   // something is not already an operand of the multiply.  If so, merge it into
2726   // the multiply.
2727   for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2728     const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2729     for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2730       const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2731       if (isa<SCEVConstant>(MulOpSCEV))
2732         continue;
2733       for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
2734         if (MulOpSCEV == Ops[AddOp]) {
2735           // Fold W + X + (X * Y * Z)  -->  W + (X * ((Y*Z)+1))
2736           const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
2737           if (Mul->getNumOperands() != 2) {
2738             // If the multiply has more than two operands, we must get the
2739             // Y*Z term.
2740             SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2741                                                 Mul->op_begin()+MulOp);
2742             MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2743             InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2744           }
2745           SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul};
2746           const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2747           const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV,
2748                                             SCEV::FlagAnyWrap, Depth + 1);
2749           if (Ops.size() == 2) return OuterMul;
2750           if (AddOp < Idx) {
2751             Ops.erase(Ops.begin()+AddOp);
2752             Ops.erase(Ops.begin()+Idx-1);
2753           } else {
2754             Ops.erase(Ops.begin()+Idx);
2755             Ops.erase(Ops.begin()+AddOp-1);
2756           }
2757           Ops.push_back(OuterMul);
2758           return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2759         }
2760 
2761       // Check this multiply against other multiplies being added together.
2762       for (unsigned OtherMulIdx = Idx+1;
2763            OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2764            ++OtherMulIdx) {
2765         const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
2766         // If MulOp occurs in OtherMul, we can fold the two multiplies
2767         // together.
2768         for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2769              OMulOp != e; ++OMulOp)
2770           if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2771             // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
2772             const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
2773             if (Mul->getNumOperands() != 2) {
2774               SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2775                                                   Mul->op_begin()+MulOp);
2776               MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2777               InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2778             }
2779             const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
2780             if (OtherMul->getNumOperands() != 2) {
2781               SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
2782                                                   OtherMul->op_begin()+OMulOp);
2783               MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
2784               InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2785             }
2786             SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2};
2787             const SCEV *InnerMulSum =
2788                 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2789             const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum,
2790                                               SCEV::FlagAnyWrap, Depth + 1);
2791             if (Ops.size() == 2) return OuterMul;
2792             Ops.erase(Ops.begin()+Idx);
2793             Ops.erase(Ops.begin()+OtherMulIdx-1);
2794             Ops.push_back(OuterMul);
2795             return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2796           }
2797       }
2798     }
2799   }
2800 
2801   // If there are any add recurrences in the operands list, see if any other
2802   // added values are loop invariant.  If so, we can fold them into the
2803   // recurrence.
2804   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2805     ++Idx;
2806 
2807   // Scan over all recurrences, trying to fold loop invariants into them.
2808   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2809     // Scan all of the other operands to this add and add them to the vector if
2810     // they are loop invariant w.r.t. the recurrence.
2811     SmallVector<const SCEV *, 8> LIOps;
2812     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2813     const Loop *AddRecLoop = AddRec->getLoop();
2814     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2815       if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2816         LIOps.push_back(Ops[i]);
2817         Ops.erase(Ops.begin()+i);
2818         --i; --e;
2819       }
2820 
2821     // If we found some loop invariants, fold them into the recurrence.
2822     if (!LIOps.empty()) {
2823       // Compute nowrap flags for the addition of the loop-invariant ops and
2824       // the addrec. Temporarily push it as an operand for that purpose. These
2825       // flags are valid in the scope of the addrec only.
2826       LIOps.push_back(AddRec);
2827       SCEV::NoWrapFlags Flags = ComputeFlags(LIOps);
2828       LIOps.pop_back();
2829 
2830       //  NLI + LI + {Start,+,Step}  -->  NLI + {LI+Start,+,Step}
2831       LIOps.push_back(AddRec->getStart());
2832 
2833       SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands());
2834 
2835       // It is not in general safe to propagate flags valid on an add within
2836       // the addrec scope to one outside it.  We must prove that the inner
2837       // scope is guaranteed to execute if the outer one does to be able to
2838       // safely propagate.  We know the program is undefined if poison is
2839       // produced on the inner scoped addrec.  We also know that *for this use*
2840       // the outer scoped add can't overflow (because of the flags we just
2841       // computed for the inner scoped add) without the program being undefined.
2842       // Proving that entry to the outer scope neccesitates entry to the inner
2843       // scope, thus proves the program undefined if the flags would be violated
2844       // in the outer scope.
2845       SCEV::NoWrapFlags AddFlags = Flags;
2846       if (AddFlags != SCEV::FlagAnyWrap) {
2847         auto *DefI = getDefiningScopeBound(LIOps);
2848         auto *ReachI = &*AddRecLoop->getHeader()->begin();
2849         if (!isGuaranteedToTransferExecutionTo(DefI, ReachI))
2850           AddFlags = SCEV::FlagAnyWrap;
2851       }
2852       AddRecOps[0] = getAddExpr(LIOps, AddFlags, Depth + 1);
2853 
2854       // Build the new addrec. Propagate the NUW and NSW flags if both the
2855       // outer add and the inner addrec are guaranteed to have no overflow.
2856       // Always propagate NW.
2857       Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2858       const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2859 
2860       // If all of the other operands were loop invariant, we are done.
2861       if (Ops.size() == 1) return NewRec;
2862 
2863       // Otherwise, add the folded AddRec by the non-invariant parts.
2864       for (unsigned i = 0;; ++i)
2865         if (Ops[i] == AddRec) {
2866           Ops[i] = NewRec;
2867           break;
2868         }
2869       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2870     }
2871 
2872     // Okay, if there weren't any loop invariants to be folded, check to see if
2873     // there are multiple AddRec's with the same loop induction variable being
2874     // added together.  If so, we can fold them.
2875     for (unsigned OtherIdx = Idx+1;
2876          OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2877          ++OtherIdx) {
2878       // We expect the AddRecExpr's to be sorted in reverse dominance order,
2879       // so that the 1st found AddRecExpr is dominated by all others.
2880       assert(DT.dominates(
2881            cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
2882            AddRec->getLoop()->getHeader()) &&
2883         "AddRecExprs are not sorted in reverse dominance order?");
2884       if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2885         // Other + {A,+,B}<L> + {C,+,D}<L>  -->  Other + {A+C,+,B+D}<L>
2886         SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands());
2887         for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2888              ++OtherIdx) {
2889           const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2890           if (OtherAddRec->getLoop() == AddRecLoop) {
2891             for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2892                  i != e; ++i) {
2893               if (i >= AddRecOps.size()) {
2894                 AddRecOps.append(OtherAddRec->op_begin()+i,
2895                                  OtherAddRec->op_end());
2896                 break;
2897               }
2898               SmallVector<const SCEV *, 2> TwoOps = {
2899                   AddRecOps[i], OtherAddRec->getOperand(i)};
2900               AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2901             }
2902             Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2903           }
2904         }
2905         // Step size has changed, so we cannot guarantee no self-wraparound.
2906         Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2907         return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2908       }
2909     }
2910 
2911     // Otherwise couldn't fold anything into this recurrence.  Move onto the
2912     // next one.
2913   }
2914 
2915   // Okay, it looks like we really DO need an add expr.  Check to see if we
2916   // already have one, otherwise create a new one.
2917   return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
2918 }
2919 
2920 const SCEV *
2921 ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops,
2922                                     SCEV::NoWrapFlags Flags) {
2923   FoldingSetNodeID ID;
2924   ID.AddInteger(scAddExpr);
2925   for (const SCEV *Op : Ops)
2926     ID.AddPointer(Op);
2927   void *IP = nullptr;
2928   SCEVAddExpr *S =
2929       static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2930   if (!S) {
2931     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2932     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2933     S = new (SCEVAllocator)
2934         SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
2935     UniqueSCEVs.InsertNode(S, IP);
2936     registerUser(S, Ops);
2937   }
2938   S->setNoWrapFlags(Flags);
2939   return S;
2940 }
2941 
2942 const SCEV *
2943 ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops,
2944                                        const Loop *L, SCEV::NoWrapFlags Flags) {
2945   FoldingSetNodeID ID;
2946   ID.AddInteger(scAddRecExpr);
2947   for (const SCEV *Op : Ops)
2948     ID.AddPointer(Op);
2949   ID.AddPointer(L);
2950   void *IP = nullptr;
2951   SCEVAddRecExpr *S =
2952       static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2953   if (!S) {
2954     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2955     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2956     S = new (SCEVAllocator)
2957         SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L);
2958     UniqueSCEVs.InsertNode(S, IP);
2959     LoopUsers[L].push_back(S);
2960     registerUser(S, Ops);
2961   }
2962   setNoWrapFlags(S, Flags);
2963   return S;
2964 }
2965 
2966 const SCEV *
2967 ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops,
2968                                     SCEV::NoWrapFlags Flags) {
2969   FoldingSetNodeID ID;
2970   ID.AddInteger(scMulExpr);
2971   for (const SCEV *Op : Ops)
2972     ID.AddPointer(Op);
2973   void *IP = nullptr;
2974   SCEVMulExpr *S =
2975     static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2976   if (!S) {
2977     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2978     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2979     S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2980                                         O, Ops.size());
2981     UniqueSCEVs.InsertNode(S, IP);
2982     registerUser(S, Ops);
2983   }
2984   S->setNoWrapFlags(Flags);
2985   return S;
2986 }
2987 
2988 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2989   uint64_t k = i*j;
2990   if (j > 1 && k / j != i) Overflow = true;
2991   return k;
2992 }
2993 
2994 /// Compute the result of "n choose k", the binomial coefficient.  If an
2995 /// intermediate computation overflows, Overflow will be set and the return will
2996 /// be garbage. Overflow is not cleared on absence of overflow.
2997 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2998   // We use the multiplicative formula:
2999   //     n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
3000   // At each iteration, we take the n-th term of the numeral and divide by the
3001   // (k-n)th term of the denominator.  This division will always produce an
3002   // integral result, and helps reduce the chance of overflow in the
3003   // intermediate computations. However, we can still overflow even when the
3004   // final result would fit.
3005 
3006   if (n == 0 || n == k) return 1;
3007   if (k > n) return 0;
3008 
3009   if (k > n/2)
3010     k = n-k;
3011 
3012   uint64_t r = 1;
3013   for (uint64_t i = 1; i <= k; ++i) {
3014     r = umul_ov(r, n-(i-1), Overflow);
3015     r /= i;
3016   }
3017   return r;
3018 }
3019 
3020 /// Determine if any of the operands in this SCEV are a constant or if
3021 /// any of the add or multiply expressions in this SCEV contain a constant.
3022 static bool containsConstantInAddMulChain(const SCEV *StartExpr) {
3023   struct FindConstantInAddMulChain {
3024     bool FoundConstant = false;
3025 
3026     bool follow(const SCEV *S) {
3027       FoundConstant |= isa<SCEVConstant>(S);
3028       return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
3029     }
3030 
3031     bool isDone() const {
3032       return FoundConstant;
3033     }
3034   };
3035 
3036   FindConstantInAddMulChain F;
3037   SCEVTraversal<FindConstantInAddMulChain> ST(F);
3038   ST.visitAll(StartExpr);
3039   return F.FoundConstant;
3040 }
3041 
3042 /// Get a canonical multiply expression, or something simpler if possible.
3043 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
3044                                         SCEV::NoWrapFlags OrigFlags,
3045                                         unsigned Depth) {
3046   assert(OrigFlags == maskFlags(OrigFlags, SCEV::FlagNUW | SCEV::FlagNSW) &&
3047          "only nuw or nsw allowed");
3048   assert(!Ops.empty() && "Cannot get empty mul!");
3049   if (Ops.size() == 1) return Ops[0];
3050 #ifndef NDEBUG
3051   Type *ETy = Ops[0]->getType();
3052   assert(!ETy->isPointerTy());
3053   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3054     assert(Ops[i]->getType() == ETy &&
3055            "SCEVMulExpr operand types don't match!");
3056 #endif
3057 
3058   // Sort by complexity, this groups all similar expression types together.
3059   GroupByComplexity(Ops, &LI, DT);
3060 
3061   // If there are any constants, fold them together.
3062   unsigned Idx = 0;
3063   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3064     ++Idx;
3065     assert(Idx < Ops.size());
3066     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3067       // We found two constants, fold them together!
3068       Ops[0] = getConstant(LHSC->getAPInt() * RHSC->getAPInt());
3069       if (Ops.size() == 2) return Ops[0];
3070       Ops.erase(Ops.begin()+1);  // Erase the folded element
3071       LHSC = cast<SCEVConstant>(Ops[0]);
3072     }
3073 
3074     // If we have a multiply of zero, it will always be zero.
3075     if (LHSC->getValue()->isZero())
3076       return LHSC;
3077 
3078     // If we are left with a constant one being multiplied, strip it off.
3079     if (LHSC->getValue()->isOne()) {
3080       Ops.erase(Ops.begin());
3081       --Idx;
3082     }
3083 
3084     if (Ops.size() == 1)
3085       return Ops[0];
3086   }
3087 
3088   // Delay expensive flag strengthening until necessary.
3089   auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) {
3090     return StrengthenNoWrapFlags(this, scMulExpr, Ops, OrigFlags);
3091   };
3092 
3093   // Limit recursion calls depth.
3094   if (Depth > MaxArithDepth || hasHugeExpression(Ops))
3095     return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
3096 
3097   if (SCEV *S = findExistingSCEVInCache(scMulExpr, Ops)) {
3098     // Don't strengthen flags if we have no new information.
3099     SCEVMulExpr *Mul = static_cast<SCEVMulExpr *>(S);
3100     if (Mul->getNoWrapFlags(OrigFlags) != OrigFlags)
3101       Mul->setNoWrapFlags(ComputeFlags(Ops));
3102     return S;
3103   }
3104 
3105   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3106     if (Ops.size() == 2) {
3107       // C1*(C2+V) -> C1*C2 + C1*V
3108       if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
3109         // If any of Add's ops are Adds or Muls with a constant, apply this
3110         // transformation as well.
3111         //
3112         // TODO: There are some cases where this transformation is not
3113         // profitable; for example, Add = (C0 + X) * Y + Z.  Maybe the scope of
3114         // this transformation should be narrowed down.
3115         if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add))
3116           return getAddExpr(getMulExpr(LHSC, Add->getOperand(0),
3117                                        SCEV::FlagAnyWrap, Depth + 1),
3118                             getMulExpr(LHSC, Add->getOperand(1),
3119                                        SCEV::FlagAnyWrap, Depth + 1),
3120                             SCEV::FlagAnyWrap, Depth + 1);
3121 
3122       if (Ops[0]->isAllOnesValue()) {
3123         // If we have a mul by -1 of an add, try distributing the -1 among the
3124         // add operands.
3125         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
3126           SmallVector<const SCEV *, 4> NewOps;
3127           bool AnyFolded = false;
3128           for (const SCEV *AddOp : Add->operands()) {
3129             const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap,
3130                                          Depth + 1);
3131             if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
3132             NewOps.push_back(Mul);
3133           }
3134           if (AnyFolded)
3135             return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1);
3136         } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
3137           // Negation preserves a recurrence's no self-wrap property.
3138           SmallVector<const SCEV *, 4> Operands;
3139           for (const SCEV *AddRecOp : AddRec->operands())
3140             Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap,
3141                                           Depth + 1));
3142 
3143           return getAddRecExpr(Operands, AddRec->getLoop(),
3144                                AddRec->getNoWrapFlags(SCEV::FlagNW));
3145         }
3146       }
3147     }
3148   }
3149 
3150   // Skip over the add expression until we get to a multiply.
3151   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
3152     ++Idx;
3153 
3154   // If there are mul operands inline them all into this expression.
3155   if (Idx < Ops.size()) {
3156     bool DeletedMul = false;
3157     while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
3158       if (Ops.size() > MulOpsInlineThreshold)
3159         break;
3160       // If we have an mul, expand the mul operands onto the end of the
3161       // operands list.
3162       Ops.erase(Ops.begin()+Idx);
3163       Ops.append(Mul->op_begin(), Mul->op_end());
3164       DeletedMul = true;
3165     }
3166 
3167     // If we deleted at least one mul, we added operands to the end of the
3168     // list, and they are not necessarily sorted.  Recurse to resort and
3169     // resimplify any operands we just acquired.
3170     if (DeletedMul)
3171       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3172   }
3173 
3174   // If there are any add recurrences in the operands list, see if any other
3175   // added values are loop invariant.  If so, we can fold them into the
3176   // recurrence.
3177   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
3178     ++Idx;
3179 
3180   // Scan over all recurrences, trying to fold loop invariants into them.
3181   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
3182     // Scan all of the other operands to this mul and add them to the vector
3183     // if they are loop invariant w.r.t. the recurrence.
3184     SmallVector<const SCEV *, 8> LIOps;
3185     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
3186     const Loop *AddRecLoop = AddRec->getLoop();
3187     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3188       if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
3189         LIOps.push_back(Ops[i]);
3190         Ops.erase(Ops.begin()+i);
3191         --i; --e;
3192       }
3193 
3194     // If we found some loop invariants, fold them into the recurrence.
3195     if (!LIOps.empty()) {
3196       //  NLI * LI * {Start,+,Step}  -->  NLI * {LI*Start,+,LI*Step}
3197       SmallVector<const SCEV *, 4> NewOps;
3198       NewOps.reserve(AddRec->getNumOperands());
3199       const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1);
3200       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
3201         NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
3202                                     SCEV::FlagAnyWrap, Depth + 1));
3203 
3204       // Build the new addrec. Propagate the NUW and NSW flags if both the
3205       // outer mul and the inner addrec are guaranteed to have no overflow.
3206       //
3207       // No self-wrap cannot be guaranteed after changing the step size, but
3208       // will be inferred if either NUW or NSW is true.
3209       SCEV::NoWrapFlags Flags = ComputeFlags({Scale, AddRec});
3210       const SCEV *NewRec = getAddRecExpr(
3211           NewOps, AddRecLoop, AddRec->getNoWrapFlags(Flags));
3212 
3213       // If all of the other operands were loop invariant, we are done.
3214       if (Ops.size() == 1) return NewRec;
3215 
3216       // Otherwise, multiply the folded AddRec by the non-invariant parts.
3217       for (unsigned i = 0;; ++i)
3218         if (Ops[i] == AddRec) {
3219           Ops[i] = NewRec;
3220           break;
3221         }
3222       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3223     }
3224 
3225     // Okay, if there weren't any loop invariants to be folded, check to see
3226     // if there are multiple AddRec's with the same loop induction variable
3227     // being multiplied together.  If so, we can fold them.
3228 
3229     // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
3230     // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
3231     //       choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
3232     //   ]]],+,...up to x=2n}.
3233     // Note that the arguments to choose() are always integers with values
3234     // known at compile time, never SCEV objects.
3235     //
3236     // The implementation avoids pointless extra computations when the two
3237     // addrec's are of different length (mathematically, it's equivalent to
3238     // an infinite stream of zeros on the right).
3239     bool OpsModified = false;
3240     for (unsigned OtherIdx = Idx+1;
3241          OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
3242          ++OtherIdx) {
3243       const SCEVAddRecExpr *OtherAddRec =
3244         dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
3245       if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
3246         continue;
3247 
3248       // Limit max number of arguments to avoid creation of unreasonably big
3249       // SCEVAddRecs with very complex operands.
3250       if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
3251           MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec}))
3252         continue;
3253 
3254       bool Overflow = false;
3255       Type *Ty = AddRec->getType();
3256       bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
3257       SmallVector<const SCEV*, 7> AddRecOps;
3258       for (int x = 0, xe = AddRec->getNumOperands() +
3259              OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
3260         SmallVector <const SCEV *, 7> SumOps;
3261         for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
3262           uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
3263           for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
3264                  ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
3265                z < ze && !Overflow; ++z) {
3266             uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
3267             uint64_t Coeff;
3268             if (LargerThan64Bits)
3269               Coeff = umul_ov(Coeff1, Coeff2, Overflow);
3270             else
3271               Coeff = Coeff1*Coeff2;
3272             const SCEV *CoeffTerm = getConstant(Ty, Coeff);
3273             const SCEV *Term1 = AddRec->getOperand(y-z);
3274             const SCEV *Term2 = OtherAddRec->getOperand(z);
3275             SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2,
3276                                         SCEV::FlagAnyWrap, Depth + 1));
3277           }
3278         }
3279         if (SumOps.empty())
3280           SumOps.push_back(getZero(Ty));
3281         AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1));
3282       }
3283       if (!Overflow) {
3284         const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRecLoop,
3285                                               SCEV::FlagAnyWrap);
3286         if (Ops.size() == 2) return NewAddRec;
3287         Ops[Idx] = NewAddRec;
3288         Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
3289         OpsModified = true;
3290         AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
3291         if (!AddRec)
3292           break;
3293       }
3294     }
3295     if (OpsModified)
3296       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3297 
3298     // Otherwise couldn't fold anything into this recurrence.  Move onto the
3299     // next one.
3300   }
3301 
3302   // Okay, it looks like we really DO need an mul expr.  Check to see if we
3303   // already have one, otherwise create a new one.
3304   return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
3305 }
3306 
3307 /// Represents an unsigned remainder expression based on unsigned division.
3308 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS,
3309                                          const SCEV *RHS) {
3310   assert(getEffectiveSCEVType(LHS->getType()) ==
3311          getEffectiveSCEVType(RHS->getType()) &&
3312          "SCEVURemExpr operand types don't match!");
3313 
3314   // Short-circuit easy cases
3315   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3316     // If constant is one, the result is trivial
3317     if (RHSC->getValue()->isOne())
3318       return getZero(LHS->getType()); // X urem 1 --> 0
3319 
3320     // If constant is a power of two, fold into a zext(trunc(LHS)).
3321     if (RHSC->getAPInt().isPowerOf2()) {
3322       Type *FullTy = LHS->getType();
3323       Type *TruncTy =
3324           IntegerType::get(getContext(), RHSC->getAPInt().logBase2());
3325       return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy);
3326     }
3327   }
3328 
3329   // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
3330   const SCEV *UDiv = getUDivExpr(LHS, RHS);
3331   const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW);
3332   return getMinusSCEV(LHS, Mult, SCEV::FlagNUW);
3333 }
3334 
3335 /// Get a canonical unsigned division expression, or something simpler if
3336 /// possible.
3337 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
3338                                          const SCEV *RHS) {
3339   assert(!LHS->getType()->isPointerTy() &&
3340          "SCEVUDivExpr operand can't be pointer!");
3341   assert(LHS->getType() == RHS->getType() &&
3342          "SCEVUDivExpr operand types don't match!");
3343 
3344   FoldingSetNodeID ID;
3345   ID.AddInteger(scUDivExpr);
3346   ID.AddPointer(LHS);
3347   ID.AddPointer(RHS);
3348   void *IP = nullptr;
3349   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
3350     return S;
3351 
3352   // 0 udiv Y == 0
3353   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS))
3354     if (LHSC->getValue()->isZero())
3355       return LHS;
3356 
3357   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3358     if (RHSC->getValue()->isOne())
3359       return LHS;                               // X udiv 1 --> x
3360     // If the denominator is zero, the result of the udiv is undefined. Don't
3361     // try to analyze it, because the resolution chosen here may differ from
3362     // the resolution chosen in other parts of the compiler.
3363     if (!RHSC->getValue()->isZero()) {
3364       // Determine if the division can be folded into the operands of
3365       // its operands.
3366       // TODO: Generalize this to non-constants by using known-bits information.
3367       Type *Ty = LHS->getType();
3368       unsigned LZ = RHSC->getAPInt().countLeadingZeros();
3369       unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
3370       // For non-power-of-two values, effectively round the value up to the
3371       // nearest power of two.
3372       if (!RHSC->getAPInt().isPowerOf2())
3373         ++MaxShiftAmt;
3374       IntegerType *ExtTy =
3375         IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
3376       if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
3377         if (const SCEVConstant *Step =
3378             dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
3379           // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
3380           const APInt &StepInt = Step->getAPInt();
3381           const APInt &DivInt = RHSC->getAPInt();
3382           if (!StepInt.urem(DivInt) &&
3383               getZeroExtendExpr(AR, ExtTy) ==
3384               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3385                             getZeroExtendExpr(Step, ExtTy),
3386                             AR->getLoop(), SCEV::FlagAnyWrap)) {
3387             SmallVector<const SCEV *, 4> Operands;
3388             for (const SCEV *Op : AR->operands())
3389               Operands.push_back(getUDivExpr(Op, RHS));
3390             return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
3391           }
3392           /// Get a canonical UDivExpr for a recurrence.
3393           /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
3394           // We can currently only fold X%N if X is constant.
3395           const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
3396           if (StartC && !DivInt.urem(StepInt) &&
3397               getZeroExtendExpr(AR, ExtTy) ==
3398               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3399                             getZeroExtendExpr(Step, ExtTy),
3400                             AR->getLoop(), SCEV::FlagAnyWrap)) {
3401             const APInt &StartInt = StartC->getAPInt();
3402             const APInt &StartRem = StartInt.urem(StepInt);
3403             if (StartRem != 0) {
3404               const SCEV *NewLHS =
3405                   getAddRecExpr(getConstant(StartInt - StartRem), Step,
3406                                 AR->getLoop(), SCEV::FlagNW);
3407               if (LHS != NewLHS) {
3408                 LHS = NewLHS;
3409 
3410                 // Reset the ID to include the new LHS, and check if it is
3411                 // already cached.
3412                 ID.clear();
3413                 ID.AddInteger(scUDivExpr);
3414                 ID.AddPointer(LHS);
3415                 ID.AddPointer(RHS);
3416                 IP = nullptr;
3417                 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
3418                   return S;
3419               }
3420             }
3421           }
3422         }
3423       // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
3424       if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
3425         SmallVector<const SCEV *, 4> Operands;
3426         for (const SCEV *Op : M->operands())
3427           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3428         if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
3429           // Find an operand that's safely divisible.
3430           for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3431             const SCEV *Op = M->getOperand(i);
3432             const SCEV *Div = getUDivExpr(Op, RHSC);
3433             if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
3434               Operands = SmallVector<const SCEV *, 4>(M->operands());
3435               Operands[i] = Div;
3436               return getMulExpr(Operands);
3437             }
3438           }
3439       }
3440 
3441       // (A/B)/C --> A/(B*C) if safe and B*C can be folded.
3442       if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) {
3443         if (auto *DivisorConstant =
3444                 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) {
3445           bool Overflow = false;
3446           APInt NewRHS =
3447               DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow);
3448           if (Overflow) {
3449             return getConstant(RHSC->getType(), 0, false);
3450           }
3451           return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS));
3452         }
3453       }
3454 
3455       // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
3456       if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
3457         SmallVector<const SCEV *, 4> Operands;
3458         for (const SCEV *Op : A->operands())
3459           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3460         if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
3461           Operands.clear();
3462           for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
3463             const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
3464             if (isa<SCEVUDivExpr>(Op) ||
3465                 getMulExpr(Op, RHS) != A->getOperand(i))
3466               break;
3467             Operands.push_back(Op);
3468           }
3469           if (Operands.size() == A->getNumOperands())
3470             return getAddExpr(Operands);
3471         }
3472       }
3473 
3474       // Fold if both operands are constant.
3475       if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
3476         Constant *LHSCV = LHSC->getValue();
3477         Constant *RHSCV = RHSC->getValue();
3478         return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
3479                                                                    RHSCV)));
3480       }
3481     }
3482   }
3483 
3484   // The Insertion Point (IP) might be invalid by now (due to UniqueSCEVs
3485   // changes). Make sure we get a new one.
3486   IP = nullptr;
3487   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3488   SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
3489                                              LHS, RHS);
3490   UniqueSCEVs.InsertNode(S, IP);
3491   registerUser(S, {LHS, RHS});
3492   return S;
3493 }
3494 
3495 APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
3496   APInt A = C1->getAPInt().abs();
3497   APInt B = C2->getAPInt().abs();
3498   uint32_t ABW = A.getBitWidth();
3499   uint32_t BBW = B.getBitWidth();
3500 
3501   if (ABW > BBW)
3502     B = B.zext(ABW);
3503   else if (ABW < BBW)
3504     A = A.zext(BBW);
3505 
3506   return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B));
3507 }
3508 
3509 /// Get a canonical unsigned division expression, or something simpler if
3510 /// possible. There is no representation for an exact udiv in SCEV IR, but we
3511 /// can attempt to remove factors from the LHS and RHS.  We can't do this when
3512 /// it's not exact because the udiv may be clearing bits.
3513 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
3514                                               const SCEV *RHS) {
3515   // TODO: we could try to find factors in all sorts of things, but for now we
3516   // just deal with u/exact (multiply, constant). See SCEVDivision towards the
3517   // end of this file for inspiration.
3518 
3519   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
3520   if (!Mul || !Mul->hasNoUnsignedWrap())
3521     return getUDivExpr(LHS, RHS);
3522 
3523   if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
3524     // If the mulexpr multiplies by a constant, then that constant must be the
3525     // first element of the mulexpr.
3526     if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
3527       if (LHSCst == RHSCst) {
3528         SmallVector<const SCEV *, 2> Operands(drop_begin(Mul->operands()));
3529         return getMulExpr(Operands);
3530       }
3531 
3532       // We can't just assume that LHSCst divides RHSCst cleanly, it could be
3533       // that there's a factor provided by one of the other terms. We need to
3534       // check.
3535       APInt Factor = gcd(LHSCst, RHSCst);
3536       if (!Factor.isIntN(1)) {
3537         LHSCst =
3538             cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
3539         RHSCst =
3540             cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
3541         SmallVector<const SCEV *, 2> Operands;
3542         Operands.push_back(LHSCst);
3543         Operands.append(Mul->op_begin() + 1, Mul->op_end());
3544         LHS = getMulExpr(Operands);
3545         RHS = RHSCst;
3546         Mul = dyn_cast<SCEVMulExpr>(LHS);
3547         if (!Mul)
3548           return getUDivExactExpr(LHS, RHS);
3549       }
3550     }
3551   }
3552 
3553   for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3554     if (Mul->getOperand(i) == RHS) {
3555       SmallVector<const SCEV *, 2> Operands;
3556       Operands.append(Mul->op_begin(), Mul->op_begin() + i);
3557       Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
3558       return getMulExpr(Operands);
3559     }
3560   }
3561 
3562   return getUDivExpr(LHS, RHS);
3563 }
3564 
3565 /// Get an add recurrence expression for the specified loop.  Simplify the
3566 /// expression as much as possible.
3567 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
3568                                            const Loop *L,
3569                                            SCEV::NoWrapFlags Flags) {
3570   SmallVector<const SCEV *, 4> Operands;
3571   Operands.push_back(Start);
3572   if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3573     if (StepChrec->getLoop() == L) {
3574       Operands.append(StepChrec->op_begin(), StepChrec->op_end());
3575       return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
3576     }
3577 
3578   Operands.push_back(Step);
3579   return getAddRecExpr(Operands, L, Flags);
3580 }
3581 
3582 /// Get an add recurrence expression for the specified loop.  Simplify the
3583 /// expression as much as possible.
3584 const SCEV *
3585 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
3586                                const Loop *L, SCEV::NoWrapFlags Flags) {
3587   if (Operands.size() == 1) return Operands[0];
3588 #ifndef NDEBUG
3589   Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
3590   for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
3591     assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
3592            "SCEVAddRecExpr operand types don't match!");
3593     assert(!Operands[i]->getType()->isPointerTy() && "Step must be integer");
3594   }
3595   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3596     assert(isLoopInvariant(Operands[i], L) &&
3597            "SCEVAddRecExpr operand is not loop-invariant!");
3598 #endif
3599 
3600   if (Operands.back()->isZero()) {
3601     Operands.pop_back();
3602     return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0}  -->  X
3603   }
3604 
3605   // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and
3606   // use that information to infer NUW and NSW flags. However, computing a
3607   // BE count requires calling getAddRecExpr, so we may not yet have a
3608   // meaningful BE count at this point (and if we don't, we'd be stuck
3609   // with a SCEVCouldNotCompute as the cached BE count).
3610 
3611   Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
3612 
3613   // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3614   if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3615     const Loop *NestedLoop = NestedAR->getLoop();
3616     if (L->contains(NestedLoop)
3617             ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3618             : (!NestedLoop->contains(L) &&
3619                DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3620       SmallVector<const SCEV *, 4> NestedOperands(NestedAR->operands());
3621       Operands[0] = NestedAR->getStart();
3622       // AddRecs require their operands be loop-invariant with respect to their
3623       // loops. Don't perform this transformation if it would break this
3624       // requirement.
3625       bool AllInvariant = all_of(
3626           Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3627 
3628       if (AllInvariant) {
3629         // Create a recurrence for the outer loop with the same step size.
3630         //
3631         // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3632         // inner recurrence has the same property.
3633         SCEV::NoWrapFlags OuterFlags =
3634           maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3635 
3636         NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3637         AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3638           return isLoopInvariant(Op, NestedLoop);
3639         });
3640 
3641         if (AllInvariant) {
3642           // Ok, both add recurrences are valid after the transformation.
3643           //
3644           // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3645           // the outer recurrence has the same property.
3646           SCEV::NoWrapFlags InnerFlags =
3647             maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
3648           return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3649         }
3650       }
3651       // Reset Operands to its original state.
3652       Operands[0] = NestedAR;
3653     }
3654   }
3655 
3656   // Okay, it looks like we really DO need an addrec expr.  Check to see if we
3657   // already have one, otherwise create a new one.
3658   return getOrCreateAddRecExpr(Operands, L, Flags);
3659 }
3660 
3661 const SCEV *
3662 ScalarEvolution::getGEPExpr(GEPOperator *GEP,
3663                             const SmallVectorImpl<const SCEV *> &IndexExprs) {
3664   const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3665   // getSCEV(Base)->getType() has the same address space as Base->getType()
3666   // because SCEV::getType() preserves the address space.
3667   Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType());
3668   const bool AssumeInBoundsFlags = [&]() {
3669     if (!GEP->isInBounds())
3670       return false;
3671 
3672     // We'd like to propagate flags from the IR to the corresponding SCEV nodes,
3673     // but to do that, we have to ensure that said flag is valid in the entire
3674     // defined scope of the SCEV.
3675     auto *GEPI = dyn_cast<Instruction>(GEP);
3676     // TODO: non-instructions have global scope.  We might be able to prove
3677     // some global scope cases
3678     return GEPI && isSCEVExprNeverPoison(GEPI);
3679   }();
3680 
3681   SCEV::NoWrapFlags OffsetWrap =
3682     AssumeInBoundsFlags ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3683 
3684   Type *CurTy = GEP->getType();
3685   bool FirstIter = true;
3686   SmallVector<const SCEV *, 4> Offsets;
3687   for (const SCEV *IndexExpr : IndexExprs) {
3688     // Compute the (potentially symbolic) offset in bytes for this index.
3689     if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3690       // For a struct, add the member offset.
3691       ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3692       unsigned FieldNo = Index->getZExtValue();
3693       const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo);
3694       Offsets.push_back(FieldOffset);
3695 
3696       // Update CurTy to the type of the field at Index.
3697       CurTy = STy->getTypeAtIndex(Index);
3698     } else {
3699       // Update CurTy to its element type.
3700       if (FirstIter) {
3701         assert(isa<PointerType>(CurTy) &&
3702                "The first index of a GEP indexes a pointer");
3703         CurTy = GEP->getSourceElementType();
3704         FirstIter = false;
3705       } else {
3706         CurTy = GetElementPtrInst::getTypeAtIndex(CurTy, (uint64_t)0);
3707       }
3708       // For an array, add the element offset, explicitly scaled.
3709       const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy);
3710       // Getelementptr indices are signed.
3711       IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy);
3712 
3713       // Multiply the index by the element size to compute the element offset.
3714       const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, OffsetWrap);
3715       Offsets.push_back(LocalOffset);
3716     }
3717   }
3718 
3719   // Handle degenerate case of GEP without offsets.
3720   if (Offsets.empty())
3721     return BaseExpr;
3722 
3723   // Add the offsets together, assuming nsw if inbounds.
3724   const SCEV *Offset = getAddExpr(Offsets, OffsetWrap);
3725   // Add the base address and the offset. We cannot use the nsw flag, as the
3726   // base address is unsigned. However, if we know that the offset is
3727   // non-negative, we can use nuw.
3728   SCEV::NoWrapFlags BaseWrap = AssumeInBoundsFlags && isKnownNonNegative(Offset)
3729                                    ? SCEV::FlagNUW : SCEV::FlagAnyWrap;
3730   auto *GEPExpr = getAddExpr(BaseExpr, Offset, BaseWrap);
3731   assert(BaseExpr->getType() == GEPExpr->getType() &&
3732          "GEP should not change type mid-flight.");
3733   return GEPExpr;
3734 }
3735 
3736 SCEV *ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType,
3737                                                ArrayRef<const SCEV *> Ops) {
3738   FoldingSetNodeID ID;
3739   ID.AddInteger(SCEVType);
3740   for (const SCEV *Op : Ops)
3741     ID.AddPointer(Op);
3742   void *IP = nullptr;
3743   return UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
3744 }
3745 
3746 const SCEV *ScalarEvolution::getAbsExpr(const SCEV *Op, bool IsNSW) {
3747   SCEV::NoWrapFlags Flags = IsNSW ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3748   return getSMaxExpr(Op, getNegativeSCEV(Op, Flags));
3749 }
3750 
3751 const SCEV *ScalarEvolution::getMinMaxExpr(SCEVTypes Kind,
3752                                            SmallVectorImpl<const SCEV *> &Ops) {
3753   assert(SCEVMinMaxExpr::isMinMaxType(Kind) && "Not a SCEVMinMaxExpr!");
3754   assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
3755   if (Ops.size() == 1) return Ops[0];
3756 #ifndef NDEBUG
3757   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3758   for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
3759     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3760            "Operand types don't match!");
3761     assert(Ops[0]->getType()->isPointerTy() ==
3762                Ops[i]->getType()->isPointerTy() &&
3763            "min/max should be consistently pointerish");
3764   }
3765 #endif
3766 
3767   bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr;
3768   bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr;
3769 
3770   // Sort by complexity, this groups all similar expression types together.
3771   GroupByComplexity(Ops, &LI, DT);
3772 
3773   // Check if we have created the same expression before.
3774   if (const SCEV *S = findExistingSCEVInCache(Kind, Ops)) {
3775     return S;
3776   }
3777 
3778   // If there are any constants, fold them together.
3779   unsigned Idx = 0;
3780   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3781     ++Idx;
3782     assert(Idx < Ops.size());
3783     auto FoldOp = [&](const APInt &LHS, const APInt &RHS) {
3784       if (Kind == scSMaxExpr)
3785         return APIntOps::smax(LHS, RHS);
3786       else if (Kind == scSMinExpr)
3787         return APIntOps::smin(LHS, RHS);
3788       else if (Kind == scUMaxExpr)
3789         return APIntOps::umax(LHS, RHS);
3790       else if (Kind == scUMinExpr)
3791         return APIntOps::umin(LHS, RHS);
3792       llvm_unreachable("Unknown SCEV min/max opcode");
3793     };
3794 
3795     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3796       // We found two constants, fold them together!
3797       ConstantInt *Fold = ConstantInt::get(
3798           getContext(), FoldOp(LHSC->getAPInt(), RHSC->getAPInt()));
3799       Ops[0] = getConstant(Fold);
3800       Ops.erase(Ops.begin()+1);  // Erase the folded element
3801       if (Ops.size() == 1) return Ops[0];
3802       LHSC = cast<SCEVConstant>(Ops[0]);
3803     }
3804 
3805     bool IsMinV = LHSC->getValue()->isMinValue(IsSigned);
3806     bool IsMaxV = LHSC->getValue()->isMaxValue(IsSigned);
3807 
3808     if (IsMax ? IsMinV : IsMaxV) {
3809       // If we are left with a constant minimum(/maximum)-int, strip it off.
3810       Ops.erase(Ops.begin());
3811       --Idx;
3812     } else if (IsMax ? IsMaxV : IsMinV) {
3813       // If we have a max(/min) with a constant maximum(/minimum)-int,
3814       // it will always be the extremum.
3815       return LHSC;
3816     }
3817 
3818     if (Ops.size() == 1) return Ops[0];
3819   }
3820 
3821   // Find the first operation of the same kind
3822   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind)
3823     ++Idx;
3824 
3825   // Check to see if one of the operands is of the same kind. If so, expand its
3826   // operands onto our operand list, and recurse to simplify.
3827   if (Idx < Ops.size()) {
3828     bool DeletedAny = false;
3829     while (Ops[Idx]->getSCEVType() == Kind) {
3830       const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]);
3831       Ops.erase(Ops.begin()+Idx);
3832       Ops.append(SMME->op_begin(), SMME->op_end());
3833       DeletedAny = true;
3834     }
3835 
3836     if (DeletedAny)
3837       return getMinMaxExpr(Kind, Ops);
3838   }
3839 
3840   // Okay, check to see if the same value occurs in the operand list twice.  If
3841   // so, delete one.  Since we sorted the list, these values are required to
3842   // be adjacent.
3843   llvm::CmpInst::Predicate GEPred =
3844       IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
3845   llvm::CmpInst::Predicate LEPred =
3846       IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
3847   llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred;
3848   llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred;
3849   for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) {
3850     if (Ops[i] == Ops[i + 1] ||
3851         isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) {
3852       //  X op Y op Y  -->  X op Y
3853       //  X op Y       -->  X, if we know X, Y are ordered appropriately
3854       Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2);
3855       --i;
3856       --e;
3857     } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i],
3858                                                Ops[i + 1])) {
3859       //  X op Y       -->  Y, if we know X, Y are ordered appropriately
3860       Ops.erase(Ops.begin() + i, Ops.begin() + i + 1);
3861       --i;
3862       --e;
3863     }
3864   }
3865 
3866   if (Ops.size() == 1) return Ops[0];
3867 
3868   assert(!Ops.empty() && "Reduced smax down to nothing!");
3869 
3870   // Okay, it looks like we really DO need an expr.  Check to see if we
3871   // already have one, otherwise create a new one.
3872   FoldingSetNodeID ID;
3873   ID.AddInteger(Kind);
3874   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3875     ID.AddPointer(Ops[i]);
3876   void *IP = nullptr;
3877   const SCEV *ExistingSCEV = UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
3878   if (ExistingSCEV)
3879     return ExistingSCEV;
3880   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3881   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3882   SCEV *S = new (SCEVAllocator)
3883       SCEVMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
3884 
3885   UniqueSCEVs.InsertNode(S, IP);
3886   registerUser(S, Ops);
3887   return S;
3888 }
3889 
3890 namespace {
3891 
3892 class SCEVSequentialMinMaxDeduplicatingVisitor final
3893     : public SCEVVisitor<SCEVSequentialMinMaxDeduplicatingVisitor,
3894                          Optional<const SCEV *>> {
3895   using RetVal = Optional<const SCEV *>;
3896   using Base = SCEVVisitor<SCEVSequentialMinMaxDeduplicatingVisitor, RetVal>;
3897 
3898   ScalarEvolution &SE;
3899   const SCEVTypes RootKind; // Must be a sequential min/max expression.
3900   const SCEVTypes NonSequentialRootKind; // Non-sequential variant of RootKind.
3901   SmallPtrSet<const SCEV *, 16> SeenOps;
3902 
3903   bool canRecurseInto(SCEVTypes Kind) const {
3904     // We can only recurse into the SCEV expression of the same effective type
3905     // as the type of our root SCEV expression.
3906     return RootKind == Kind || NonSequentialRootKind == Kind;
3907   };
3908 
3909   RetVal visitAnyMinMaxExpr(const SCEV *S) {
3910     assert((isa<SCEVMinMaxExpr>(S) || isa<SCEVSequentialMinMaxExpr>(S)) &&
3911            "Only for min/max expressions.");
3912     SCEVTypes Kind = S->getSCEVType();
3913 
3914     if (!canRecurseInto(Kind))
3915       return S;
3916 
3917     auto *NAry = cast<SCEVNAryExpr>(S);
3918     SmallVector<const SCEV *> NewOps;
3919     bool Changed =
3920         visit(Kind, makeArrayRef(NAry->op_begin(), NAry->op_end()), NewOps);
3921 
3922     if (!Changed)
3923       return S;
3924     if (NewOps.empty())
3925       return None;
3926 
3927     return isa<SCEVSequentialMinMaxExpr>(S)
3928                ? SE.getSequentialMinMaxExpr(Kind, NewOps)
3929                : SE.getMinMaxExpr(Kind, NewOps);
3930   }
3931 
3932   RetVal visit(const SCEV *S) {
3933     // Has the whole operand been seen already?
3934     if (!SeenOps.insert(S).second)
3935       return None;
3936     return Base::visit(S);
3937   }
3938 
3939 public:
3940   SCEVSequentialMinMaxDeduplicatingVisitor(ScalarEvolution &SE,
3941                                            SCEVTypes RootKind)
3942       : SE(SE), RootKind(RootKind),
3943         NonSequentialRootKind(
3944             SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType(
3945                 RootKind)) {}
3946 
3947   bool /*Changed*/ visit(SCEVTypes Kind, ArrayRef<const SCEV *> OrigOps,
3948                          SmallVectorImpl<const SCEV *> &NewOps) {
3949     bool Changed = false;
3950     SmallVector<const SCEV *> Ops;
3951     Ops.reserve(OrigOps.size());
3952 
3953     for (const SCEV *Op : OrigOps) {
3954       RetVal NewOp = visit(Op);
3955       if (NewOp != Op)
3956         Changed = true;
3957       if (NewOp)
3958         Ops.emplace_back(*NewOp);
3959     }
3960 
3961     if (Changed)
3962       NewOps = std::move(Ops);
3963     return Changed;
3964   }
3965 
3966   RetVal visitConstant(const SCEVConstant *Constant) { return Constant; }
3967 
3968   RetVal visitPtrToIntExpr(const SCEVPtrToIntExpr *Expr) { return Expr; }
3969 
3970   RetVal visitTruncateExpr(const SCEVTruncateExpr *Expr) { return Expr; }
3971 
3972   RetVal visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { return Expr; }
3973 
3974   RetVal visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { return Expr; }
3975 
3976   RetVal visitAddExpr(const SCEVAddExpr *Expr) { return Expr; }
3977 
3978   RetVal visitMulExpr(const SCEVMulExpr *Expr) { return Expr; }
3979 
3980   RetVal visitUDivExpr(const SCEVUDivExpr *Expr) { return Expr; }
3981 
3982   RetVal visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; }
3983 
3984   RetVal visitSMaxExpr(const SCEVSMaxExpr *Expr) {
3985     return visitAnyMinMaxExpr(Expr);
3986   }
3987 
3988   RetVal visitUMaxExpr(const SCEVUMaxExpr *Expr) {
3989     return visitAnyMinMaxExpr(Expr);
3990   }
3991 
3992   RetVal visitSMinExpr(const SCEVSMinExpr *Expr) {
3993     return visitAnyMinMaxExpr(Expr);
3994   }
3995 
3996   RetVal visitUMinExpr(const SCEVUMinExpr *Expr) {
3997     return visitAnyMinMaxExpr(Expr);
3998   }
3999 
4000   RetVal visitSequentialUMinExpr(const SCEVSequentialUMinExpr *Expr) {
4001     return visitAnyMinMaxExpr(Expr);
4002   }
4003 
4004   RetVal visitUnknown(const SCEVUnknown *Expr) { return Expr; }
4005 
4006   RetVal visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { return Expr; }
4007 };
4008 
4009 } // namespace
4010 
4011 /// Return true if V is poison given that AssumedPoison is already poison.
4012 static bool impliesPoison(const SCEV *AssumedPoison, const SCEV *S) {
4013   // The only way poison may be introduced in a SCEV expression is from a
4014   // poison SCEVUnknown (ConstantExprs are also represented as SCEVUnknown,
4015   // not SCEVConstant). Notably, nowrap flags in SCEV nodes can *not*
4016   // introduce poison -- they encode guaranteed, non-speculated knowledge.
4017   //
4018   // Additionally, all SCEV nodes propagate poison from inputs to outputs,
4019   // with the notable exception of umin_seq, where only poison from the first
4020   // operand is (unconditionally) propagated.
4021   struct SCEVPoisonCollector {
4022     bool LookThroughSeq;
4023     SmallPtrSet<const SCEV *, 4> MaybePoison;
4024     SCEVPoisonCollector(bool LookThroughSeq) : LookThroughSeq(LookThroughSeq) {}
4025 
4026     bool follow(const SCEV *S) {
4027       // TODO: We can always follow the first operand, but the SCEVTraversal
4028       // API doesn't support this.
4029       if (!LookThroughSeq && isa<SCEVSequentialMinMaxExpr>(S))
4030         return false;
4031 
4032       if (auto *SU = dyn_cast<SCEVUnknown>(S)) {
4033         if (!isGuaranteedNotToBePoison(SU->getValue()))
4034           MaybePoison.insert(S);
4035       }
4036       return true;
4037     }
4038     bool isDone() const { return false; }
4039   };
4040 
4041   // First collect all SCEVs that might result in AssumedPoison to be poison.
4042   // We need to look through umin_seq here, because we want to find all SCEVs
4043   // that *might* result in poison, not only those that are *required* to.
4044   SCEVPoisonCollector PC1(/* LookThroughSeq */ true);
4045   visitAll(AssumedPoison, PC1);
4046 
4047   // AssumedPoison is never poison. As the assumption is false, the implication
4048   // is true. Don't bother walking the other SCEV in this case.
4049   if (PC1.MaybePoison.empty())
4050     return true;
4051 
4052   // Collect all SCEVs in S that, if poison, *will* result in S being poison
4053   // as well. We cannot look through umin_seq here, as its argument only *may*
4054   // make the result poison.
4055   SCEVPoisonCollector PC2(/* LookThroughSeq */ false);
4056   visitAll(S, PC2);
4057 
4058   // Make sure that no matter which SCEV in PC1.MaybePoison is actually poison,
4059   // it will also make S poison by being part of PC2.MaybePoison.
4060   return all_of(PC1.MaybePoison,
4061                 [&](const SCEV *S) { return PC2.MaybePoison.contains(S); });
4062 }
4063 
4064 const SCEV *
4065 ScalarEvolution::getSequentialMinMaxExpr(SCEVTypes Kind,
4066                                          SmallVectorImpl<const SCEV *> &Ops) {
4067   assert(SCEVSequentialMinMaxExpr::isSequentialMinMaxType(Kind) &&
4068          "Not a SCEVSequentialMinMaxExpr!");
4069   assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
4070   if (Ops.size() == 1)
4071     return Ops[0];
4072 #ifndef NDEBUG
4073   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
4074   for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
4075     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
4076            "Operand types don't match!");
4077     assert(Ops[0]->getType()->isPointerTy() ==
4078                Ops[i]->getType()->isPointerTy() &&
4079            "min/max should be consistently pointerish");
4080   }
4081 #endif
4082 
4083   // Note that SCEVSequentialMinMaxExpr is *NOT* commutative,
4084   // so we can *NOT* do any kind of sorting of the expressions!
4085 
4086   // Check if we have created the same expression before.
4087   if (const SCEV *S = findExistingSCEVInCache(Kind, Ops))
4088     return S;
4089 
4090   // FIXME: there are *some* simplifications that we can do here.
4091 
4092   // Keep only the first instance of an operand.
4093   {
4094     SCEVSequentialMinMaxDeduplicatingVisitor Deduplicator(*this, Kind);
4095     bool Changed = Deduplicator.visit(Kind, Ops, Ops);
4096     if (Changed)
4097       return getSequentialMinMaxExpr(Kind, Ops);
4098   }
4099 
4100   // Check to see if one of the operands is of the same kind. If so, expand its
4101   // operands onto our operand list, and recurse to simplify.
4102   {
4103     unsigned Idx = 0;
4104     bool DeletedAny = false;
4105     while (Idx < Ops.size()) {
4106       if (Ops[Idx]->getSCEVType() != Kind) {
4107         ++Idx;
4108         continue;
4109       }
4110       const auto *SMME = cast<SCEVSequentialMinMaxExpr>(Ops[Idx]);
4111       Ops.erase(Ops.begin() + Idx);
4112       Ops.insert(Ops.begin() + Idx, SMME->op_begin(), SMME->op_end());
4113       DeletedAny = true;
4114     }
4115 
4116     if (DeletedAny)
4117       return getSequentialMinMaxExpr(Kind, Ops);
4118   }
4119 
4120   const SCEV *SaturationPoint;
4121   ICmpInst::Predicate Pred;
4122   switch (Kind) {
4123   case scSequentialUMinExpr:
4124     SaturationPoint = getZero(Ops[0]->getType());
4125     Pred = ICmpInst::ICMP_ULE;
4126     break;
4127   default:
4128     llvm_unreachable("Not a sequential min/max type.");
4129   }
4130 
4131   for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
4132     // We can replace %x umin_seq %y with %x umin %y if either:
4133     //  * %y being poison implies %x is also poison.
4134     //  * %x cannot be the saturating value (e.g. zero for umin).
4135     if (::impliesPoison(Ops[i], Ops[i - 1]) ||
4136         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, Ops[i - 1],
4137                                         SaturationPoint)) {
4138       SmallVector<const SCEV *> SeqOps = {Ops[i - 1], Ops[i]};
4139       Ops[i - 1] = getMinMaxExpr(
4140           SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType(Kind),
4141           SeqOps);
4142       Ops.erase(Ops.begin() + i);
4143       return getSequentialMinMaxExpr(Kind, Ops);
4144     }
4145     // Fold %x umin_seq %y to %x if %x ule %y.
4146     // TODO: We might be able to prove the predicate for a later operand.
4147     if (isKnownViaNonRecursiveReasoning(Pred, Ops[i - 1], Ops[i])) {
4148       Ops.erase(Ops.begin() + i);
4149       return getSequentialMinMaxExpr(Kind, Ops);
4150     }
4151   }
4152 
4153   // Okay, it looks like we really DO need an expr.  Check to see if we
4154   // already have one, otherwise create a new one.
4155   FoldingSetNodeID ID;
4156   ID.AddInteger(Kind);
4157   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
4158     ID.AddPointer(Ops[i]);
4159   void *IP = nullptr;
4160   const SCEV *ExistingSCEV = UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
4161   if (ExistingSCEV)
4162     return ExistingSCEV;
4163 
4164   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
4165   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
4166   SCEV *S = new (SCEVAllocator)
4167       SCEVSequentialMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
4168 
4169   UniqueSCEVs.InsertNode(S, IP);
4170   registerUser(S, Ops);
4171   return S;
4172 }
4173 
4174 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) {
4175   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
4176   return getSMaxExpr(Ops);
4177 }
4178 
4179 const SCEV *ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
4180   return getMinMaxExpr(scSMaxExpr, Ops);
4181 }
4182 
4183 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) {
4184   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
4185   return getUMaxExpr(Ops);
4186 }
4187 
4188 const SCEV *ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
4189   return getMinMaxExpr(scUMaxExpr, Ops);
4190 }
4191 
4192 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
4193                                          const SCEV *RHS) {
4194   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
4195   return getSMinExpr(Ops);
4196 }
4197 
4198 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) {
4199   return getMinMaxExpr(scSMinExpr, Ops);
4200 }
4201 
4202 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, const SCEV *RHS,
4203                                          bool Sequential) {
4204   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
4205   return getUMinExpr(Ops, Sequential);
4206 }
4207 
4208 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops,
4209                                          bool Sequential) {
4210   return Sequential ? getSequentialMinMaxExpr(scSequentialUMinExpr, Ops)
4211                     : getMinMaxExpr(scUMinExpr, Ops);
4212 }
4213 
4214 const SCEV *
4215 ScalarEvolution::getSizeOfScalableVectorExpr(Type *IntTy,
4216                                              ScalableVectorType *ScalableTy) {
4217   Constant *NullPtr = Constant::getNullValue(ScalableTy->getPointerTo());
4218   Constant *One = ConstantInt::get(IntTy, 1);
4219   Constant *GEP = ConstantExpr::getGetElementPtr(ScalableTy, NullPtr, One);
4220   // Note that the expression we created is the final expression, we don't
4221   // want to simplify it any further Also, if we call a normal getSCEV(),
4222   // we'll end up in an endless recursion. So just create an SCEVUnknown.
4223   return getUnknown(ConstantExpr::getPtrToInt(GEP, IntTy));
4224 }
4225 
4226 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
4227   if (auto *ScalableAllocTy = dyn_cast<ScalableVectorType>(AllocTy))
4228     return getSizeOfScalableVectorExpr(IntTy, ScalableAllocTy);
4229   // We can bypass creating a target-independent constant expression and then
4230   // folding it back into a ConstantInt. This is just a compile-time
4231   // optimization.
4232   return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
4233 }
4234 
4235 const SCEV *ScalarEvolution::getStoreSizeOfExpr(Type *IntTy, Type *StoreTy) {
4236   if (auto *ScalableStoreTy = dyn_cast<ScalableVectorType>(StoreTy))
4237     return getSizeOfScalableVectorExpr(IntTy, ScalableStoreTy);
4238   // We can bypass creating a target-independent constant expression and then
4239   // folding it back into a ConstantInt. This is just a compile-time
4240   // optimization.
4241   return getConstant(IntTy, getDataLayout().getTypeStoreSize(StoreTy));
4242 }
4243 
4244 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
4245                                              StructType *STy,
4246                                              unsigned FieldNo) {
4247   // We can bypass creating a target-independent constant expression and then
4248   // folding it back into a ConstantInt. This is just a compile-time
4249   // optimization.
4250   return getConstant(
4251       IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
4252 }
4253 
4254 const SCEV *ScalarEvolution::getUnknown(Value *V) {
4255   // Don't attempt to do anything other than create a SCEVUnknown object
4256   // here.  createSCEV only calls getUnknown after checking for all other
4257   // interesting possibilities, and any other code that calls getUnknown
4258   // is doing so in order to hide a value from SCEV canonicalization.
4259 
4260   FoldingSetNodeID ID;
4261   ID.AddInteger(scUnknown);
4262   ID.AddPointer(V);
4263   void *IP = nullptr;
4264   if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
4265     assert(cast<SCEVUnknown>(S)->getValue() == V &&
4266            "Stale SCEVUnknown in uniquing map!");
4267     return S;
4268   }
4269   SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
4270                                             FirstUnknown);
4271   FirstUnknown = cast<SCEVUnknown>(S);
4272   UniqueSCEVs.InsertNode(S, IP);
4273   return S;
4274 }
4275 
4276 //===----------------------------------------------------------------------===//
4277 //            Basic SCEV Analysis and PHI Idiom Recognition Code
4278 //
4279 
4280 /// Test if values of the given type are analyzable within the SCEV
4281 /// framework. This primarily includes integer types, and it can optionally
4282 /// include pointer types if the ScalarEvolution class has access to
4283 /// target-specific information.
4284 bool ScalarEvolution::isSCEVable(Type *Ty) const {
4285   // Integers and pointers are always SCEVable.
4286   return Ty->isIntOrPtrTy();
4287 }
4288 
4289 /// Return the size in bits of the specified type, for which isSCEVable must
4290 /// return true.
4291 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
4292   assert(isSCEVable(Ty) && "Type is not SCEVable!");
4293   if (Ty->isPointerTy())
4294     return getDataLayout().getIndexTypeSizeInBits(Ty);
4295   return getDataLayout().getTypeSizeInBits(Ty);
4296 }
4297 
4298 /// Return a type with the same bitwidth as the given type and which represents
4299 /// how SCEV will treat the given type, for which isSCEVable must return
4300 /// true. For pointer types, this is the pointer index sized integer type.
4301 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
4302   assert(isSCEVable(Ty) && "Type is not SCEVable!");
4303 
4304   if (Ty->isIntegerTy())
4305     return Ty;
4306 
4307   // The only other support type is pointer.
4308   assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
4309   return getDataLayout().getIndexType(Ty);
4310 }
4311 
4312 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const {
4313   return  getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
4314 }
4315 
4316 bool ScalarEvolution::instructionCouldExistWitthOperands(const SCEV *A,
4317                                                          const SCEV *B) {
4318   /// For a valid use point to exist, the defining scope of one operand
4319   /// must dominate the other.
4320   bool PreciseA, PreciseB;
4321   auto *ScopeA = getDefiningScopeBound({A}, PreciseA);
4322   auto *ScopeB = getDefiningScopeBound({B}, PreciseB);
4323   if (!PreciseA || !PreciseB)
4324     // Can't tell.
4325     return false;
4326   return (ScopeA == ScopeB) || DT.dominates(ScopeA, ScopeB) ||
4327     DT.dominates(ScopeB, ScopeA);
4328 }
4329 
4330 
4331 const SCEV *ScalarEvolution::getCouldNotCompute() {
4332   return CouldNotCompute.get();
4333 }
4334 
4335 bool ScalarEvolution::checkValidity(const SCEV *S) const {
4336   bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
4337     auto *SU = dyn_cast<SCEVUnknown>(S);
4338     return SU && SU->getValue() == nullptr;
4339   });
4340 
4341   return !ContainsNulls;
4342 }
4343 
4344 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
4345   HasRecMapType::iterator I = HasRecMap.find(S);
4346   if (I != HasRecMap.end())
4347     return I->second;
4348 
4349   bool FoundAddRec =
4350       SCEVExprContains(S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); });
4351   HasRecMap.insert({S, FoundAddRec});
4352   return FoundAddRec;
4353 }
4354 
4355 /// Return the ValueOffsetPair set for \p S. \p S can be represented
4356 /// by the value and offset from any ValueOffsetPair in the set.
4357 ArrayRef<Value *> ScalarEvolution::getSCEVValues(const SCEV *S) {
4358   ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
4359   if (SI == ExprValueMap.end())
4360     return None;
4361 #ifndef NDEBUG
4362   if (VerifySCEVMap) {
4363     // Check there is no dangling Value in the set returned.
4364     for (Value *V : SI->second)
4365       assert(ValueExprMap.count(V));
4366   }
4367 #endif
4368   return SI->second.getArrayRef();
4369 }
4370 
4371 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
4372 /// cannot be used separately. eraseValueFromMap should be used to remove
4373 /// V from ValueExprMap and ExprValueMap at the same time.
4374 void ScalarEvolution::eraseValueFromMap(Value *V) {
4375   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
4376   if (I != ValueExprMap.end()) {
4377     auto EVIt = ExprValueMap.find(I->second);
4378     bool Removed = EVIt->second.remove(V);
4379     (void) Removed;
4380     assert(Removed && "Value not in ExprValueMap?");
4381     ValueExprMap.erase(I);
4382   }
4383 }
4384 
4385 void ScalarEvolution::insertValueToMap(Value *V, const SCEV *S) {
4386   // A recursive query may have already computed the SCEV. It should be
4387   // equivalent, but may not necessarily be exactly the same, e.g. due to lazily
4388   // inferred nowrap flags.
4389   auto It = ValueExprMap.find_as(V);
4390   if (It == ValueExprMap.end()) {
4391     ValueExprMap.insert({SCEVCallbackVH(V, this), S});
4392     ExprValueMap[S].insert(V);
4393   }
4394 }
4395 
4396 /// Return an existing SCEV if it exists, otherwise analyze the expression and
4397 /// create a new one.
4398 const SCEV *ScalarEvolution::getSCEV(Value *V) {
4399   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
4400 
4401   const SCEV *S = getExistingSCEV(V);
4402   if (S == nullptr) {
4403     S = createSCEV(V);
4404     // During PHI resolution, it is possible to create two SCEVs for the same
4405     // V, so it is needed to double check whether V->S is inserted into
4406     // ValueExprMap before insert S->{V, 0} into ExprValueMap.
4407     std::pair<ValueExprMapType::iterator, bool> Pair =
4408         ValueExprMap.insert({SCEVCallbackVH(V, this), S});
4409     if (Pair.second)
4410       ExprValueMap[S].insert(V);
4411   }
4412   return S;
4413 }
4414 
4415 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
4416   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
4417 
4418   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
4419   if (I != ValueExprMap.end()) {
4420     const SCEV *S = I->second;
4421     assert(checkValidity(S) &&
4422            "existing SCEV has not been properly invalidated");
4423     return S;
4424   }
4425   return nullptr;
4426 }
4427 
4428 /// Return a SCEV corresponding to -V = -1*V
4429 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
4430                                              SCEV::NoWrapFlags Flags) {
4431   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4432     return getConstant(
4433                cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
4434 
4435   Type *Ty = V->getType();
4436   Ty = getEffectiveSCEVType(Ty);
4437   return getMulExpr(V, getMinusOne(Ty), Flags);
4438 }
4439 
4440 /// If Expr computes ~A, return A else return nullptr
4441 static const SCEV *MatchNotExpr(const SCEV *Expr) {
4442   const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
4443   if (!Add || Add->getNumOperands() != 2 ||
4444       !Add->getOperand(0)->isAllOnesValue())
4445     return nullptr;
4446 
4447   const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
4448   if (!AddRHS || AddRHS->getNumOperands() != 2 ||
4449       !AddRHS->getOperand(0)->isAllOnesValue())
4450     return nullptr;
4451 
4452   return AddRHS->getOperand(1);
4453 }
4454 
4455 /// Return a SCEV corresponding to ~V = -1-V
4456 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
4457   assert(!V->getType()->isPointerTy() && "Can't negate pointer");
4458 
4459   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4460     return getConstant(
4461                 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
4462 
4463   // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y)
4464   if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) {
4465     auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) {
4466       SmallVector<const SCEV *, 2> MatchedOperands;
4467       for (const SCEV *Operand : MME->operands()) {
4468         const SCEV *Matched = MatchNotExpr(Operand);
4469         if (!Matched)
4470           return (const SCEV *)nullptr;
4471         MatchedOperands.push_back(Matched);
4472       }
4473       return getMinMaxExpr(SCEVMinMaxExpr::negate(MME->getSCEVType()),
4474                            MatchedOperands);
4475     };
4476     if (const SCEV *Replaced = MatchMinMaxNegation(MME))
4477       return Replaced;
4478   }
4479 
4480   Type *Ty = V->getType();
4481   Ty = getEffectiveSCEVType(Ty);
4482   return getMinusSCEV(getMinusOne(Ty), V);
4483 }
4484 
4485 const SCEV *ScalarEvolution::removePointerBase(const SCEV *P) {
4486   assert(P->getType()->isPointerTy());
4487 
4488   if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(P)) {
4489     // The base of an AddRec is the first operand.
4490     SmallVector<const SCEV *> Ops{AddRec->operands()};
4491     Ops[0] = removePointerBase(Ops[0]);
4492     // Don't try to transfer nowrap flags for now. We could in some cases
4493     // (for example, if pointer operand of the AddRec is a SCEVUnknown).
4494     return getAddRecExpr(Ops, AddRec->getLoop(), SCEV::FlagAnyWrap);
4495   }
4496   if (auto *Add = dyn_cast<SCEVAddExpr>(P)) {
4497     // The base of an Add is the pointer operand.
4498     SmallVector<const SCEV *> Ops{Add->operands()};
4499     const SCEV **PtrOp = nullptr;
4500     for (const SCEV *&AddOp : Ops) {
4501       if (AddOp->getType()->isPointerTy()) {
4502         assert(!PtrOp && "Cannot have multiple pointer ops");
4503         PtrOp = &AddOp;
4504       }
4505     }
4506     *PtrOp = removePointerBase(*PtrOp);
4507     // Don't try to transfer nowrap flags for now. We could in some cases
4508     // (for example, if the pointer operand of the Add is a SCEVUnknown).
4509     return getAddExpr(Ops);
4510   }
4511   // Any other expression must be a pointer base.
4512   return getZero(P->getType());
4513 }
4514 
4515 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
4516                                           SCEV::NoWrapFlags Flags,
4517                                           unsigned Depth) {
4518   // Fast path: X - X --> 0.
4519   if (LHS == RHS)
4520     return getZero(LHS->getType());
4521 
4522   // If we subtract two pointers with different pointer bases, bail.
4523   // Eventually, we're going to add an assertion to getMulExpr that we
4524   // can't multiply by a pointer.
4525   if (RHS->getType()->isPointerTy()) {
4526     if (!LHS->getType()->isPointerTy() ||
4527         getPointerBase(LHS) != getPointerBase(RHS))
4528       return getCouldNotCompute();
4529     LHS = removePointerBase(LHS);
4530     RHS = removePointerBase(RHS);
4531   }
4532 
4533   // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
4534   // makes it so that we cannot make much use of NUW.
4535   auto AddFlags = SCEV::FlagAnyWrap;
4536   const bool RHSIsNotMinSigned =
4537       !getSignedRangeMin(RHS).isMinSignedValue();
4538   if (hasFlags(Flags, SCEV::FlagNSW)) {
4539     // Let M be the minimum representable signed value. Then (-1)*RHS
4540     // signed-wraps if and only if RHS is M. That can happen even for
4541     // a NSW subtraction because e.g. (-1)*M signed-wraps even though
4542     // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
4543     // (-1)*RHS, we need to prove that RHS != M.
4544     //
4545     // If LHS is non-negative and we know that LHS - RHS does not
4546     // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
4547     // either by proving that RHS > M or that LHS >= 0.
4548     if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
4549       AddFlags = SCEV::FlagNSW;
4550     }
4551   }
4552 
4553   // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
4554   // RHS is NSW and LHS >= 0.
4555   //
4556   // The difficulty here is that the NSW flag may have been proven
4557   // relative to a loop that is to be found in a recurrence in LHS and
4558   // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
4559   // larger scope than intended.
4560   auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
4561 
4562   return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
4563 }
4564 
4565 const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty,
4566                                                      unsigned Depth) {
4567   Type *SrcTy = V->getType();
4568   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4569          "Cannot truncate or zero extend with non-integer arguments!");
4570   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4571     return V;  // No conversion
4572   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4573     return getTruncateExpr(V, Ty, Depth);
4574   return getZeroExtendExpr(V, Ty, Depth);
4575 }
4576 
4577 const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty,
4578                                                      unsigned Depth) {
4579   Type *SrcTy = V->getType();
4580   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4581          "Cannot truncate or zero extend with non-integer arguments!");
4582   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4583     return V;  // No conversion
4584   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4585     return getTruncateExpr(V, Ty, Depth);
4586   return getSignExtendExpr(V, Ty, Depth);
4587 }
4588 
4589 const SCEV *
4590 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
4591   Type *SrcTy = V->getType();
4592   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4593          "Cannot noop or zero extend with non-integer arguments!");
4594   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4595          "getNoopOrZeroExtend cannot truncate!");
4596   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4597     return V;  // No conversion
4598   return getZeroExtendExpr(V, Ty);
4599 }
4600 
4601 const SCEV *
4602 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
4603   Type *SrcTy = V->getType();
4604   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4605          "Cannot noop or sign extend with non-integer arguments!");
4606   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4607          "getNoopOrSignExtend cannot truncate!");
4608   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4609     return V;  // No conversion
4610   return getSignExtendExpr(V, Ty);
4611 }
4612 
4613 const SCEV *
4614 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
4615   Type *SrcTy = V->getType();
4616   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4617          "Cannot noop or any extend with non-integer arguments!");
4618   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4619          "getNoopOrAnyExtend cannot truncate!");
4620   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4621     return V;  // No conversion
4622   return getAnyExtendExpr(V, Ty);
4623 }
4624 
4625 const SCEV *
4626 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
4627   Type *SrcTy = V->getType();
4628   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4629          "Cannot truncate or noop with non-integer arguments!");
4630   assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
4631          "getTruncateOrNoop cannot extend!");
4632   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4633     return V;  // No conversion
4634   return getTruncateExpr(V, Ty);
4635 }
4636 
4637 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
4638                                                         const SCEV *RHS) {
4639   const SCEV *PromotedLHS = LHS;
4640   const SCEV *PromotedRHS = RHS;
4641 
4642   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
4643     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
4644   else
4645     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
4646 
4647   return getUMaxExpr(PromotedLHS, PromotedRHS);
4648 }
4649 
4650 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
4651                                                         const SCEV *RHS,
4652                                                         bool Sequential) {
4653   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
4654   return getUMinFromMismatchedTypes(Ops, Sequential);
4655 }
4656 
4657 const SCEV *
4658 ScalarEvolution::getUMinFromMismatchedTypes(SmallVectorImpl<const SCEV *> &Ops,
4659                                             bool Sequential) {
4660   assert(!Ops.empty() && "At least one operand must be!");
4661   // Trivial case.
4662   if (Ops.size() == 1)
4663     return Ops[0];
4664 
4665   // Find the max type first.
4666   Type *MaxType = nullptr;
4667   for (auto *S : Ops)
4668     if (MaxType)
4669       MaxType = getWiderType(MaxType, S->getType());
4670     else
4671       MaxType = S->getType();
4672   assert(MaxType && "Failed to find maximum type!");
4673 
4674   // Extend all ops to max type.
4675   SmallVector<const SCEV *, 2> PromotedOps;
4676   for (auto *S : Ops)
4677     PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType));
4678 
4679   // Generate umin.
4680   return getUMinExpr(PromotedOps, Sequential);
4681 }
4682 
4683 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
4684   // A pointer operand may evaluate to a nonpointer expression, such as null.
4685   if (!V->getType()->isPointerTy())
4686     return V;
4687 
4688   while (true) {
4689     if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
4690       V = AddRec->getStart();
4691     } else if (auto *Add = dyn_cast<SCEVAddExpr>(V)) {
4692       const SCEV *PtrOp = nullptr;
4693       for (const SCEV *AddOp : Add->operands()) {
4694         if (AddOp->getType()->isPointerTy()) {
4695           assert(!PtrOp && "Cannot have multiple pointer ops");
4696           PtrOp = AddOp;
4697         }
4698       }
4699       assert(PtrOp && "Must have pointer op");
4700       V = PtrOp;
4701     } else // Not something we can look further into.
4702       return V;
4703   }
4704 }
4705 
4706 /// Push users of the given Instruction onto the given Worklist.
4707 static void PushDefUseChildren(Instruction *I,
4708                                SmallVectorImpl<Instruction *> &Worklist,
4709                                SmallPtrSetImpl<Instruction *> &Visited) {
4710   // Push the def-use children onto the Worklist stack.
4711   for (User *U : I->users()) {
4712     auto *UserInsn = cast<Instruction>(U);
4713     if (Visited.insert(UserInsn).second)
4714       Worklist.push_back(UserInsn);
4715   }
4716 }
4717 
4718 namespace {
4719 
4720 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start
4721 /// expression in case its Loop is L. If it is not L then
4722 /// if IgnoreOtherLoops is true then use AddRec itself
4723 /// otherwise rewrite cannot be done.
4724 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4725 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
4726 public:
4727   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
4728                              bool IgnoreOtherLoops = true) {
4729     SCEVInitRewriter Rewriter(L, SE);
4730     const SCEV *Result = Rewriter.visit(S);
4731     if (Rewriter.hasSeenLoopVariantSCEVUnknown())
4732       return SE.getCouldNotCompute();
4733     return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops
4734                ? SE.getCouldNotCompute()
4735                : Result;
4736   }
4737 
4738   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4739     if (!SE.isLoopInvariant(Expr, L))
4740       SeenLoopVariantSCEVUnknown = true;
4741     return Expr;
4742   }
4743 
4744   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4745     // Only re-write AddRecExprs for this loop.
4746     if (Expr->getLoop() == L)
4747       return Expr->getStart();
4748     SeenOtherLoops = true;
4749     return Expr;
4750   }
4751 
4752   bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4753 
4754   bool hasSeenOtherLoops() { return SeenOtherLoops; }
4755 
4756 private:
4757   explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
4758       : SCEVRewriteVisitor(SE), L(L) {}
4759 
4760   const Loop *L;
4761   bool SeenLoopVariantSCEVUnknown = false;
4762   bool SeenOtherLoops = false;
4763 };
4764 
4765 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post
4766 /// increment expression in case its Loop is L. If it is not L then
4767 /// use AddRec itself.
4768 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4769 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> {
4770 public:
4771   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) {
4772     SCEVPostIncRewriter Rewriter(L, SE);
4773     const SCEV *Result = Rewriter.visit(S);
4774     return Rewriter.hasSeenLoopVariantSCEVUnknown()
4775         ? SE.getCouldNotCompute()
4776         : Result;
4777   }
4778 
4779   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4780     if (!SE.isLoopInvariant(Expr, L))
4781       SeenLoopVariantSCEVUnknown = true;
4782     return Expr;
4783   }
4784 
4785   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4786     // Only re-write AddRecExprs for this loop.
4787     if (Expr->getLoop() == L)
4788       return Expr->getPostIncExpr(SE);
4789     SeenOtherLoops = true;
4790     return Expr;
4791   }
4792 
4793   bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4794 
4795   bool hasSeenOtherLoops() { return SeenOtherLoops; }
4796 
4797 private:
4798   explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE)
4799       : SCEVRewriteVisitor(SE), L(L) {}
4800 
4801   const Loop *L;
4802   bool SeenLoopVariantSCEVUnknown = false;
4803   bool SeenOtherLoops = false;
4804 };
4805 
4806 /// This class evaluates the compare condition by matching it against the
4807 /// condition of loop latch. If there is a match we assume a true value
4808 /// for the condition while building SCEV nodes.
4809 class SCEVBackedgeConditionFolder
4810     : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> {
4811 public:
4812   static const SCEV *rewrite(const SCEV *S, const Loop *L,
4813                              ScalarEvolution &SE) {
4814     bool IsPosBECond = false;
4815     Value *BECond = nullptr;
4816     if (BasicBlock *Latch = L->getLoopLatch()) {
4817       BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator());
4818       if (BI && BI->isConditional()) {
4819         assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
4820                "Both outgoing branches should not target same header!");
4821         BECond = BI->getCondition();
4822         IsPosBECond = BI->getSuccessor(0) == L->getHeader();
4823       } else {
4824         return S;
4825       }
4826     }
4827     SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE);
4828     return Rewriter.visit(S);
4829   }
4830 
4831   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4832     const SCEV *Result = Expr;
4833     bool InvariantF = SE.isLoopInvariant(Expr, L);
4834 
4835     if (!InvariantF) {
4836       Instruction *I = cast<Instruction>(Expr->getValue());
4837       switch (I->getOpcode()) {
4838       case Instruction::Select: {
4839         SelectInst *SI = cast<SelectInst>(I);
4840         Optional<const SCEV *> Res =
4841             compareWithBackedgeCondition(SI->getCondition());
4842         if (Res.hasValue()) {
4843           bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne();
4844           Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue());
4845         }
4846         break;
4847       }
4848       default: {
4849         Optional<const SCEV *> Res = compareWithBackedgeCondition(I);
4850         if (Res.hasValue())
4851           Result = Res.getValue();
4852         break;
4853       }
4854       }
4855     }
4856     return Result;
4857   }
4858 
4859 private:
4860   explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond,
4861                                        bool IsPosBECond, ScalarEvolution &SE)
4862       : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond),
4863         IsPositiveBECond(IsPosBECond) {}
4864 
4865   Optional<const SCEV *> compareWithBackedgeCondition(Value *IC);
4866 
4867   const Loop *L;
4868   /// Loop back condition.
4869   Value *BackedgeCond = nullptr;
4870   /// Set to true if loop back is on positive branch condition.
4871   bool IsPositiveBECond;
4872 };
4873 
4874 Optional<const SCEV *>
4875 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) {
4876 
4877   // If value matches the backedge condition for loop latch,
4878   // then return a constant evolution node based on loopback
4879   // branch taken.
4880   if (BackedgeCond == IC)
4881     return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext()))
4882                             : SE.getZero(Type::getInt1Ty(SE.getContext()));
4883   return None;
4884 }
4885 
4886 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
4887 public:
4888   static const SCEV *rewrite(const SCEV *S, const Loop *L,
4889                              ScalarEvolution &SE) {
4890     SCEVShiftRewriter Rewriter(L, SE);
4891     const SCEV *Result = Rewriter.visit(S);
4892     return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
4893   }
4894 
4895   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4896     // Only allow AddRecExprs for this loop.
4897     if (!SE.isLoopInvariant(Expr, L))
4898       Valid = false;
4899     return Expr;
4900   }
4901 
4902   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4903     if (Expr->getLoop() == L && Expr->isAffine())
4904       return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
4905     Valid = false;
4906     return Expr;
4907   }
4908 
4909   bool isValid() { return Valid; }
4910 
4911 private:
4912   explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
4913       : SCEVRewriteVisitor(SE), L(L) {}
4914 
4915   const Loop *L;
4916   bool Valid = true;
4917 };
4918 
4919 } // end anonymous namespace
4920 
4921 SCEV::NoWrapFlags
4922 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
4923   if (!AR->isAffine())
4924     return SCEV::FlagAnyWrap;
4925 
4926   using OBO = OverflowingBinaryOperator;
4927 
4928   SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
4929 
4930   if (!AR->hasNoSignedWrap()) {
4931     ConstantRange AddRecRange = getSignedRange(AR);
4932     ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
4933 
4934     auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4935         Instruction::Add, IncRange, OBO::NoSignedWrap);
4936     if (NSWRegion.contains(AddRecRange))
4937       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
4938   }
4939 
4940   if (!AR->hasNoUnsignedWrap()) {
4941     ConstantRange AddRecRange = getUnsignedRange(AR);
4942     ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
4943 
4944     auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4945         Instruction::Add, IncRange, OBO::NoUnsignedWrap);
4946     if (NUWRegion.contains(AddRecRange))
4947       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
4948   }
4949 
4950   return Result;
4951 }
4952 
4953 SCEV::NoWrapFlags
4954 ScalarEvolution::proveNoSignedWrapViaInduction(const SCEVAddRecExpr *AR) {
4955   SCEV::NoWrapFlags Result = AR->getNoWrapFlags();
4956 
4957   if (AR->hasNoSignedWrap())
4958     return Result;
4959 
4960   if (!AR->isAffine())
4961     return Result;
4962 
4963   const SCEV *Step = AR->getStepRecurrence(*this);
4964   const Loop *L = AR->getLoop();
4965 
4966   // Check whether the backedge-taken count is SCEVCouldNotCompute.
4967   // Note that this serves two purposes: It filters out loops that are
4968   // simply not analyzable, and it covers the case where this code is
4969   // being called from within backedge-taken count analysis, such that
4970   // attempting to ask for the backedge-taken count would likely result
4971   // in infinite recursion. In the later case, the analysis code will
4972   // cope with a conservative value, and it will take care to purge
4973   // that value once it has finished.
4974   const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
4975 
4976   // Normally, in the cases we can prove no-overflow via a
4977   // backedge guarding condition, we can also compute a backedge
4978   // taken count for the loop.  The exceptions are assumptions and
4979   // guards present in the loop -- SCEV is not great at exploiting
4980   // these to compute max backedge taken counts, but can still use
4981   // these to prove lack of overflow.  Use this fact to avoid
4982   // doing extra work that may not pay off.
4983 
4984   if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
4985       AC.assumptions().empty())
4986     return Result;
4987 
4988   // If the backedge is guarded by a comparison with the pre-inc  value the
4989   // addrec is safe. Also, if the entry is guarded by a comparison with the
4990   // start value and the backedge is guarded by a comparison with the post-inc
4991   // value, the addrec is safe.
4992   ICmpInst::Predicate Pred;
4993   const SCEV *OverflowLimit =
4994     getSignedOverflowLimitForStep(Step, &Pred, this);
4995   if (OverflowLimit &&
4996       (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
4997        isKnownOnEveryIteration(Pred, AR, OverflowLimit))) {
4998     Result = setFlags(Result, SCEV::FlagNSW);
4999   }
5000   return Result;
5001 }
5002 SCEV::NoWrapFlags
5003 ScalarEvolution::proveNoUnsignedWrapViaInduction(const SCEVAddRecExpr *AR) {
5004   SCEV::NoWrapFlags Result = AR->getNoWrapFlags();
5005 
5006   if (AR->hasNoUnsignedWrap())
5007     return Result;
5008 
5009   if (!AR->isAffine())
5010     return Result;
5011 
5012   const SCEV *Step = AR->getStepRecurrence(*this);
5013   unsigned BitWidth = getTypeSizeInBits(AR->getType());
5014   const Loop *L = AR->getLoop();
5015 
5016   // Check whether the backedge-taken count is SCEVCouldNotCompute.
5017   // Note that this serves two purposes: It filters out loops that are
5018   // simply not analyzable, and it covers the case where this code is
5019   // being called from within backedge-taken count analysis, such that
5020   // attempting to ask for the backedge-taken count would likely result
5021   // in infinite recursion. In the later case, the analysis code will
5022   // cope with a conservative value, and it will take care to purge
5023   // that value once it has finished.
5024   const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
5025 
5026   // Normally, in the cases we can prove no-overflow via a
5027   // backedge guarding condition, we can also compute a backedge
5028   // taken count for the loop.  The exceptions are assumptions and
5029   // guards present in the loop -- SCEV is not great at exploiting
5030   // these to compute max backedge taken counts, but can still use
5031   // these to prove lack of overflow.  Use this fact to avoid
5032   // doing extra work that may not pay off.
5033 
5034   if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
5035       AC.assumptions().empty())
5036     return Result;
5037 
5038   // If the backedge is guarded by a comparison with the pre-inc  value the
5039   // addrec is safe. Also, if the entry is guarded by a comparison with the
5040   // start value and the backedge is guarded by a comparison with the post-inc
5041   // value, the addrec is safe.
5042   if (isKnownPositive(Step)) {
5043     const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
5044                                 getUnsignedRangeMax(Step));
5045     if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
5046         isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) {
5047       Result = setFlags(Result, SCEV::FlagNUW);
5048     }
5049   }
5050 
5051   return Result;
5052 }
5053 
5054 namespace {
5055 
5056 /// Represents an abstract binary operation.  This may exist as a
5057 /// normal instruction or constant expression, or may have been
5058 /// derived from an expression tree.
5059 struct BinaryOp {
5060   unsigned Opcode;
5061   Value *LHS;
5062   Value *RHS;
5063   bool IsNSW = false;
5064   bool IsNUW = false;
5065 
5066   /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
5067   /// constant expression.
5068   Operator *Op = nullptr;
5069 
5070   explicit BinaryOp(Operator *Op)
5071       : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
5072         Op(Op) {
5073     if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
5074       IsNSW = OBO->hasNoSignedWrap();
5075       IsNUW = OBO->hasNoUnsignedWrap();
5076     }
5077   }
5078 
5079   explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
5080                     bool IsNUW = false)
5081       : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {}
5082 };
5083 
5084 } // end anonymous namespace
5085 
5086 /// Try to map \p V into a BinaryOp, and return \c None on failure.
5087 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) {
5088   auto *Op = dyn_cast<Operator>(V);
5089   if (!Op)
5090     return None;
5091 
5092   // Implementation detail: all the cleverness here should happen without
5093   // creating new SCEV expressions -- our caller knowns tricks to avoid creating
5094   // SCEV expressions when possible, and we should not break that.
5095 
5096   switch (Op->getOpcode()) {
5097   case Instruction::Add:
5098   case Instruction::Sub:
5099   case Instruction::Mul:
5100   case Instruction::UDiv:
5101   case Instruction::URem:
5102   case Instruction::And:
5103   case Instruction::Or:
5104   case Instruction::AShr:
5105   case Instruction::Shl:
5106     return BinaryOp(Op);
5107 
5108   case Instruction::Xor:
5109     if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
5110       // If the RHS of the xor is a signmask, then this is just an add.
5111       // Instcombine turns add of signmask into xor as a strength reduction step.
5112       if (RHSC->getValue().isSignMask())
5113         return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
5114     // Binary `xor` is a bit-wise `add`.
5115     if (V->getType()->isIntegerTy(1))
5116       return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
5117     return BinaryOp(Op);
5118 
5119   case Instruction::LShr:
5120     // Turn logical shift right of a constant into a unsigned divide.
5121     if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
5122       uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
5123 
5124       // If the shift count is not less than the bitwidth, the result of
5125       // the shift is undefined. Don't try to analyze it, because the
5126       // resolution chosen here may differ from the resolution chosen in
5127       // other parts of the compiler.
5128       if (SA->getValue().ult(BitWidth)) {
5129         Constant *X =
5130             ConstantInt::get(SA->getContext(),
5131                              APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
5132         return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
5133       }
5134     }
5135     return BinaryOp(Op);
5136 
5137   case Instruction::ExtractValue: {
5138     auto *EVI = cast<ExtractValueInst>(Op);
5139     if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
5140       break;
5141 
5142     auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand());
5143     if (!WO)
5144       break;
5145 
5146     Instruction::BinaryOps BinOp = WO->getBinaryOp();
5147     bool Signed = WO->isSigned();
5148     // TODO: Should add nuw/nsw flags for mul as well.
5149     if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT))
5150       return BinaryOp(BinOp, WO->getLHS(), WO->getRHS());
5151 
5152     // Now that we know that all uses of the arithmetic-result component of
5153     // CI are guarded by the overflow check, we can go ahead and pretend
5154     // that the arithmetic is non-overflowing.
5155     return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(),
5156                     /* IsNSW = */ Signed, /* IsNUW = */ !Signed);
5157   }
5158 
5159   default:
5160     break;
5161   }
5162 
5163   // Recognise intrinsic loop.decrement.reg, and as this has exactly the same
5164   // semantics as a Sub, return a binary sub expression.
5165   if (auto *II = dyn_cast<IntrinsicInst>(V))
5166     if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg)
5167       return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1));
5168 
5169   return None;
5170 }
5171 
5172 /// Helper function to createAddRecFromPHIWithCasts. We have a phi
5173 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
5174 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
5175 /// way. This function checks if \p Op, an operand of this SCEVAddExpr,
5176 /// follows one of the following patterns:
5177 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
5178 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
5179 /// If the SCEV expression of \p Op conforms with one of the expected patterns
5180 /// we return the type of the truncation operation, and indicate whether the
5181 /// truncated type should be treated as signed/unsigned by setting
5182 /// \p Signed to true/false, respectively.
5183 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
5184                                bool &Signed, ScalarEvolution &SE) {
5185   // The case where Op == SymbolicPHI (that is, with no type conversions on
5186   // the way) is handled by the regular add recurrence creating logic and
5187   // would have already been triggered in createAddRecForPHI. Reaching it here
5188   // means that createAddRecFromPHI had failed for this PHI before (e.g.,
5189   // because one of the other operands of the SCEVAddExpr updating this PHI is
5190   // not invariant).
5191   //
5192   // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
5193   // this case predicates that allow us to prove that Op == SymbolicPHI will
5194   // be added.
5195   if (Op == SymbolicPHI)
5196     return nullptr;
5197 
5198   unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
5199   unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
5200   if (SourceBits != NewBits)
5201     return nullptr;
5202 
5203   const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op);
5204   const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op);
5205   if (!SExt && !ZExt)
5206     return nullptr;
5207   const SCEVTruncateExpr *Trunc =
5208       SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand())
5209            : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand());
5210   if (!Trunc)
5211     return nullptr;
5212   const SCEV *X = Trunc->getOperand();
5213   if (X != SymbolicPHI)
5214     return nullptr;
5215   Signed = SExt != nullptr;
5216   return Trunc->getType();
5217 }
5218 
5219 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
5220   if (!PN->getType()->isIntegerTy())
5221     return nullptr;
5222   const Loop *L = LI.getLoopFor(PN->getParent());
5223   if (!L || L->getHeader() != PN->getParent())
5224     return nullptr;
5225   return L;
5226 }
5227 
5228 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
5229 // computation that updates the phi follows the following pattern:
5230 //   (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
5231 // which correspond to a phi->trunc->sext/zext->add->phi update chain.
5232 // If so, try to see if it can be rewritten as an AddRecExpr under some
5233 // Predicates. If successful, return them as a pair. Also cache the results
5234 // of the analysis.
5235 //
5236 // Example usage scenario:
5237 //    Say the Rewriter is called for the following SCEV:
5238 //         8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
5239 //    where:
5240 //         %X = phi i64 (%Start, %BEValue)
5241 //    It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
5242 //    and call this function with %SymbolicPHI = %X.
5243 //
5244 //    The analysis will find that the value coming around the backedge has
5245 //    the following SCEV:
5246 //         BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
5247 //    Upon concluding that this matches the desired pattern, the function
5248 //    will return the pair {NewAddRec, SmallPredsVec} where:
5249 //         NewAddRec = {%Start,+,%Step}
5250 //         SmallPredsVec = {P1, P2, P3} as follows:
5251 //           P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
5252 //           P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
5253 //           P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
5254 //    The returned pair means that SymbolicPHI can be rewritten into NewAddRec
5255 //    under the predicates {P1,P2,P3}.
5256 //    This predicated rewrite will be cached in PredicatedSCEVRewrites:
5257 //         PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
5258 //
5259 // TODO's:
5260 //
5261 // 1) Extend the Induction descriptor to also support inductions that involve
5262 //    casts: When needed (namely, when we are called in the context of the
5263 //    vectorizer induction analysis), a Set of cast instructions will be
5264 //    populated by this method, and provided back to isInductionPHI. This is
5265 //    needed to allow the vectorizer to properly record them to be ignored by
5266 //    the cost model and to avoid vectorizing them (otherwise these casts,
5267 //    which are redundant under the runtime overflow checks, will be
5268 //    vectorized, which can be costly).
5269 //
5270 // 2) Support additional induction/PHISCEV patterns: We also want to support
5271 //    inductions where the sext-trunc / zext-trunc operations (partly) occur
5272 //    after the induction update operation (the induction increment):
5273 //
5274 //      (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
5275 //    which correspond to a phi->add->trunc->sext/zext->phi update chain.
5276 //
5277 //      (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
5278 //    which correspond to a phi->trunc->add->sext/zext->phi update chain.
5279 //
5280 // 3) Outline common code with createAddRecFromPHI to avoid duplication.
5281 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5282 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
5283   SmallVector<const SCEVPredicate *, 3> Predicates;
5284 
5285   // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
5286   // return an AddRec expression under some predicate.
5287 
5288   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
5289   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
5290   assert(L && "Expecting an integer loop header phi");
5291 
5292   // The loop may have multiple entrances or multiple exits; we can analyze
5293   // this phi as an addrec if it has a unique entry value and a unique
5294   // backedge value.
5295   Value *BEValueV = nullptr, *StartValueV = nullptr;
5296   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5297     Value *V = PN->getIncomingValue(i);
5298     if (L->contains(PN->getIncomingBlock(i))) {
5299       if (!BEValueV) {
5300         BEValueV = V;
5301       } else if (BEValueV != V) {
5302         BEValueV = nullptr;
5303         break;
5304       }
5305     } else if (!StartValueV) {
5306       StartValueV = V;
5307     } else if (StartValueV != V) {
5308       StartValueV = nullptr;
5309       break;
5310     }
5311   }
5312   if (!BEValueV || !StartValueV)
5313     return None;
5314 
5315   const SCEV *BEValue = getSCEV(BEValueV);
5316 
5317   // If the value coming around the backedge is an add with the symbolic
5318   // value we just inserted, possibly with casts that we can ignore under
5319   // an appropriate runtime guard, then we found a simple induction variable!
5320   const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
5321   if (!Add)
5322     return None;
5323 
5324   // If there is a single occurrence of the symbolic value, possibly
5325   // casted, replace it with a recurrence.
5326   unsigned FoundIndex = Add->getNumOperands();
5327   Type *TruncTy = nullptr;
5328   bool Signed;
5329   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5330     if ((TruncTy =
5331              isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
5332       if (FoundIndex == e) {
5333         FoundIndex = i;
5334         break;
5335       }
5336 
5337   if (FoundIndex == Add->getNumOperands())
5338     return None;
5339 
5340   // Create an add with everything but the specified operand.
5341   SmallVector<const SCEV *, 8> Ops;
5342   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5343     if (i != FoundIndex)
5344       Ops.push_back(Add->getOperand(i));
5345   const SCEV *Accum = getAddExpr(Ops);
5346 
5347   // The runtime checks will not be valid if the step amount is
5348   // varying inside the loop.
5349   if (!isLoopInvariant(Accum, L))
5350     return None;
5351 
5352   // *** Part2: Create the predicates
5353 
5354   // Analysis was successful: we have a phi-with-cast pattern for which we
5355   // can return an AddRec expression under the following predicates:
5356   //
5357   // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
5358   //     fits within the truncated type (does not overflow) for i = 0 to n-1.
5359   // P2: An Equal predicate that guarantees that
5360   //     Start = (Ext ix (Trunc iy (Start) to ix) to iy)
5361   // P3: An Equal predicate that guarantees that
5362   //     Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
5363   //
5364   // As we next prove, the above predicates guarantee that:
5365   //     Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
5366   //
5367   //
5368   // More formally, we want to prove that:
5369   //     Expr(i+1) = Start + (i+1) * Accum
5370   //               = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5371   //
5372   // Given that:
5373   // 1) Expr(0) = Start
5374   // 2) Expr(1) = Start + Accum
5375   //            = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
5376   // 3) Induction hypothesis (step i):
5377   //    Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
5378   //
5379   // Proof:
5380   //  Expr(i+1) =
5381   //   = Start + (i+1)*Accum
5382   //   = (Start + i*Accum) + Accum
5383   //   = Expr(i) + Accum
5384   //   = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
5385   //                                                             :: from step i
5386   //
5387   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
5388   //
5389   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
5390   //     + (Ext ix (Trunc iy (Accum) to ix) to iy)
5391   //     + Accum                                                     :: from P3
5392   //
5393   //   = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
5394   //     + Accum                            :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
5395   //
5396   //   = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
5397   //   = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5398   //
5399   // By induction, the same applies to all iterations 1<=i<n:
5400   //
5401 
5402   // Create a truncated addrec for which we will add a no overflow check (P1).
5403   const SCEV *StartVal = getSCEV(StartValueV);
5404   const SCEV *PHISCEV =
5405       getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
5406                     getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap);
5407 
5408   // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
5409   // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
5410   // will be constant.
5411   //
5412   //  If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
5413   // add P1.
5414   if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
5415     SCEVWrapPredicate::IncrementWrapFlags AddedFlags =
5416         Signed ? SCEVWrapPredicate::IncrementNSSW
5417                : SCEVWrapPredicate::IncrementNUSW;
5418     const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
5419     Predicates.push_back(AddRecPred);
5420   }
5421 
5422   // Create the Equal Predicates P2,P3:
5423 
5424   // It is possible that the predicates P2 and/or P3 are computable at
5425   // compile time due to StartVal and/or Accum being constants.
5426   // If either one is, then we can check that now and escape if either P2
5427   // or P3 is false.
5428 
5429   // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
5430   // for each of StartVal and Accum
5431   auto getExtendedExpr = [&](const SCEV *Expr,
5432                              bool CreateSignExtend) -> const SCEV * {
5433     assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant");
5434     const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
5435     const SCEV *ExtendedExpr =
5436         CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType())
5437                          : getZeroExtendExpr(TruncatedExpr, Expr->getType());
5438     return ExtendedExpr;
5439   };
5440 
5441   // Given:
5442   //  ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
5443   //               = getExtendedExpr(Expr)
5444   // Determine whether the predicate P: Expr == ExtendedExpr
5445   // is known to be false at compile time
5446   auto PredIsKnownFalse = [&](const SCEV *Expr,
5447                               const SCEV *ExtendedExpr) -> bool {
5448     return Expr != ExtendedExpr &&
5449            isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr);
5450   };
5451 
5452   const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
5453   if (PredIsKnownFalse(StartVal, StartExtended)) {
5454     LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";);
5455     return None;
5456   }
5457 
5458   // The Step is always Signed (because the overflow checks are either
5459   // NSSW or NUSW)
5460   const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true);
5461   if (PredIsKnownFalse(Accum, AccumExtended)) {
5462     LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";);
5463     return None;
5464   }
5465 
5466   auto AppendPredicate = [&](const SCEV *Expr,
5467                              const SCEV *ExtendedExpr) -> void {
5468     if (Expr != ExtendedExpr &&
5469         !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
5470       const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
5471       LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred);
5472       Predicates.push_back(Pred);
5473     }
5474   };
5475 
5476   AppendPredicate(StartVal, StartExtended);
5477   AppendPredicate(Accum, AccumExtended);
5478 
5479   // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
5480   // which the casts had been folded away. The caller can rewrite SymbolicPHI
5481   // into NewAR if it will also add the runtime overflow checks specified in
5482   // Predicates.
5483   auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap);
5484 
5485   std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
5486       std::make_pair(NewAR, Predicates);
5487   // Remember the result of the analysis for this SCEV at this locayyytion.
5488   PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
5489   return PredRewrite;
5490 }
5491 
5492 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5493 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) {
5494   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
5495   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
5496   if (!L)
5497     return None;
5498 
5499   // Check to see if we already analyzed this PHI.
5500   auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
5501   if (I != PredicatedSCEVRewrites.end()) {
5502     std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
5503         I->second;
5504     // Analysis was done before and failed to create an AddRec:
5505     if (Rewrite.first == SymbolicPHI)
5506       return None;
5507     // Analysis was done before and succeeded to create an AddRec under
5508     // a predicate:
5509     assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec");
5510     assert(!(Rewrite.second).empty() && "Expected to find Predicates");
5511     return Rewrite;
5512   }
5513 
5514   Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5515     Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
5516 
5517   // Record in the cache that the analysis failed
5518   if (!Rewrite) {
5519     SmallVector<const SCEVPredicate *, 3> Predicates;
5520     PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
5521     return None;
5522   }
5523 
5524   return Rewrite;
5525 }
5526 
5527 // FIXME: This utility is currently required because the Rewriter currently
5528 // does not rewrite this expression:
5529 // {0, +, (sext ix (trunc iy to ix) to iy)}
5530 // into {0, +, %step},
5531 // even when the following Equal predicate exists:
5532 // "%step == (sext ix (trunc iy to ix) to iy)".
5533 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds(
5534     const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const {
5535   if (AR1 == AR2)
5536     return true;
5537 
5538   auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool {
5539     if (Expr1 != Expr2 && !Preds->implies(SE.getEqualPredicate(Expr1, Expr2)) &&
5540         !Preds->implies(SE.getEqualPredicate(Expr2, Expr1)))
5541       return false;
5542     return true;
5543   };
5544 
5545   if (!areExprsEqual(AR1->getStart(), AR2->getStart()) ||
5546       !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE)))
5547     return false;
5548   return true;
5549 }
5550 
5551 /// A helper function for createAddRecFromPHI to handle simple cases.
5552 ///
5553 /// This function tries to find an AddRec expression for the simplest (yet most
5554 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
5555 /// If it fails, createAddRecFromPHI will use a more general, but slow,
5556 /// technique for finding the AddRec expression.
5557 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
5558                                                       Value *BEValueV,
5559                                                       Value *StartValueV) {
5560   const Loop *L = LI.getLoopFor(PN->getParent());
5561   assert(L && L->getHeader() == PN->getParent());
5562   assert(BEValueV && StartValueV);
5563 
5564   auto BO = MatchBinaryOp(BEValueV, DT);
5565   if (!BO)
5566     return nullptr;
5567 
5568   if (BO->Opcode != Instruction::Add)
5569     return nullptr;
5570 
5571   const SCEV *Accum = nullptr;
5572   if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
5573     Accum = getSCEV(BO->RHS);
5574   else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
5575     Accum = getSCEV(BO->LHS);
5576 
5577   if (!Accum)
5578     return nullptr;
5579 
5580   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5581   if (BO->IsNUW)
5582     Flags = setFlags(Flags, SCEV::FlagNUW);
5583   if (BO->IsNSW)
5584     Flags = setFlags(Flags, SCEV::FlagNSW);
5585 
5586   const SCEV *StartVal = getSCEV(StartValueV);
5587   const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5588   insertValueToMap(PN, PHISCEV);
5589 
5590   // We can add Flags to the post-inc expression only if we
5591   // know that it is *undefined behavior* for BEValueV to
5592   // overflow.
5593   if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) {
5594     assert(isLoopInvariant(Accum, L) &&
5595            "Accum is defined outside L, but is not invariant?");
5596     if (isAddRecNeverPoison(BEInst, L))
5597       (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5598   }
5599 
5600   return PHISCEV;
5601 }
5602 
5603 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
5604   const Loop *L = LI.getLoopFor(PN->getParent());
5605   if (!L || L->getHeader() != PN->getParent())
5606     return nullptr;
5607 
5608   // The loop may have multiple entrances or multiple exits; we can analyze
5609   // this phi as an addrec if it has a unique entry value and a unique
5610   // backedge value.
5611   Value *BEValueV = nullptr, *StartValueV = nullptr;
5612   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5613     Value *V = PN->getIncomingValue(i);
5614     if (L->contains(PN->getIncomingBlock(i))) {
5615       if (!BEValueV) {
5616         BEValueV = V;
5617       } else if (BEValueV != V) {
5618         BEValueV = nullptr;
5619         break;
5620       }
5621     } else if (!StartValueV) {
5622       StartValueV = V;
5623     } else if (StartValueV != V) {
5624       StartValueV = nullptr;
5625       break;
5626     }
5627   }
5628   if (!BEValueV || !StartValueV)
5629     return nullptr;
5630 
5631   assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
5632          "PHI node already processed?");
5633 
5634   // First, try to find AddRec expression without creating a fictituos symbolic
5635   // value for PN.
5636   if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
5637     return S;
5638 
5639   // Handle PHI node value symbolically.
5640   const SCEV *SymbolicName = getUnknown(PN);
5641   insertValueToMap(PN, SymbolicName);
5642 
5643   // Using this symbolic name for the PHI, analyze the value coming around
5644   // the back-edge.
5645   const SCEV *BEValue = getSCEV(BEValueV);
5646 
5647   // NOTE: If BEValue is loop invariant, we know that the PHI node just
5648   // has a special value for the first iteration of the loop.
5649 
5650   // If the value coming around the backedge is an add with the symbolic
5651   // value we just inserted, then we found a simple induction variable!
5652   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
5653     // If there is a single occurrence of the symbolic value, replace it
5654     // with a recurrence.
5655     unsigned FoundIndex = Add->getNumOperands();
5656     for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5657       if (Add->getOperand(i) == SymbolicName)
5658         if (FoundIndex == e) {
5659           FoundIndex = i;
5660           break;
5661         }
5662 
5663     if (FoundIndex != Add->getNumOperands()) {
5664       // Create an add with everything but the specified operand.
5665       SmallVector<const SCEV *, 8> Ops;
5666       for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5667         if (i != FoundIndex)
5668           Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i),
5669                                                              L, *this));
5670       const SCEV *Accum = getAddExpr(Ops);
5671 
5672       // This is not a valid addrec if the step amount is varying each
5673       // loop iteration, but is not itself an addrec in this loop.
5674       if (isLoopInvariant(Accum, L) ||
5675           (isa<SCEVAddRecExpr>(Accum) &&
5676            cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
5677         SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5678 
5679         if (auto BO = MatchBinaryOp(BEValueV, DT)) {
5680           if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
5681             if (BO->IsNUW)
5682               Flags = setFlags(Flags, SCEV::FlagNUW);
5683             if (BO->IsNSW)
5684               Flags = setFlags(Flags, SCEV::FlagNSW);
5685           }
5686         } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
5687           // If the increment is an inbounds GEP, then we know the address
5688           // space cannot be wrapped around. We cannot make any guarantee
5689           // about signed or unsigned overflow because pointers are
5690           // unsigned but we may have a negative index from the base
5691           // pointer. We can guarantee that no unsigned wrap occurs if the
5692           // indices form a positive value.
5693           if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
5694             Flags = setFlags(Flags, SCEV::FlagNW);
5695 
5696             const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
5697             if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
5698               Flags = setFlags(Flags, SCEV::FlagNUW);
5699           }
5700 
5701           // We cannot transfer nuw and nsw flags from subtraction
5702           // operations -- sub nuw X, Y is not the same as add nuw X, -Y
5703           // for instance.
5704         }
5705 
5706         const SCEV *StartVal = getSCEV(StartValueV);
5707         const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5708 
5709         // Okay, for the entire analysis of this edge we assumed the PHI
5710         // to be symbolic.  We now need to go back and purge all of the
5711         // entries for the scalars that use the symbolic expression.
5712         forgetMemoizedResults(SymbolicName);
5713         insertValueToMap(PN, PHISCEV);
5714 
5715         // We can add Flags to the post-inc expression only if we
5716         // know that it is *undefined behavior* for BEValueV to
5717         // overflow.
5718         if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5719           if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5720             (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5721 
5722         return PHISCEV;
5723       }
5724     }
5725   } else {
5726     // Otherwise, this could be a loop like this:
5727     //     i = 0;  for (j = 1; ..; ++j) { ....  i = j; }
5728     // In this case, j = {1,+,1}  and BEValue is j.
5729     // Because the other in-value of i (0) fits the evolution of BEValue
5730     // i really is an addrec evolution.
5731     //
5732     // We can generalize this saying that i is the shifted value of BEValue
5733     // by one iteration:
5734     //   PHI(f(0), f({1,+,1})) --> f({0,+,1})
5735     const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
5736     const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false);
5737     if (Shifted != getCouldNotCompute() &&
5738         Start != getCouldNotCompute()) {
5739       const SCEV *StartVal = getSCEV(StartValueV);
5740       if (Start == StartVal) {
5741         // Okay, for the entire analysis of this edge we assumed the PHI
5742         // to be symbolic.  We now need to go back and purge all of the
5743         // entries for the scalars that use the symbolic expression.
5744         forgetMemoizedResults(SymbolicName);
5745         insertValueToMap(PN, Shifted);
5746         return Shifted;
5747       }
5748     }
5749   }
5750 
5751   // Remove the temporary PHI node SCEV that has been inserted while intending
5752   // to create an AddRecExpr for this PHI node. We can not keep this temporary
5753   // as it will prevent later (possibly simpler) SCEV expressions to be added
5754   // to the ValueExprMap.
5755   eraseValueFromMap(PN);
5756 
5757   return nullptr;
5758 }
5759 
5760 // Checks if the SCEV S is available at BB.  S is considered available at BB
5761 // if S can be materialized at BB without introducing a fault.
5762 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
5763                                BasicBlock *BB) {
5764   struct CheckAvailable {
5765     bool TraversalDone = false;
5766     bool Available = true;
5767 
5768     const Loop *L = nullptr;  // The loop BB is in (can be nullptr)
5769     BasicBlock *BB = nullptr;
5770     DominatorTree &DT;
5771 
5772     CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
5773       : L(L), BB(BB), DT(DT) {}
5774 
5775     bool setUnavailable() {
5776       TraversalDone = true;
5777       Available = false;
5778       return false;
5779     }
5780 
5781     bool follow(const SCEV *S) {
5782       switch (S->getSCEVType()) {
5783       case scConstant:
5784       case scPtrToInt:
5785       case scTruncate:
5786       case scZeroExtend:
5787       case scSignExtend:
5788       case scAddExpr:
5789       case scMulExpr:
5790       case scUMaxExpr:
5791       case scSMaxExpr:
5792       case scUMinExpr:
5793       case scSMinExpr:
5794       case scSequentialUMinExpr:
5795         // These expressions are available if their operand(s) is/are.
5796         return true;
5797 
5798       case scAddRecExpr: {
5799         // We allow add recurrences that are on the loop BB is in, or some
5800         // outer loop.  This guarantees availability because the value of the
5801         // add recurrence at BB is simply the "current" value of the induction
5802         // variable.  We can relax this in the future; for instance an add
5803         // recurrence on a sibling dominating loop is also available at BB.
5804         const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
5805         if (L && (ARLoop == L || ARLoop->contains(L)))
5806           return true;
5807 
5808         return setUnavailable();
5809       }
5810 
5811       case scUnknown: {
5812         // For SCEVUnknown, we check for simple dominance.
5813         const auto *SU = cast<SCEVUnknown>(S);
5814         Value *V = SU->getValue();
5815 
5816         if (isa<Argument>(V))
5817           return false;
5818 
5819         if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
5820           return false;
5821 
5822         return setUnavailable();
5823       }
5824 
5825       case scUDivExpr:
5826       case scCouldNotCompute:
5827         // We do not try to smart about these at all.
5828         return setUnavailable();
5829       }
5830       llvm_unreachable("Unknown SCEV kind!");
5831     }
5832 
5833     bool isDone() { return TraversalDone; }
5834   };
5835 
5836   CheckAvailable CA(L, BB, DT);
5837   SCEVTraversal<CheckAvailable> ST(CA);
5838 
5839   ST.visitAll(S);
5840   return CA.Available;
5841 }
5842 
5843 // Try to match a control flow sequence that branches out at BI and merges back
5844 // at Merge into a "C ? LHS : RHS" select pattern.  Return true on a successful
5845 // match.
5846 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
5847                           Value *&C, Value *&LHS, Value *&RHS) {
5848   C = BI->getCondition();
5849 
5850   BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
5851   BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
5852 
5853   if (!LeftEdge.isSingleEdge())
5854     return false;
5855 
5856   assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
5857 
5858   Use &LeftUse = Merge->getOperandUse(0);
5859   Use &RightUse = Merge->getOperandUse(1);
5860 
5861   if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
5862     LHS = LeftUse;
5863     RHS = RightUse;
5864     return true;
5865   }
5866 
5867   if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
5868     LHS = RightUse;
5869     RHS = LeftUse;
5870     return true;
5871   }
5872 
5873   return false;
5874 }
5875 
5876 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
5877   auto IsReachable =
5878       [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
5879   if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
5880     const Loop *L = LI.getLoopFor(PN->getParent());
5881 
5882     // We don't want to break LCSSA, even in a SCEV expression tree.
5883     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
5884       if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
5885         return nullptr;
5886 
5887     // Try to match
5888     //
5889     //  br %cond, label %left, label %right
5890     // left:
5891     //  br label %merge
5892     // right:
5893     //  br label %merge
5894     // merge:
5895     //  V = phi [ %x, %left ], [ %y, %right ]
5896     //
5897     // as "select %cond, %x, %y"
5898 
5899     BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
5900     assert(IDom && "At least the entry block should dominate PN");
5901 
5902     auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
5903     Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
5904 
5905     if (BI && BI->isConditional() &&
5906         BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
5907         IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
5908         IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
5909       return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
5910   }
5911 
5912   return nullptr;
5913 }
5914 
5915 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
5916   if (const SCEV *S = createAddRecFromPHI(PN))
5917     return S;
5918 
5919   if (const SCEV *S = createNodeFromSelectLikePHI(PN))
5920     return S;
5921 
5922   // If the PHI has a single incoming value, follow that value, unless the
5923   // PHI's incoming blocks are in a different loop, in which case doing so
5924   // risks breaking LCSSA form. Instcombine would normally zap these, but
5925   // it doesn't have DominatorTree information, so it may miss cases.
5926   if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC}))
5927     if (LI.replacementPreservesLCSSAForm(PN, V))
5928       return getSCEV(V);
5929 
5930   // If it's not a loop phi, we can't handle it yet.
5931   return getUnknown(PN);
5932 }
5933 
5934 bool SCEVMinMaxExprContains(const SCEV *Root, const SCEV *OperandToFind,
5935                             SCEVTypes RootKind) {
5936   struct FindClosure {
5937     const SCEV *OperandToFind;
5938     const SCEVTypes RootKind; // Must be a sequential min/max expression.
5939     const SCEVTypes NonSequentialRootKind; // Non-seq variant of RootKind.
5940 
5941     bool Found = false;
5942 
5943     bool canRecurseInto(SCEVTypes Kind) const {
5944       // We can only recurse into the SCEV expression of the same effective type
5945       // as the type of our root SCEV expression, and into zero-extensions.
5946       return RootKind == Kind || NonSequentialRootKind == Kind ||
5947              scZeroExtend == Kind;
5948     };
5949 
5950     FindClosure(const SCEV *OperandToFind, SCEVTypes RootKind)
5951         : OperandToFind(OperandToFind), RootKind(RootKind),
5952           NonSequentialRootKind(
5953               SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType(
5954                   RootKind)) {}
5955 
5956     bool follow(const SCEV *S) {
5957       Found = S == OperandToFind;
5958 
5959       return !isDone() && canRecurseInto(S->getSCEVType());
5960     }
5961 
5962     bool isDone() const { return Found; }
5963   };
5964 
5965   FindClosure FC(OperandToFind, RootKind);
5966   visitAll(Root, FC);
5967   return FC.Found;
5968 }
5969 
5970 const SCEV *ScalarEvolution::createNodeForSelectOrPHIInstWithICmpInstCond(
5971     Instruction *I, ICmpInst *Cond, Value *TrueVal, Value *FalseVal) {
5972   // Try to match some simple smax or umax patterns.
5973   auto *ICI = Cond;
5974 
5975   Value *LHS = ICI->getOperand(0);
5976   Value *RHS = ICI->getOperand(1);
5977 
5978   switch (ICI->getPredicate()) {
5979   case ICmpInst::ICMP_SLT:
5980   case ICmpInst::ICMP_SLE:
5981   case ICmpInst::ICMP_ULT:
5982   case ICmpInst::ICMP_ULE:
5983     std::swap(LHS, RHS);
5984     LLVM_FALLTHROUGH;
5985   case ICmpInst::ICMP_SGT:
5986   case ICmpInst::ICMP_SGE:
5987   case ICmpInst::ICMP_UGT:
5988   case ICmpInst::ICMP_UGE:
5989     // a > b ? a+x : b+x  ->  max(a, b)+x
5990     // a > b ? b+x : a+x  ->  min(a, b)+x
5991     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5992       bool Signed = ICI->isSigned();
5993       const SCEV *LA = getSCEV(TrueVal);
5994       const SCEV *RA = getSCEV(FalseVal);
5995       const SCEV *LS = getSCEV(LHS);
5996       const SCEV *RS = getSCEV(RHS);
5997       if (LA->getType()->isPointerTy()) {
5998         // FIXME: Handle cases where LS/RS are pointers not equal to LA/RA.
5999         // Need to make sure we can't produce weird expressions involving
6000         // negated pointers.
6001         if (LA == LS && RA == RS)
6002           return Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS);
6003         if (LA == RS && RA == LS)
6004           return Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS);
6005       }
6006       auto CoerceOperand = [&](const SCEV *Op) -> const SCEV * {
6007         if (Op->getType()->isPointerTy()) {
6008           Op = getLosslessPtrToIntExpr(Op);
6009           if (isa<SCEVCouldNotCompute>(Op))
6010             return Op;
6011         }
6012         if (Signed)
6013           Op = getNoopOrSignExtend(Op, I->getType());
6014         else
6015           Op = getNoopOrZeroExtend(Op, I->getType());
6016         return Op;
6017       };
6018       LS = CoerceOperand(LS);
6019       RS = CoerceOperand(RS);
6020       if (isa<SCEVCouldNotCompute>(LS) || isa<SCEVCouldNotCompute>(RS))
6021         break;
6022       const SCEV *LDiff = getMinusSCEV(LA, LS);
6023       const SCEV *RDiff = getMinusSCEV(RA, RS);
6024       if (LDiff == RDiff)
6025         return getAddExpr(Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS),
6026                           LDiff);
6027       LDiff = getMinusSCEV(LA, RS);
6028       RDiff = getMinusSCEV(RA, LS);
6029       if (LDiff == RDiff)
6030         return getAddExpr(Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS),
6031                           LDiff);
6032     }
6033     break;
6034   case ICmpInst::ICMP_NE:
6035     // x != 0 ? x+y : C+y  ->  x == 0 ? C+y : x+y
6036     std::swap(TrueVal, FalseVal);
6037     LLVM_FALLTHROUGH;
6038   case ICmpInst::ICMP_EQ:
6039     // x == 0 ? C+y : x+y  ->  umax(x, C)+y   iff C u<= 1
6040     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
6041         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
6042       const SCEV *X = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
6043       const SCEV *TrueValExpr = getSCEV(TrueVal);    // C+y
6044       const SCEV *FalseValExpr = getSCEV(FalseVal);  // x+y
6045       const SCEV *Y = getMinusSCEV(FalseValExpr, X); // y = (x+y)-x
6046       const SCEV *C = getMinusSCEV(TrueValExpr, Y);  // C = (C+y)-y
6047       if (isa<SCEVConstant>(C) && cast<SCEVConstant>(C)->getAPInt().ule(1))
6048         return getAddExpr(getUMaxExpr(X, C), Y);
6049     }
6050     // x == 0 ? 0 : umin    (..., x, ...)  ->  umin_seq(x, umin    (...))
6051     // x == 0 ? 0 : umin_seq(..., x, ...)  ->  umin_seq(x, umin_seq(...))
6052     // x == 0 ? 0 : umin    (..., umin_seq(..., x, ...), ...)
6053     //                    ->  umin_seq(x, umin (..., umin_seq(...), ...))
6054     if (isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero() &&
6055         isa<ConstantInt>(TrueVal) && cast<ConstantInt>(TrueVal)->isZero()) {
6056       const SCEV *X = getSCEV(LHS);
6057       while (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(X))
6058         X = ZExt->getOperand();
6059       if (getTypeSizeInBits(X->getType()) <= getTypeSizeInBits(I->getType())) {
6060         const SCEV *FalseValExpr = getSCEV(FalseVal);
6061         if (SCEVMinMaxExprContains(FalseValExpr, X, scSequentialUMinExpr))
6062           return getUMinExpr(getNoopOrZeroExtend(X, I->getType()), FalseValExpr,
6063                              /*Sequential=*/true);
6064       }
6065     }
6066     break;
6067   default:
6068     break;
6069   }
6070 
6071   return getUnknown(I);
6072 }
6073 
6074 static Optional<const SCEV *>
6075 createNodeForSelectViaUMinSeq(ScalarEvolution *SE, const SCEV *CondExpr,
6076                               const SCEV *TrueExpr, const SCEV *FalseExpr) {
6077   assert(CondExpr->getType()->isIntegerTy(1) &&
6078          TrueExpr->getType() == FalseExpr->getType() &&
6079          TrueExpr->getType()->isIntegerTy(1) &&
6080          "Unexpected operands of a select.");
6081 
6082   // i1 cond ? i1 x : i1 C  -->  C + (i1  cond ? (i1 x - i1 C) : i1 0)
6083   //                        -->  C + (umin_seq  cond, x - C)
6084   //
6085   // i1 cond ? i1 C : i1 x  -->  C + (i1  cond ? i1 0 : (i1 x - i1 C))
6086   //                        -->  C + (i1 ~cond ? (i1 x - i1 C) : i1 0)
6087   //                        -->  C + (umin_seq ~cond, x - C)
6088 
6089   // FIXME: while we can't legally model the case where both of the hands
6090   // are fully variable, we only require that the *difference* is constant.
6091   if (!isa<SCEVConstant>(TrueExpr) && !isa<SCEVConstant>(FalseExpr))
6092     return None;
6093 
6094   const SCEV *X, *C;
6095   if (isa<SCEVConstant>(TrueExpr)) {
6096     CondExpr = SE->getNotSCEV(CondExpr);
6097     X = FalseExpr;
6098     C = TrueExpr;
6099   } else {
6100     X = TrueExpr;
6101     C = FalseExpr;
6102   }
6103   return SE->getAddExpr(C, SE->getUMinExpr(CondExpr, SE->getMinusSCEV(X, C),
6104                                            /*Sequential=*/true));
6105 }
6106 
6107 static Optional<const SCEV *> createNodeForSelectViaUMinSeq(ScalarEvolution *SE,
6108                                                             Value *Cond,
6109                                                             Value *TrueVal,
6110                                                             Value *FalseVal) {
6111   if (!isa<ConstantInt>(TrueVal) && !isa<ConstantInt>(FalseVal))
6112     return None;
6113 
6114   return createNodeForSelectViaUMinSeq(
6115       SE, SE->getSCEV(Cond), SE->getSCEV(TrueVal), SE->getSCEV(FalseVal));
6116 }
6117 
6118 const SCEV *ScalarEvolution::createNodeForSelectOrPHIViaUMinSeq(
6119     Value *V, Value *Cond, Value *TrueVal, Value *FalseVal) {
6120   assert(Cond->getType()->isIntegerTy(1) && "Select condition is not an i1?");
6121   assert(TrueVal->getType() == FalseVal->getType() &&
6122          V->getType() == TrueVal->getType() &&
6123          "Types of select hands and of the result must match.");
6124 
6125   // For now, only deal with i1-typed `select`s.
6126   if (!V->getType()->isIntegerTy(1))
6127     return getUnknown(V);
6128 
6129   if (Optional<const SCEV *> S =
6130           createNodeForSelectViaUMinSeq(this, Cond, TrueVal, FalseVal))
6131     return *S;
6132 
6133   return getUnknown(V);
6134 }
6135 
6136 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Value *V, Value *Cond,
6137                                                       Value *TrueVal,
6138                                                       Value *FalseVal) {
6139   // Handle "constant" branch or select. This can occur for instance when a
6140   // loop pass transforms an inner loop and moves on to process the outer loop.
6141   if (auto *CI = dyn_cast<ConstantInt>(Cond))
6142     return getSCEV(CI->isOne() ? TrueVal : FalseVal);
6143 
6144   if (auto *I = dyn_cast<Instruction>(V)) {
6145     if (auto *ICI = dyn_cast<ICmpInst>(Cond)) {
6146       const SCEV *S = createNodeForSelectOrPHIInstWithICmpInstCond(
6147           I, ICI, TrueVal, FalseVal);
6148       if (!isa<SCEVUnknown>(S))
6149         return S;
6150     }
6151   }
6152 
6153   return createNodeForSelectOrPHIViaUMinSeq(V, Cond, TrueVal, FalseVal);
6154 }
6155 
6156 /// Expand GEP instructions into add and multiply operations. This allows them
6157 /// to be analyzed by regular SCEV code.
6158 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
6159   // Don't attempt to analyze GEPs over unsized objects.
6160   if (!GEP->getSourceElementType()->isSized())
6161     return getUnknown(GEP);
6162 
6163   SmallVector<const SCEV *, 4> IndexExprs;
6164   for (Value *Index : GEP->indices())
6165     IndexExprs.push_back(getSCEV(Index));
6166   return getGEPExpr(GEP, IndexExprs);
6167 }
6168 
6169 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) {
6170   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
6171     return C->getAPInt().countTrailingZeros();
6172 
6173   if (const SCEVPtrToIntExpr *I = dyn_cast<SCEVPtrToIntExpr>(S))
6174     return GetMinTrailingZeros(I->getOperand());
6175 
6176   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
6177     return std::min(GetMinTrailingZeros(T->getOperand()),
6178                     (uint32_t)getTypeSizeInBits(T->getType()));
6179 
6180   if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
6181     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
6182     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
6183                ? getTypeSizeInBits(E->getType())
6184                : OpRes;
6185   }
6186 
6187   if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
6188     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
6189     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
6190                ? getTypeSizeInBits(E->getType())
6191                : OpRes;
6192   }
6193 
6194   if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
6195     // The result is the min of all operands results.
6196     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
6197     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
6198       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
6199     return MinOpRes;
6200   }
6201 
6202   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
6203     // The result is the sum of all operands results.
6204     uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
6205     uint32_t BitWidth = getTypeSizeInBits(M->getType());
6206     for (unsigned i = 1, e = M->getNumOperands();
6207          SumOpRes != BitWidth && i != e; ++i)
6208       SumOpRes =
6209           std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth);
6210     return SumOpRes;
6211   }
6212 
6213   if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
6214     // The result is the min of all operands results.
6215     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
6216     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
6217       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
6218     return MinOpRes;
6219   }
6220 
6221   if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
6222     // The result is the min of all operands results.
6223     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
6224     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
6225       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
6226     return MinOpRes;
6227   }
6228 
6229   if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
6230     // The result is the min of all operands results.
6231     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
6232     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
6233       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
6234     return MinOpRes;
6235   }
6236 
6237   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
6238     // For a SCEVUnknown, ask ValueTracking.
6239     KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT);
6240     return Known.countMinTrailingZeros();
6241   }
6242 
6243   // SCEVUDivExpr
6244   return 0;
6245 }
6246 
6247 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
6248   auto I = MinTrailingZerosCache.find(S);
6249   if (I != MinTrailingZerosCache.end())
6250     return I->second;
6251 
6252   uint32_t Result = GetMinTrailingZerosImpl(S);
6253   auto InsertPair = MinTrailingZerosCache.insert({S, Result});
6254   assert(InsertPair.second && "Should insert a new key");
6255   return InsertPair.first->second;
6256 }
6257 
6258 /// Helper method to assign a range to V from metadata present in the IR.
6259 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
6260   if (Instruction *I = dyn_cast<Instruction>(V))
6261     if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
6262       return getConstantRangeFromMetadata(*MD);
6263 
6264   return None;
6265 }
6266 
6267 void ScalarEvolution::setNoWrapFlags(SCEVAddRecExpr *AddRec,
6268                                      SCEV::NoWrapFlags Flags) {
6269   if (AddRec->getNoWrapFlags(Flags) != Flags) {
6270     AddRec->setNoWrapFlags(Flags);
6271     UnsignedRanges.erase(AddRec);
6272     SignedRanges.erase(AddRec);
6273   }
6274 }
6275 
6276 ConstantRange ScalarEvolution::
6277 getRangeForUnknownRecurrence(const SCEVUnknown *U) {
6278   const DataLayout &DL = getDataLayout();
6279 
6280   unsigned BitWidth = getTypeSizeInBits(U->getType());
6281   const ConstantRange FullSet(BitWidth, /*isFullSet=*/true);
6282 
6283   // Match a simple recurrence of the form: <start, ShiftOp, Step>, and then
6284   // use information about the trip count to improve our available range.  Note
6285   // that the trip count independent cases are already handled by known bits.
6286   // WARNING: The definition of recurrence used here is subtly different than
6287   // the one used by AddRec (and thus most of this file).  Step is allowed to
6288   // be arbitrarily loop varying here, where AddRec allows only loop invariant
6289   // and other addrecs in the same loop (for non-affine addrecs).  The code
6290   // below intentionally handles the case where step is not loop invariant.
6291   auto *P = dyn_cast<PHINode>(U->getValue());
6292   if (!P)
6293     return FullSet;
6294 
6295   // Make sure that no Phi input comes from an unreachable block. Otherwise,
6296   // even the values that are not available in these blocks may come from them,
6297   // and this leads to false-positive recurrence test.
6298   for (auto *Pred : predecessors(P->getParent()))
6299     if (!DT.isReachableFromEntry(Pred))
6300       return FullSet;
6301 
6302   BinaryOperator *BO;
6303   Value *Start, *Step;
6304   if (!matchSimpleRecurrence(P, BO, Start, Step))
6305     return FullSet;
6306 
6307   // If we found a recurrence in reachable code, we must be in a loop. Note
6308   // that BO might be in some subloop of L, and that's completely okay.
6309   auto *L = LI.getLoopFor(P->getParent());
6310   assert(L && L->getHeader() == P->getParent());
6311   if (!L->contains(BO->getParent()))
6312     // NOTE: This bailout should be an assert instead.  However, asserting
6313     // the condition here exposes a case where LoopFusion is querying SCEV
6314     // with malformed loop information during the midst of the transform.
6315     // There doesn't appear to be an obvious fix, so for the moment bailout
6316     // until the caller issue can be fixed.  PR49566 tracks the bug.
6317     return FullSet;
6318 
6319   // TODO: Extend to other opcodes such as mul, and div
6320   switch (BO->getOpcode()) {
6321   default:
6322     return FullSet;
6323   case Instruction::AShr:
6324   case Instruction::LShr:
6325   case Instruction::Shl:
6326     break;
6327   };
6328 
6329   if (BO->getOperand(0) != P)
6330     // TODO: Handle the power function forms some day.
6331     return FullSet;
6332 
6333   unsigned TC = getSmallConstantMaxTripCount(L);
6334   if (!TC || TC >= BitWidth)
6335     return FullSet;
6336 
6337   auto KnownStart = computeKnownBits(Start, DL, 0, &AC, nullptr, &DT);
6338   auto KnownStep = computeKnownBits(Step, DL, 0, &AC, nullptr, &DT);
6339   assert(KnownStart.getBitWidth() == BitWidth &&
6340          KnownStep.getBitWidth() == BitWidth);
6341 
6342   // Compute total shift amount, being careful of overflow and bitwidths.
6343   auto MaxShiftAmt = KnownStep.getMaxValue();
6344   APInt TCAP(BitWidth, TC-1);
6345   bool Overflow = false;
6346   auto TotalShift = MaxShiftAmt.umul_ov(TCAP, Overflow);
6347   if (Overflow)
6348     return FullSet;
6349 
6350   switch (BO->getOpcode()) {
6351   default:
6352     llvm_unreachable("filtered out above");
6353   case Instruction::AShr: {
6354     // For each ashr, three cases:
6355     //   shift = 0 => unchanged value
6356     //   saturation => 0 or -1
6357     //   other => a value closer to zero (of the same sign)
6358     // Thus, the end value is closer to zero than the start.
6359     auto KnownEnd = KnownBits::ashr(KnownStart,
6360                                     KnownBits::makeConstant(TotalShift));
6361     if (KnownStart.isNonNegative())
6362       // Analogous to lshr (simply not yet canonicalized)
6363       return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
6364                                         KnownStart.getMaxValue() + 1);
6365     if (KnownStart.isNegative())
6366       // End >=u Start && End <=s Start
6367       return ConstantRange::getNonEmpty(KnownStart.getMinValue(),
6368                                         KnownEnd.getMaxValue() + 1);
6369     break;
6370   }
6371   case Instruction::LShr: {
6372     // For each lshr, three cases:
6373     //   shift = 0 => unchanged value
6374     //   saturation => 0
6375     //   other => a smaller positive number
6376     // Thus, the low end of the unsigned range is the last value produced.
6377     auto KnownEnd = KnownBits::lshr(KnownStart,
6378                                     KnownBits::makeConstant(TotalShift));
6379     return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
6380                                       KnownStart.getMaxValue() + 1);
6381   }
6382   case Instruction::Shl: {
6383     // Iff no bits are shifted out, value increases on every shift.
6384     auto KnownEnd = KnownBits::shl(KnownStart,
6385                                    KnownBits::makeConstant(TotalShift));
6386     if (TotalShift.ult(KnownStart.countMinLeadingZeros()))
6387       return ConstantRange(KnownStart.getMinValue(),
6388                            KnownEnd.getMaxValue() + 1);
6389     break;
6390   }
6391   };
6392   return FullSet;
6393 }
6394 
6395 /// Determine the range for a particular SCEV.  If SignHint is
6396 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
6397 /// with a "cleaner" unsigned (resp. signed) representation.
6398 const ConstantRange &
6399 ScalarEvolution::getRangeRef(const SCEV *S,
6400                              ScalarEvolution::RangeSignHint SignHint) {
6401   DenseMap<const SCEV *, ConstantRange> &Cache =
6402       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
6403                                                        : SignedRanges;
6404   ConstantRange::PreferredRangeType RangeType =
6405       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED
6406           ? ConstantRange::Unsigned : ConstantRange::Signed;
6407 
6408   // See if we've computed this range already.
6409   DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
6410   if (I != Cache.end())
6411     return I->second;
6412 
6413   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
6414     return setRange(C, SignHint, ConstantRange(C->getAPInt()));
6415 
6416   unsigned BitWidth = getTypeSizeInBits(S->getType());
6417   ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
6418   using OBO = OverflowingBinaryOperator;
6419 
6420   // If the value has known zeros, the maximum value will have those known zeros
6421   // as well.
6422   uint32_t TZ = GetMinTrailingZeros(S);
6423   if (TZ != 0) {
6424     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
6425       ConservativeResult =
6426           ConstantRange(APInt::getMinValue(BitWidth),
6427                         APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
6428     else
6429       ConservativeResult = ConstantRange(
6430           APInt::getSignedMinValue(BitWidth),
6431           APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
6432   }
6433 
6434   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
6435     ConstantRange X = getRangeRef(Add->getOperand(0), SignHint);
6436     unsigned WrapType = OBO::AnyWrap;
6437     if (Add->hasNoSignedWrap())
6438       WrapType |= OBO::NoSignedWrap;
6439     if (Add->hasNoUnsignedWrap())
6440       WrapType |= OBO::NoUnsignedWrap;
6441     for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
6442       X = X.addWithNoWrap(getRangeRef(Add->getOperand(i), SignHint),
6443                           WrapType, RangeType);
6444     return setRange(Add, SignHint,
6445                     ConservativeResult.intersectWith(X, RangeType));
6446   }
6447 
6448   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
6449     ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint);
6450     for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
6451       X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint));
6452     return setRange(Mul, SignHint,
6453                     ConservativeResult.intersectWith(X, RangeType));
6454   }
6455 
6456   if (isa<SCEVMinMaxExpr>(S) || isa<SCEVSequentialMinMaxExpr>(S)) {
6457     Intrinsic::ID ID;
6458     switch (S->getSCEVType()) {
6459     case scUMaxExpr:
6460       ID = Intrinsic::umax;
6461       break;
6462     case scSMaxExpr:
6463       ID = Intrinsic::smax;
6464       break;
6465     case scUMinExpr:
6466     case scSequentialUMinExpr:
6467       ID = Intrinsic::umin;
6468       break;
6469     case scSMinExpr:
6470       ID = Intrinsic::smin;
6471       break;
6472     default:
6473       llvm_unreachable("Unknown SCEVMinMaxExpr/SCEVSequentialMinMaxExpr.");
6474     }
6475 
6476     const auto *NAry = cast<SCEVNAryExpr>(S);
6477     ConstantRange X = getRangeRef(NAry->getOperand(0), SignHint);
6478     for (unsigned i = 1, e = NAry->getNumOperands(); i != e; ++i)
6479       X = X.intrinsic(ID, {X, getRangeRef(NAry->getOperand(i), SignHint)});
6480     return setRange(S, SignHint,
6481                     ConservativeResult.intersectWith(X, RangeType));
6482   }
6483 
6484   if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
6485     ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint);
6486     ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint);
6487     return setRange(UDiv, SignHint,
6488                     ConservativeResult.intersectWith(X.udiv(Y), RangeType));
6489   }
6490 
6491   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
6492     ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint);
6493     return setRange(ZExt, SignHint,
6494                     ConservativeResult.intersectWith(X.zeroExtend(BitWidth),
6495                                                      RangeType));
6496   }
6497 
6498   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
6499     ConstantRange X = getRangeRef(SExt->getOperand(), SignHint);
6500     return setRange(SExt, SignHint,
6501                     ConservativeResult.intersectWith(X.signExtend(BitWidth),
6502                                                      RangeType));
6503   }
6504 
6505   if (const SCEVPtrToIntExpr *PtrToInt = dyn_cast<SCEVPtrToIntExpr>(S)) {
6506     ConstantRange X = getRangeRef(PtrToInt->getOperand(), SignHint);
6507     return setRange(PtrToInt, SignHint, X);
6508   }
6509 
6510   if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
6511     ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint);
6512     return setRange(Trunc, SignHint,
6513                     ConservativeResult.intersectWith(X.truncate(BitWidth),
6514                                                      RangeType));
6515   }
6516 
6517   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
6518     // If there's no unsigned wrap, the value will never be less than its
6519     // initial value.
6520     if (AddRec->hasNoUnsignedWrap()) {
6521       APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart());
6522       if (!UnsignedMinValue.isZero())
6523         ConservativeResult = ConservativeResult.intersectWith(
6524             ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType);
6525     }
6526 
6527     // If there's no signed wrap, and all the operands except initial value have
6528     // the same sign or zero, the value won't ever be:
6529     // 1: smaller than initial value if operands are non negative,
6530     // 2: bigger than initial value if operands are non positive.
6531     // For both cases, value can not cross signed min/max boundary.
6532     if (AddRec->hasNoSignedWrap()) {
6533       bool AllNonNeg = true;
6534       bool AllNonPos = true;
6535       for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) {
6536         if (!isKnownNonNegative(AddRec->getOperand(i)))
6537           AllNonNeg = false;
6538         if (!isKnownNonPositive(AddRec->getOperand(i)))
6539           AllNonPos = false;
6540       }
6541       if (AllNonNeg)
6542         ConservativeResult = ConservativeResult.intersectWith(
6543             ConstantRange::getNonEmpty(getSignedRangeMin(AddRec->getStart()),
6544                                        APInt::getSignedMinValue(BitWidth)),
6545             RangeType);
6546       else if (AllNonPos)
6547         ConservativeResult = ConservativeResult.intersectWith(
6548             ConstantRange::getNonEmpty(
6549                 APInt::getSignedMinValue(BitWidth),
6550                 getSignedRangeMax(AddRec->getStart()) + 1),
6551             RangeType);
6552     }
6553 
6554     // TODO: non-affine addrec
6555     if (AddRec->isAffine()) {
6556       const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(AddRec->getLoop());
6557       if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
6558           getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
6559         auto RangeFromAffine = getRangeForAffineAR(
6560             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
6561             BitWidth);
6562         ConservativeResult =
6563             ConservativeResult.intersectWith(RangeFromAffine, RangeType);
6564 
6565         auto RangeFromFactoring = getRangeViaFactoring(
6566             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
6567             BitWidth);
6568         ConservativeResult =
6569             ConservativeResult.intersectWith(RangeFromFactoring, RangeType);
6570       }
6571 
6572       // Now try symbolic BE count and more powerful methods.
6573       if (UseExpensiveRangeSharpening) {
6574         const SCEV *SymbolicMaxBECount =
6575             getSymbolicMaxBackedgeTakenCount(AddRec->getLoop());
6576         if (!isa<SCEVCouldNotCompute>(SymbolicMaxBECount) &&
6577             getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
6578             AddRec->hasNoSelfWrap()) {
6579           auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR(
6580               AddRec, SymbolicMaxBECount, BitWidth, SignHint);
6581           ConservativeResult =
6582               ConservativeResult.intersectWith(RangeFromAffineNew, RangeType);
6583         }
6584       }
6585     }
6586 
6587     return setRange(AddRec, SignHint, std::move(ConservativeResult));
6588   }
6589 
6590   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
6591 
6592     // Check if the IR explicitly contains !range metadata.
6593     Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
6594     if (MDRange.hasValue())
6595       ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue(),
6596                                                             RangeType);
6597 
6598     // Use facts about recurrences in the underlying IR.  Note that add
6599     // recurrences are AddRecExprs and thus don't hit this path.  This
6600     // primarily handles shift recurrences.
6601     auto CR = getRangeForUnknownRecurrence(U);
6602     ConservativeResult = ConservativeResult.intersectWith(CR);
6603 
6604     // See if ValueTracking can give us a useful range.
6605     const DataLayout &DL = getDataLayout();
6606     KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
6607     if (Known.getBitWidth() != BitWidth)
6608       Known = Known.zextOrTrunc(BitWidth);
6609 
6610     // ValueTracking may be able to compute a tighter result for the number of
6611     // sign bits than for the value of those sign bits.
6612     unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
6613     if (U->getType()->isPointerTy()) {
6614       // If the pointer size is larger than the index size type, this can cause
6615       // NS to be larger than BitWidth. So compensate for this.
6616       unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType());
6617       int ptrIdxDiff = ptrSize - BitWidth;
6618       if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff)
6619         NS -= ptrIdxDiff;
6620     }
6621 
6622     if (NS > 1) {
6623       // If we know any of the sign bits, we know all of the sign bits.
6624       if (!Known.Zero.getHiBits(NS).isZero())
6625         Known.Zero.setHighBits(NS);
6626       if (!Known.One.getHiBits(NS).isZero())
6627         Known.One.setHighBits(NS);
6628     }
6629 
6630     if (Known.getMinValue() != Known.getMaxValue() + 1)
6631       ConservativeResult = ConservativeResult.intersectWith(
6632           ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1),
6633           RangeType);
6634     if (NS > 1)
6635       ConservativeResult = ConservativeResult.intersectWith(
6636           ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
6637                         APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1),
6638           RangeType);
6639 
6640     // A range of Phi is a subset of union of all ranges of its input.
6641     if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) {
6642       // Make sure that we do not run over cycled Phis.
6643       if (PendingPhiRanges.insert(Phi).second) {
6644         ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false);
6645         for (auto &Op : Phi->operands()) {
6646           auto OpRange = getRangeRef(getSCEV(Op), SignHint);
6647           RangeFromOps = RangeFromOps.unionWith(OpRange);
6648           // No point to continue if we already have a full set.
6649           if (RangeFromOps.isFullSet())
6650             break;
6651         }
6652         ConservativeResult =
6653             ConservativeResult.intersectWith(RangeFromOps, RangeType);
6654         bool Erased = PendingPhiRanges.erase(Phi);
6655         assert(Erased && "Failed to erase Phi properly?");
6656         (void) Erased;
6657       }
6658     }
6659 
6660     return setRange(U, SignHint, std::move(ConservativeResult));
6661   }
6662 
6663   return setRange(S, SignHint, std::move(ConservativeResult));
6664 }
6665 
6666 // Given a StartRange, Step and MaxBECount for an expression compute a range of
6667 // values that the expression can take. Initially, the expression has a value
6668 // from StartRange and then is changed by Step up to MaxBECount times. Signed
6669 // argument defines if we treat Step as signed or unsigned.
6670 static ConstantRange getRangeForAffineARHelper(APInt Step,
6671                                                const ConstantRange &StartRange,
6672                                                const APInt &MaxBECount,
6673                                                unsigned BitWidth, bool Signed) {
6674   // If either Step or MaxBECount is 0, then the expression won't change, and we
6675   // just need to return the initial range.
6676   if (Step == 0 || MaxBECount == 0)
6677     return StartRange;
6678 
6679   // If we don't know anything about the initial value (i.e. StartRange is
6680   // FullRange), then we don't know anything about the final range either.
6681   // Return FullRange.
6682   if (StartRange.isFullSet())
6683     return ConstantRange::getFull(BitWidth);
6684 
6685   // If Step is signed and negative, then we use its absolute value, but we also
6686   // note that we're moving in the opposite direction.
6687   bool Descending = Signed && Step.isNegative();
6688 
6689   if (Signed)
6690     // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
6691     // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
6692     // This equations hold true due to the well-defined wrap-around behavior of
6693     // APInt.
6694     Step = Step.abs();
6695 
6696   // Check if Offset is more than full span of BitWidth. If it is, the
6697   // expression is guaranteed to overflow.
6698   if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
6699     return ConstantRange::getFull(BitWidth);
6700 
6701   // Offset is by how much the expression can change. Checks above guarantee no
6702   // overflow here.
6703   APInt Offset = Step * MaxBECount;
6704 
6705   // Minimum value of the final range will match the minimal value of StartRange
6706   // if the expression is increasing and will be decreased by Offset otherwise.
6707   // Maximum value of the final range will match the maximal value of StartRange
6708   // if the expression is decreasing and will be increased by Offset otherwise.
6709   APInt StartLower = StartRange.getLower();
6710   APInt StartUpper = StartRange.getUpper() - 1;
6711   APInt MovedBoundary = Descending ? (StartLower - std::move(Offset))
6712                                    : (StartUpper + std::move(Offset));
6713 
6714   // It's possible that the new minimum/maximum value will fall into the initial
6715   // range (due to wrap around). This means that the expression can take any
6716   // value in this bitwidth, and we have to return full range.
6717   if (StartRange.contains(MovedBoundary))
6718     return ConstantRange::getFull(BitWidth);
6719 
6720   APInt NewLower =
6721       Descending ? std::move(MovedBoundary) : std::move(StartLower);
6722   APInt NewUpper =
6723       Descending ? std::move(StartUpper) : std::move(MovedBoundary);
6724   NewUpper += 1;
6725 
6726   // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
6727   return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper));
6728 }
6729 
6730 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
6731                                                    const SCEV *Step,
6732                                                    const SCEV *MaxBECount,
6733                                                    unsigned BitWidth) {
6734   assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&
6735          getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
6736          "Precondition!");
6737 
6738   MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType());
6739   APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount);
6740 
6741   // First, consider step signed.
6742   ConstantRange StartSRange = getSignedRange(Start);
6743   ConstantRange StepSRange = getSignedRange(Step);
6744 
6745   // If Step can be both positive and negative, we need to find ranges for the
6746   // maximum absolute step values in both directions and union them.
6747   ConstantRange SR =
6748       getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange,
6749                                 MaxBECountValue, BitWidth, /* Signed = */ true);
6750   SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(),
6751                                               StartSRange, MaxBECountValue,
6752                                               BitWidth, /* Signed = */ true));
6753 
6754   // Next, consider step unsigned.
6755   ConstantRange UR = getRangeForAffineARHelper(
6756       getUnsignedRangeMax(Step), getUnsignedRange(Start),
6757       MaxBECountValue, BitWidth, /* Signed = */ false);
6758 
6759   // Finally, intersect signed and unsigned ranges.
6760   return SR.intersectWith(UR, ConstantRange::Smallest);
6761 }
6762 
6763 ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR(
6764     const SCEVAddRecExpr *AddRec, const SCEV *MaxBECount, unsigned BitWidth,
6765     ScalarEvolution::RangeSignHint SignHint) {
6766   assert(AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n");
6767   assert(AddRec->hasNoSelfWrap() &&
6768          "This only works for non-self-wrapping AddRecs!");
6769   const bool IsSigned = SignHint == HINT_RANGE_SIGNED;
6770   const SCEV *Step = AddRec->getStepRecurrence(*this);
6771   // Only deal with constant step to save compile time.
6772   if (!isa<SCEVConstant>(Step))
6773     return ConstantRange::getFull(BitWidth);
6774   // Let's make sure that we can prove that we do not self-wrap during
6775   // MaxBECount iterations. We need this because MaxBECount is a maximum
6776   // iteration count estimate, and we might infer nw from some exit for which we
6777   // do not know max exit count (or any other side reasoning).
6778   // TODO: Turn into assert at some point.
6779   if (getTypeSizeInBits(MaxBECount->getType()) >
6780       getTypeSizeInBits(AddRec->getType()))
6781     return ConstantRange::getFull(BitWidth);
6782   MaxBECount = getNoopOrZeroExtend(MaxBECount, AddRec->getType());
6783   const SCEV *RangeWidth = getMinusOne(AddRec->getType());
6784   const SCEV *StepAbs = getUMinExpr(Step, getNegativeSCEV(Step));
6785   const SCEV *MaxItersWithoutWrap = getUDivExpr(RangeWidth, StepAbs);
6786   if (!isKnownPredicateViaConstantRanges(ICmpInst::ICMP_ULE, MaxBECount,
6787                                          MaxItersWithoutWrap))
6788     return ConstantRange::getFull(BitWidth);
6789 
6790   ICmpInst::Predicate LEPred =
6791       IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
6792   ICmpInst::Predicate GEPred =
6793       IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
6794   const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
6795 
6796   // We know that there is no self-wrap. Let's take Start and End values and
6797   // look at all intermediate values V1, V2, ..., Vn that IndVar takes during
6798   // the iteration. They either lie inside the range [Min(Start, End),
6799   // Max(Start, End)] or outside it:
6800   //
6801   // Case 1:   RangeMin    ...    Start V1 ... VN End ...           RangeMax;
6802   // Case 2:   RangeMin Vk ... V1 Start    ...    End Vn ... Vk + 1 RangeMax;
6803   //
6804   // No self wrap flag guarantees that the intermediate values cannot be BOTH
6805   // outside and inside the range [Min(Start, End), Max(Start, End)]. Using that
6806   // knowledge, let's try to prove that we are dealing with Case 1. It is so if
6807   // Start <= End and step is positive, or Start >= End and step is negative.
6808   const SCEV *Start = AddRec->getStart();
6809   ConstantRange StartRange = getRangeRef(Start, SignHint);
6810   ConstantRange EndRange = getRangeRef(End, SignHint);
6811   ConstantRange RangeBetween = StartRange.unionWith(EndRange);
6812   // If they already cover full iteration space, we will know nothing useful
6813   // even if we prove what we want to prove.
6814   if (RangeBetween.isFullSet())
6815     return RangeBetween;
6816   // Only deal with ranges that do not wrap (i.e. RangeMin < RangeMax).
6817   bool IsWrappedSet = IsSigned ? RangeBetween.isSignWrappedSet()
6818                                : RangeBetween.isWrappedSet();
6819   if (IsWrappedSet)
6820     return ConstantRange::getFull(BitWidth);
6821 
6822   if (isKnownPositive(Step) &&
6823       isKnownPredicateViaConstantRanges(LEPred, Start, End))
6824     return RangeBetween;
6825   else if (isKnownNegative(Step) &&
6826            isKnownPredicateViaConstantRanges(GEPred, Start, End))
6827     return RangeBetween;
6828   return ConstantRange::getFull(BitWidth);
6829 }
6830 
6831 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
6832                                                     const SCEV *Step,
6833                                                     const SCEV *MaxBECount,
6834                                                     unsigned BitWidth) {
6835   //    RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
6836   // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
6837 
6838   struct SelectPattern {
6839     Value *Condition = nullptr;
6840     APInt TrueValue;
6841     APInt FalseValue;
6842 
6843     explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
6844                            const SCEV *S) {
6845       Optional<unsigned> CastOp;
6846       APInt Offset(BitWidth, 0);
6847 
6848       assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&
6849              "Should be!");
6850 
6851       // Peel off a constant offset:
6852       if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
6853         // In the future we could consider being smarter here and handle
6854         // {Start+Step,+,Step} too.
6855         if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
6856           return;
6857 
6858         Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
6859         S = SA->getOperand(1);
6860       }
6861 
6862       // Peel off a cast operation
6863       if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) {
6864         CastOp = SCast->getSCEVType();
6865         S = SCast->getOperand();
6866       }
6867 
6868       using namespace llvm::PatternMatch;
6869 
6870       auto *SU = dyn_cast<SCEVUnknown>(S);
6871       const APInt *TrueVal, *FalseVal;
6872       if (!SU ||
6873           !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
6874                                           m_APInt(FalseVal)))) {
6875         Condition = nullptr;
6876         return;
6877       }
6878 
6879       TrueValue = *TrueVal;
6880       FalseValue = *FalseVal;
6881 
6882       // Re-apply the cast we peeled off earlier
6883       if (CastOp.hasValue())
6884         switch (*CastOp) {
6885         default:
6886           llvm_unreachable("Unknown SCEV cast type!");
6887 
6888         case scTruncate:
6889           TrueValue = TrueValue.trunc(BitWidth);
6890           FalseValue = FalseValue.trunc(BitWidth);
6891           break;
6892         case scZeroExtend:
6893           TrueValue = TrueValue.zext(BitWidth);
6894           FalseValue = FalseValue.zext(BitWidth);
6895           break;
6896         case scSignExtend:
6897           TrueValue = TrueValue.sext(BitWidth);
6898           FalseValue = FalseValue.sext(BitWidth);
6899           break;
6900         }
6901 
6902       // Re-apply the constant offset we peeled off earlier
6903       TrueValue += Offset;
6904       FalseValue += Offset;
6905     }
6906 
6907     bool isRecognized() { return Condition != nullptr; }
6908   };
6909 
6910   SelectPattern StartPattern(*this, BitWidth, Start);
6911   if (!StartPattern.isRecognized())
6912     return ConstantRange::getFull(BitWidth);
6913 
6914   SelectPattern StepPattern(*this, BitWidth, Step);
6915   if (!StepPattern.isRecognized())
6916     return ConstantRange::getFull(BitWidth);
6917 
6918   if (StartPattern.Condition != StepPattern.Condition) {
6919     // We don't handle this case today; but we could, by considering four
6920     // possibilities below instead of two. I'm not sure if there are cases where
6921     // that will help over what getRange already does, though.
6922     return ConstantRange::getFull(BitWidth);
6923   }
6924 
6925   // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
6926   // construct arbitrary general SCEV expressions here.  This function is called
6927   // from deep in the call stack, and calling getSCEV (on a sext instruction,
6928   // say) can end up caching a suboptimal value.
6929 
6930   // FIXME: without the explicit `this` receiver below, MSVC errors out with
6931   // C2352 and C2512 (otherwise it isn't needed).
6932 
6933   const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
6934   const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
6935   const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
6936   const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
6937 
6938   ConstantRange TrueRange =
6939       this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
6940   ConstantRange FalseRange =
6941       this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
6942 
6943   return TrueRange.unionWith(FalseRange);
6944 }
6945 
6946 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
6947   if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
6948   const BinaryOperator *BinOp = cast<BinaryOperator>(V);
6949 
6950   // Return early if there are no flags to propagate to the SCEV.
6951   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
6952   if (BinOp->hasNoUnsignedWrap())
6953     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
6954   if (BinOp->hasNoSignedWrap())
6955     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
6956   if (Flags == SCEV::FlagAnyWrap)
6957     return SCEV::FlagAnyWrap;
6958 
6959   return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
6960 }
6961 
6962 const Instruction *
6963 ScalarEvolution::getNonTrivialDefiningScopeBound(const SCEV *S) {
6964   if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S))
6965     return &*AddRec->getLoop()->getHeader()->begin();
6966   if (auto *U = dyn_cast<SCEVUnknown>(S))
6967     if (auto *I = dyn_cast<Instruction>(U->getValue()))
6968       return I;
6969   return nullptr;
6970 }
6971 
6972 /// Fills \p Ops with unique operands of \p S, if it has operands. If not,
6973 /// \p Ops remains unmodified.
6974 static void collectUniqueOps(const SCEV *S,
6975                              SmallVectorImpl<const SCEV *> &Ops) {
6976   SmallPtrSet<const SCEV *, 4> Unique;
6977   auto InsertUnique = [&](const SCEV *S) {
6978     if (Unique.insert(S).second)
6979       Ops.push_back(S);
6980   };
6981   if (auto *S2 = dyn_cast<SCEVCastExpr>(S))
6982     for (auto *Op : S2->operands())
6983       InsertUnique(Op);
6984   else if (auto *S2 = dyn_cast<SCEVNAryExpr>(S))
6985     for (auto *Op : S2->operands())
6986       InsertUnique(Op);
6987   else if (auto *S2 = dyn_cast<SCEVUDivExpr>(S))
6988     for (auto *Op : S2->operands())
6989       InsertUnique(Op);
6990 }
6991 
6992 const Instruction *
6993 ScalarEvolution::getDefiningScopeBound(ArrayRef<const SCEV *> Ops,
6994                                        bool &Precise) {
6995   Precise = true;
6996   // Do a bounded search of the def relation of the requested SCEVs.
6997   SmallSet<const SCEV *, 16> Visited;
6998   SmallVector<const SCEV *> Worklist;
6999   auto pushOp = [&](const SCEV *S) {
7000     if (!Visited.insert(S).second)
7001       return;
7002     // Threshold of 30 here is arbitrary.
7003     if (Visited.size() > 30) {
7004       Precise = false;
7005       return;
7006     }
7007     Worklist.push_back(S);
7008   };
7009 
7010   for (auto *S : Ops)
7011     pushOp(S);
7012 
7013   const Instruction *Bound = nullptr;
7014   while (!Worklist.empty()) {
7015     auto *S = Worklist.pop_back_val();
7016     if (auto *DefI = getNonTrivialDefiningScopeBound(S)) {
7017       if (!Bound || DT.dominates(Bound, DefI))
7018         Bound = DefI;
7019     } else {
7020       SmallVector<const SCEV *, 4> Ops;
7021       collectUniqueOps(S, Ops);
7022       for (auto *Op : Ops)
7023         pushOp(Op);
7024     }
7025   }
7026   return Bound ? Bound : &*F.getEntryBlock().begin();
7027 }
7028 
7029 const Instruction *
7030 ScalarEvolution::getDefiningScopeBound(ArrayRef<const SCEV *> Ops) {
7031   bool Discard;
7032   return getDefiningScopeBound(Ops, Discard);
7033 }
7034 
7035 bool ScalarEvolution::isGuaranteedToTransferExecutionTo(const Instruction *A,
7036                                                         const Instruction *B) {
7037   if (A->getParent() == B->getParent() &&
7038       isGuaranteedToTransferExecutionToSuccessor(A->getIterator(),
7039                                                  B->getIterator()))
7040     return true;
7041 
7042   auto *BLoop = LI.getLoopFor(B->getParent());
7043   if (BLoop && BLoop->getHeader() == B->getParent() &&
7044       BLoop->getLoopPreheader() == A->getParent() &&
7045       isGuaranteedToTransferExecutionToSuccessor(A->getIterator(),
7046                                                  A->getParent()->end()) &&
7047       isGuaranteedToTransferExecutionToSuccessor(B->getParent()->begin(),
7048                                                  B->getIterator()))
7049     return true;
7050   return false;
7051 }
7052 
7053 
7054 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
7055   // Only proceed if we can prove that I does not yield poison.
7056   if (!programUndefinedIfPoison(I))
7057     return false;
7058 
7059   // At this point we know that if I is executed, then it does not wrap
7060   // according to at least one of NSW or NUW. If I is not executed, then we do
7061   // not know if the calculation that I represents would wrap. Multiple
7062   // instructions can map to the same SCEV. If we apply NSW or NUW from I to
7063   // the SCEV, we must guarantee no wrapping for that SCEV also when it is
7064   // derived from other instructions that map to the same SCEV. We cannot make
7065   // that guarantee for cases where I is not executed. So we need to find a
7066   // upper bound on the defining scope for the SCEV, and prove that I is
7067   // executed every time we enter that scope.  When the bounding scope is a
7068   // loop (the common case), this is equivalent to proving I executes on every
7069   // iteration of that loop.
7070   SmallVector<const SCEV *> SCEVOps;
7071   for (const Use &Op : I->operands()) {
7072     // I could be an extractvalue from a call to an overflow intrinsic.
7073     // TODO: We can do better here in some cases.
7074     if (isSCEVable(Op->getType()))
7075       SCEVOps.push_back(getSCEV(Op));
7076   }
7077   auto *DefI = getDefiningScopeBound(SCEVOps);
7078   return isGuaranteedToTransferExecutionTo(DefI, I);
7079 }
7080 
7081 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
7082   // If we know that \c I can never be poison period, then that's enough.
7083   if (isSCEVExprNeverPoison(I))
7084     return true;
7085 
7086   // For an add recurrence specifically, we assume that infinite loops without
7087   // side effects are undefined behavior, and then reason as follows:
7088   //
7089   // If the add recurrence is poison in any iteration, it is poison on all
7090   // future iterations (since incrementing poison yields poison). If the result
7091   // of the add recurrence is fed into the loop latch condition and the loop
7092   // does not contain any throws or exiting blocks other than the latch, we now
7093   // have the ability to "choose" whether the backedge is taken or not (by
7094   // choosing a sufficiently evil value for the poison feeding into the branch)
7095   // for every iteration including and after the one in which \p I first became
7096   // poison.  There are two possibilities (let's call the iteration in which \p
7097   // I first became poison as K):
7098   //
7099   //  1. In the set of iterations including and after K, the loop body executes
7100   //     no side effects.  In this case executing the backege an infinte number
7101   //     of times will yield undefined behavior.
7102   //
7103   //  2. In the set of iterations including and after K, the loop body executes
7104   //     at least one side effect.  In this case, that specific instance of side
7105   //     effect is control dependent on poison, which also yields undefined
7106   //     behavior.
7107 
7108   auto *ExitingBB = L->getExitingBlock();
7109   auto *LatchBB = L->getLoopLatch();
7110   if (!ExitingBB || !LatchBB || ExitingBB != LatchBB)
7111     return false;
7112 
7113   SmallPtrSet<const Instruction *, 16> Pushed;
7114   SmallVector<const Instruction *, 8> PoisonStack;
7115 
7116   // We start by assuming \c I, the post-inc add recurrence, is poison.  Only
7117   // things that are known to be poison under that assumption go on the
7118   // PoisonStack.
7119   Pushed.insert(I);
7120   PoisonStack.push_back(I);
7121 
7122   bool LatchControlDependentOnPoison = false;
7123   while (!PoisonStack.empty() && !LatchControlDependentOnPoison) {
7124     const Instruction *Poison = PoisonStack.pop_back_val();
7125 
7126     for (auto *PoisonUser : Poison->users()) {
7127       if (propagatesPoison(cast<Operator>(PoisonUser))) {
7128         if (Pushed.insert(cast<Instruction>(PoisonUser)).second)
7129           PoisonStack.push_back(cast<Instruction>(PoisonUser));
7130       } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) {
7131         assert(BI->isConditional() && "Only possibility!");
7132         if (BI->getParent() == LatchBB) {
7133           LatchControlDependentOnPoison = true;
7134           break;
7135         }
7136       }
7137     }
7138   }
7139 
7140   return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L);
7141 }
7142 
7143 ScalarEvolution::LoopProperties
7144 ScalarEvolution::getLoopProperties(const Loop *L) {
7145   using LoopProperties = ScalarEvolution::LoopProperties;
7146 
7147   auto Itr = LoopPropertiesCache.find(L);
7148   if (Itr == LoopPropertiesCache.end()) {
7149     auto HasSideEffects = [](Instruction *I) {
7150       if (auto *SI = dyn_cast<StoreInst>(I))
7151         return !SI->isSimple();
7152 
7153       return I->mayThrow() || I->mayWriteToMemory();
7154     };
7155 
7156     LoopProperties LP = {/* HasNoAbnormalExits */ true,
7157                          /*HasNoSideEffects*/ true};
7158 
7159     for (auto *BB : L->getBlocks())
7160       for (auto &I : *BB) {
7161         if (!isGuaranteedToTransferExecutionToSuccessor(&I))
7162           LP.HasNoAbnormalExits = false;
7163         if (HasSideEffects(&I))
7164           LP.HasNoSideEffects = false;
7165         if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
7166           break; // We're already as pessimistic as we can get.
7167       }
7168 
7169     auto InsertPair = LoopPropertiesCache.insert({L, LP});
7170     assert(InsertPair.second && "We just checked!");
7171     Itr = InsertPair.first;
7172   }
7173 
7174   return Itr->second;
7175 }
7176 
7177 bool ScalarEvolution::loopIsFiniteByAssumption(const Loop *L) {
7178   // A mustprogress loop without side effects must be finite.
7179   // TODO: The check used here is very conservative.  It's only *specific*
7180   // side effects which are well defined in infinite loops.
7181   return isFinite(L) || (isMustProgress(L) && loopHasNoSideEffects(L));
7182 }
7183 
7184 const SCEV *ScalarEvolution::createSCEV(Value *V) {
7185   if (!isSCEVable(V->getType()))
7186     return getUnknown(V);
7187 
7188   if (Instruction *I = dyn_cast<Instruction>(V)) {
7189     // Don't attempt to analyze instructions in blocks that aren't
7190     // reachable. Such instructions don't matter, and they aren't required
7191     // to obey basic rules for definitions dominating uses which this
7192     // analysis depends on.
7193     if (!DT.isReachableFromEntry(I->getParent()))
7194       return getUnknown(UndefValue::get(V->getType()));
7195   } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
7196     return getConstant(CI);
7197   else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
7198     return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee());
7199   else if (!isa<ConstantExpr>(V))
7200     return getUnknown(V);
7201 
7202   Operator *U = cast<Operator>(V);
7203   if (auto BO = MatchBinaryOp(U, DT)) {
7204     switch (BO->Opcode) {
7205     case Instruction::Add: {
7206       // The simple thing to do would be to just call getSCEV on both operands
7207       // and call getAddExpr with the result. However if we're looking at a
7208       // bunch of things all added together, this can be quite inefficient,
7209       // because it leads to N-1 getAddExpr calls for N ultimate operands.
7210       // Instead, gather up all the operands and make a single getAddExpr call.
7211       // LLVM IR canonical form means we need only traverse the left operands.
7212       SmallVector<const SCEV *, 4> AddOps;
7213       do {
7214         if (BO->Op) {
7215           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
7216             AddOps.push_back(OpSCEV);
7217             break;
7218           }
7219 
7220           // If a NUW or NSW flag can be applied to the SCEV for this
7221           // addition, then compute the SCEV for this addition by itself
7222           // with a separate call to getAddExpr. We need to do that
7223           // instead of pushing the operands of the addition onto AddOps,
7224           // since the flags are only known to apply to this particular
7225           // addition - they may not apply to other additions that can be
7226           // formed with operands from AddOps.
7227           const SCEV *RHS = getSCEV(BO->RHS);
7228           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
7229           if (Flags != SCEV::FlagAnyWrap) {
7230             const SCEV *LHS = getSCEV(BO->LHS);
7231             if (BO->Opcode == Instruction::Sub)
7232               AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
7233             else
7234               AddOps.push_back(getAddExpr(LHS, RHS, Flags));
7235             break;
7236           }
7237         }
7238 
7239         if (BO->Opcode == Instruction::Sub)
7240           AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
7241         else
7242           AddOps.push_back(getSCEV(BO->RHS));
7243 
7244         auto NewBO = MatchBinaryOp(BO->LHS, DT);
7245         if (!NewBO || (NewBO->Opcode != Instruction::Add &&
7246                        NewBO->Opcode != Instruction::Sub)) {
7247           AddOps.push_back(getSCEV(BO->LHS));
7248           break;
7249         }
7250         BO = NewBO;
7251       } while (true);
7252 
7253       return getAddExpr(AddOps);
7254     }
7255 
7256     case Instruction::Mul: {
7257       SmallVector<const SCEV *, 4> MulOps;
7258       do {
7259         if (BO->Op) {
7260           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
7261             MulOps.push_back(OpSCEV);
7262             break;
7263           }
7264 
7265           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
7266           if (Flags != SCEV::FlagAnyWrap) {
7267             MulOps.push_back(
7268                 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags));
7269             break;
7270           }
7271         }
7272 
7273         MulOps.push_back(getSCEV(BO->RHS));
7274         auto NewBO = MatchBinaryOp(BO->LHS, DT);
7275         if (!NewBO || NewBO->Opcode != Instruction::Mul) {
7276           MulOps.push_back(getSCEV(BO->LHS));
7277           break;
7278         }
7279         BO = NewBO;
7280       } while (true);
7281 
7282       return getMulExpr(MulOps);
7283     }
7284     case Instruction::UDiv:
7285       return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
7286     case Instruction::URem:
7287       return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
7288     case Instruction::Sub: {
7289       SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
7290       if (BO->Op)
7291         Flags = getNoWrapFlagsFromUB(BO->Op);
7292       return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags);
7293     }
7294     case Instruction::And:
7295       // For an expression like x&255 that merely masks off the high bits,
7296       // use zext(trunc(x)) as the SCEV expression.
7297       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
7298         if (CI->isZero())
7299           return getSCEV(BO->RHS);
7300         if (CI->isMinusOne())
7301           return getSCEV(BO->LHS);
7302         const APInt &A = CI->getValue();
7303 
7304         // Instcombine's ShrinkDemandedConstant may strip bits out of
7305         // constants, obscuring what would otherwise be a low-bits mask.
7306         // Use computeKnownBits to compute what ShrinkDemandedConstant
7307         // knew about to reconstruct a low-bits mask value.
7308         unsigned LZ = A.countLeadingZeros();
7309         unsigned TZ = A.countTrailingZeros();
7310         unsigned BitWidth = A.getBitWidth();
7311         KnownBits Known(BitWidth);
7312         computeKnownBits(BO->LHS, Known, getDataLayout(),
7313                          0, &AC, nullptr, &DT);
7314 
7315         APInt EffectiveMask =
7316             APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
7317         if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
7318           const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
7319           const SCEV *LHS = getSCEV(BO->LHS);
7320           const SCEV *ShiftedLHS = nullptr;
7321           if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
7322             if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
7323               // For an expression like (x * 8) & 8, simplify the multiply.
7324               unsigned MulZeros = OpC->getAPInt().countTrailingZeros();
7325               unsigned GCD = std::min(MulZeros, TZ);
7326               APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
7327               SmallVector<const SCEV*, 4> MulOps;
7328               MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD)));
7329               MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end());
7330               auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
7331               ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
7332             }
7333           }
7334           if (!ShiftedLHS)
7335             ShiftedLHS = getUDivExpr(LHS, MulCount);
7336           return getMulExpr(
7337               getZeroExtendExpr(
7338                   getTruncateExpr(ShiftedLHS,
7339                       IntegerType::get(getContext(), BitWidth - LZ - TZ)),
7340                   BO->LHS->getType()),
7341               MulCount);
7342         }
7343       }
7344       // Binary `and` is a bit-wise `umin`.
7345       if (BO->LHS->getType()->isIntegerTy(1))
7346         return getUMinExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
7347       break;
7348 
7349     case Instruction::Or:
7350       // If the RHS of the Or is a constant, we may have something like:
7351       // X*4+1 which got turned into X*4|1.  Handle this as an Add so loop
7352       // optimizations will transparently handle this case.
7353       //
7354       // In order for this transformation to be safe, the LHS must be of the
7355       // form X*(2^n) and the Or constant must be less than 2^n.
7356       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
7357         const SCEV *LHS = getSCEV(BO->LHS);
7358         const APInt &CIVal = CI->getValue();
7359         if (GetMinTrailingZeros(LHS) >=
7360             (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
7361           // Build a plain add SCEV.
7362           return getAddExpr(LHS, getSCEV(CI),
7363                             (SCEV::NoWrapFlags)(SCEV::FlagNUW | SCEV::FlagNSW));
7364         }
7365       }
7366       // Binary `or` is a bit-wise `umax`.
7367       if (BO->LHS->getType()->isIntegerTy(1))
7368         return getUMaxExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
7369       break;
7370 
7371     case Instruction::Xor:
7372       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
7373         // If the RHS of xor is -1, then this is a not operation.
7374         if (CI->isMinusOne())
7375           return getNotSCEV(getSCEV(BO->LHS));
7376 
7377         // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
7378         // This is a variant of the check for xor with -1, and it handles
7379         // the case where instcombine has trimmed non-demanded bits out
7380         // of an xor with -1.
7381         if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
7382           if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
7383             if (LBO->getOpcode() == Instruction::And &&
7384                 LCI->getValue() == CI->getValue())
7385               if (const SCEVZeroExtendExpr *Z =
7386                       dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
7387                 Type *UTy = BO->LHS->getType();
7388                 const SCEV *Z0 = Z->getOperand();
7389                 Type *Z0Ty = Z0->getType();
7390                 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
7391 
7392                 // If C is a low-bits mask, the zero extend is serving to
7393                 // mask off the high bits. Complement the operand and
7394                 // re-apply the zext.
7395                 if (CI->getValue().isMask(Z0TySize))
7396                   return getZeroExtendExpr(getNotSCEV(Z0), UTy);
7397 
7398                 // If C is a single bit, it may be in the sign-bit position
7399                 // before the zero-extend. In this case, represent the xor
7400                 // using an add, which is equivalent, and re-apply the zext.
7401                 APInt Trunc = CI->getValue().trunc(Z0TySize);
7402                 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
7403                     Trunc.isSignMask())
7404                   return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
7405                                            UTy);
7406               }
7407       }
7408       break;
7409 
7410     case Instruction::Shl:
7411       // Turn shift left of a constant amount into a multiply.
7412       if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
7413         uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
7414 
7415         // If the shift count is not less than the bitwidth, the result of
7416         // the shift is undefined. Don't try to analyze it, because the
7417         // resolution chosen here may differ from the resolution chosen in
7418         // other parts of the compiler.
7419         if (SA->getValue().uge(BitWidth))
7420           break;
7421 
7422         // We can safely preserve the nuw flag in all cases. It's also safe to
7423         // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation
7424         // requires special handling. It can be preserved as long as we're not
7425         // left shifting by bitwidth - 1.
7426         auto Flags = SCEV::FlagAnyWrap;
7427         if (BO->Op) {
7428           auto MulFlags = getNoWrapFlagsFromUB(BO->Op);
7429           if ((MulFlags & SCEV::FlagNSW) &&
7430               ((MulFlags & SCEV::FlagNUW) || SA->getValue().ult(BitWidth - 1)))
7431             Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNSW);
7432           if (MulFlags & SCEV::FlagNUW)
7433             Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNUW);
7434         }
7435 
7436         ConstantInt *X = ConstantInt::get(
7437             getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
7438         return getMulExpr(getSCEV(BO->LHS), getConstant(X), Flags);
7439       }
7440       break;
7441 
7442     case Instruction::AShr: {
7443       // AShr X, C, where C is a constant.
7444       ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
7445       if (!CI)
7446         break;
7447 
7448       Type *OuterTy = BO->LHS->getType();
7449       uint64_t BitWidth = getTypeSizeInBits(OuterTy);
7450       // If the shift count is not less than the bitwidth, the result of
7451       // the shift is undefined. Don't try to analyze it, because the
7452       // resolution chosen here may differ from the resolution chosen in
7453       // other parts of the compiler.
7454       if (CI->getValue().uge(BitWidth))
7455         break;
7456 
7457       if (CI->isZero())
7458         return getSCEV(BO->LHS); // shift by zero --> noop
7459 
7460       uint64_t AShrAmt = CI->getZExtValue();
7461       Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
7462 
7463       Operator *L = dyn_cast<Operator>(BO->LHS);
7464       if (L && L->getOpcode() == Instruction::Shl) {
7465         // X = Shl A, n
7466         // Y = AShr X, m
7467         // Both n and m are constant.
7468 
7469         const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
7470         if (L->getOperand(1) == BO->RHS)
7471           // For a two-shift sext-inreg, i.e. n = m,
7472           // use sext(trunc(x)) as the SCEV expression.
7473           return getSignExtendExpr(
7474               getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy);
7475 
7476         ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
7477         if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) {
7478           uint64_t ShlAmt = ShlAmtCI->getZExtValue();
7479           if (ShlAmt > AShrAmt) {
7480             // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
7481             // expression. We already checked that ShlAmt < BitWidth, so
7482             // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
7483             // ShlAmt - AShrAmt < Amt.
7484             APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
7485                                             ShlAmt - AShrAmt);
7486             return getSignExtendExpr(
7487                 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy),
7488                 getConstant(Mul)), OuterTy);
7489           }
7490         }
7491       }
7492       break;
7493     }
7494     }
7495   }
7496 
7497   switch (U->getOpcode()) {
7498   case Instruction::Trunc:
7499     return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
7500 
7501   case Instruction::ZExt:
7502     return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
7503 
7504   case Instruction::SExt:
7505     if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) {
7506       // The NSW flag of a subtract does not always survive the conversion to
7507       // A + (-1)*B.  By pushing sign extension onto its operands we are much
7508       // more likely to preserve NSW and allow later AddRec optimisations.
7509       //
7510       // NOTE: This is effectively duplicating this logic from getSignExtend:
7511       //   sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
7512       // but by that point the NSW information has potentially been lost.
7513       if (BO->Opcode == Instruction::Sub && BO->IsNSW) {
7514         Type *Ty = U->getType();
7515         auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty);
7516         auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty);
7517         return getMinusSCEV(V1, V2, SCEV::FlagNSW);
7518       }
7519     }
7520     return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
7521 
7522   case Instruction::BitCast:
7523     // BitCasts are no-op casts so we just eliminate the cast.
7524     if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
7525       return getSCEV(U->getOperand(0));
7526     break;
7527 
7528   case Instruction::PtrToInt: {
7529     // Pointer to integer cast is straight-forward, so do model it.
7530     const SCEV *Op = getSCEV(U->getOperand(0));
7531     Type *DstIntTy = U->getType();
7532     // But only if effective SCEV (integer) type is wide enough to represent
7533     // all possible pointer values.
7534     const SCEV *IntOp = getPtrToIntExpr(Op, DstIntTy);
7535     if (isa<SCEVCouldNotCompute>(IntOp))
7536       return getUnknown(V);
7537     return IntOp;
7538   }
7539   case Instruction::IntToPtr:
7540     // Just don't deal with inttoptr casts.
7541     return getUnknown(V);
7542 
7543   case Instruction::SDiv:
7544     // If both operands are non-negative, this is just an udiv.
7545     if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
7546         isKnownNonNegative(getSCEV(U->getOperand(1))))
7547       return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
7548     break;
7549 
7550   case Instruction::SRem:
7551     // If both operands are non-negative, this is just an urem.
7552     if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
7553         isKnownNonNegative(getSCEV(U->getOperand(1))))
7554       return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
7555     break;
7556 
7557   case Instruction::GetElementPtr:
7558     return createNodeForGEP(cast<GEPOperator>(U));
7559 
7560   case Instruction::PHI:
7561     return createNodeForPHI(cast<PHINode>(U));
7562 
7563   case Instruction::Select:
7564     return createNodeForSelectOrPHI(U, U->getOperand(0), U->getOperand(1),
7565                                     U->getOperand(2));
7566 
7567   case Instruction::Call:
7568   case Instruction::Invoke:
7569     if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand())
7570       return getSCEV(RV);
7571 
7572     if (auto *II = dyn_cast<IntrinsicInst>(U)) {
7573       switch (II->getIntrinsicID()) {
7574       case Intrinsic::abs:
7575         return getAbsExpr(
7576             getSCEV(II->getArgOperand(0)),
7577             /*IsNSW=*/cast<ConstantInt>(II->getArgOperand(1))->isOne());
7578       case Intrinsic::umax:
7579         return getUMaxExpr(getSCEV(II->getArgOperand(0)),
7580                            getSCEV(II->getArgOperand(1)));
7581       case Intrinsic::umin:
7582         return getUMinExpr(getSCEV(II->getArgOperand(0)),
7583                            getSCEV(II->getArgOperand(1)));
7584       case Intrinsic::smax:
7585         return getSMaxExpr(getSCEV(II->getArgOperand(0)),
7586                            getSCEV(II->getArgOperand(1)));
7587       case Intrinsic::smin:
7588         return getSMinExpr(getSCEV(II->getArgOperand(0)),
7589                            getSCEV(II->getArgOperand(1)));
7590       case Intrinsic::usub_sat: {
7591         const SCEV *X = getSCEV(II->getArgOperand(0));
7592         const SCEV *Y = getSCEV(II->getArgOperand(1));
7593         const SCEV *ClampedY = getUMinExpr(X, Y);
7594         return getMinusSCEV(X, ClampedY, SCEV::FlagNUW);
7595       }
7596       case Intrinsic::uadd_sat: {
7597         const SCEV *X = getSCEV(II->getArgOperand(0));
7598         const SCEV *Y = getSCEV(II->getArgOperand(1));
7599         const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y));
7600         return getAddExpr(ClampedX, Y, SCEV::FlagNUW);
7601       }
7602       case Intrinsic::start_loop_iterations:
7603         // A start_loop_iterations is just equivalent to the first operand for
7604         // SCEV purposes.
7605         return getSCEV(II->getArgOperand(0));
7606       default:
7607         break;
7608       }
7609     }
7610     break;
7611   }
7612 
7613   return getUnknown(V);
7614 }
7615 
7616 //===----------------------------------------------------------------------===//
7617 //                   Iteration Count Computation Code
7618 //
7619 
7620 const SCEV *ScalarEvolution::getTripCountFromExitCount(const SCEV *ExitCount,
7621                                                        bool Extend) {
7622   if (isa<SCEVCouldNotCompute>(ExitCount))
7623     return getCouldNotCompute();
7624 
7625   auto *ExitCountType = ExitCount->getType();
7626   assert(ExitCountType->isIntegerTy());
7627 
7628   if (!Extend)
7629     return getAddExpr(ExitCount, getOne(ExitCountType));
7630 
7631   auto *WiderType = Type::getIntNTy(ExitCountType->getContext(),
7632                                     1 + ExitCountType->getScalarSizeInBits());
7633   return getAddExpr(getNoopOrZeroExtend(ExitCount, WiderType),
7634                     getOne(WiderType));
7635 }
7636 
7637 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
7638   if (!ExitCount)
7639     return 0;
7640 
7641   ConstantInt *ExitConst = ExitCount->getValue();
7642 
7643   // Guard against huge trip counts.
7644   if (ExitConst->getValue().getActiveBits() > 32)
7645     return 0;
7646 
7647   // In case of integer overflow, this returns 0, which is correct.
7648   return ((unsigned)ExitConst->getZExtValue()) + 1;
7649 }
7650 
7651 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) {
7652   auto *ExitCount = dyn_cast<SCEVConstant>(getBackedgeTakenCount(L, Exact));
7653   return getConstantTripCount(ExitCount);
7654 }
7655 
7656 unsigned
7657 ScalarEvolution::getSmallConstantTripCount(const Loop *L,
7658                                            const BasicBlock *ExitingBlock) {
7659   assert(ExitingBlock && "Must pass a non-null exiting block!");
7660   assert(L->isLoopExiting(ExitingBlock) &&
7661          "Exiting block must actually branch out of the loop!");
7662   const SCEVConstant *ExitCount =
7663       dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
7664   return getConstantTripCount(ExitCount);
7665 }
7666 
7667 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) {
7668   const auto *MaxExitCount =
7669       dyn_cast<SCEVConstant>(getConstantMaxBackedgeTakenCount(L));
7670   return getConstantTripCount(MaxExitCount);
7671 }
7672 
7673 const SCEV *ScalarEvolution::getConstantMaxTripCountFromArray(const Loop *L) {
7674   // We can't infer from Array in Irregular Loop.
7675   // FIXME: It's hard to infer loop bound from array operated in Nested Loop.
7676   if (!L->isLoopSimplifyForm() || !L->isInnermost())
7677     return getCouldNotCompute();
7678 
7679   // FIXME: To make the scene more typical, we only analysis loops that have
7680   // one exiting block and that block must be the latch. To make it easier to
7681   // capture loops that have memory access and memory access will be executed
7682   // in each iteration.
7683   const BasicBlock *LoopLatch = L->getLoopLatch();
7684   assert(LoopLatch && "See defination of simplify form loop.");
7685   if (L->getExitingBlock() != LoopLatch)
7686     return getCouldNotCompute();
7687 
7688   const DataLayout &DL = getDataLayout();
7689   SmallVector<const SCEV *> InferCountColl;
7690   for (auto *BB : L->getBlocks()) {
7691     // Go here, we can know that Loop is a single exiting and simplified form
7692     // loop. Make sure that infer from Memory Operation in those BBs must be
7693     // executed in loop. First step, we can make sure that max execution time
7694     // of MemAccessBB in loop represents latch max excution time.
7695     // If MemAccessBB does not dom Latch, skip.
7696     //            Entry
7697     //              │
7698     //        ┌─────▼─────┐
7699     //        │Loop Header◄─────┐
7700     //        └──┬──────┬─┘     │
7701     //           │      │       │
7702     //  ┌────────▼──┐ ┌─▼─────┐ │
7703     //  │MemAccessBB│ │OtherBB│ │
7704     //  └────────┬──┘ └─┬─────┘ │
7705     //           │      │       │
7706     //         ┌─▼──────▼─┐     │
7707     //         │Loop Latch├─────┘
7708     //         └────┬─────┘
7709     //              ▼
7710     //             Exit
7711     if (!DT.dominates(BB, LoopLatch))
7712       continue;
7713 
7714     for (Instruction &Inst : *BB) {
7715       // Find Memory Operation Instruction.
7716       auto *GEP = getLoadStorePointerOperand(&Inst);
7717       if (!GEP)
7718         continue;
7719 
7720       auto *ElemSize = dyn_cast<SCEVConstant>(getElementSize(&Inst));
7721       // Do not infer from scalar type, eg."ElemSize = sizeof()".
7722       if (!ElemSize)
7723         continue;
7724 
7725       // Use a existing polynomial recurrence on the trip count.
7726       auto *AddRec = dyn_cast<SCEVAddRecExpr>(getSCEV(GEP));
7727       if (!AddRec)
7728         continue;
7729       auto *ArrBase = dyn_cast<SCEVUnknown>(getPointerBase(AddRec));
7730       auto *Step = dyn_cast<SCEVConstant>(AddRec->getStepRecurrence(*this));
7731       if (!ArrBase || !Step)
7732         continue;
7733       assert(isLoopInvariant(ArrBase, L) && "See addrec definition");
7734 
7735       // Only handle { %array + step },
7736       // FIXME: {(SCEVAddRecExpr) + step } could not be analysed here.
7737       if (AddRec->getStart() != ArrBase)
7738         continue;
7739 
7740       // Memory operation pattern which have gaps.
7741       // Or repeat memory opreation.
7742       // And index of GEP wraps arround.
7743       if (Step->getAPInt().getActiveBits() > 32 ||
7744           Step->getAPInt().getZExtValue() !=
7745               ElemSize->getAPInt().getZExtValue() ||
7746           Step->isZero() || Step->getAPInt().isNegative())
7747         continue;
7748 
7749       // Only infer from stack array which has certain size.
7750       // Make sure alloca instruction is not excuted in loop.
7751       AllocaInst *AllocateInst = dyn_cast<AllocaInst>(ArrBase->getValue());
7752       if (!AllocateInst || L->contains(AllocateInst->getParent()))
7753         continue;
7754 
7755       // Make sure only handle normal array.
7756       auto *Ty = dyn_cast<ArrayType>(AllocateInst->getAllocatedType());
7757       auto *ArrSize = dyn_cast<ConstantInt>(AllocateInst->getArraySize());
7758       if (!Ty || !ArrSize || !ArrSize->isOne())
7759         continue;
7760 
7761       // FIXME: Since gep indices are silently zext to the indexing type,
7762       // we will have a narrow gep index which wraps around rather than
7763       // increasing strictly, we shoule ensure that step is increasing
7764       // strictly by the loop iteration.
7765       // Now we can infer a max execution time by MemLength/StepLength.
7766       const SCEV *MemSize =
7767           getConstant(Step->getType(), DL.getTypeAllocSize(Ty));
7768       auto *MaxExeCount =
7769           dyn_cast<SCEVConstant>(getUDivCeilSCEV(MemSize, Step));
7770       if (!MaxExeCount || MaxExeCount->getAPInt().getActiveBits() > 32)
7771         continue;
7772 
7773       // If the loop reaches the maximum number of executions, we can not
7774       // access bytes starting outside the statically allocated size without
7775       // being immediate UB. But it is allowed to enter loop header one more
7776       // time.
7777       auto *InferCount = dyn_cast<SCEVConstant>(
7778           getAddExpr(MaxExeCount, getOne(MaxExeCount->getType())));
7779       // Discard the maximum number of execution times under 32bits.
7780       if (!InferCount || InferCount->getAPInt().getActiveBits() > 32)
7781         continue;
7782 
7783       InferCountColl.push_back(InferCount);
7784     }
7785   }
7786 
7787   if (InferCountColl.size() == 0)
7788     return getCouldNotCompute();
7789 
7790   return getUMinFromMismatchedTypes(InferCountColl);
7791 }
7792 
7793 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) {
7794   SmallVector<BasicBlock *, 8> ExitingBlocks;
7795   L->getExitingBlocks(ExitingBlocks);
7796 
7797   Optional<unsigned> Res = None;
7798   for (auto *ExitingBB : ExitingBlocks) {
7799     unsigned Multiple = getSmallConstantTripMultiple(L, ExitingBB);
7800     if (!Res)
7801       Res = Multiple;
7802     Res = (unsigned)GreatestCommonDivisor64(*Res, Multiple);
7803   }
7804   return Res.getValueOr(1);
7805 }
7806 
7807 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
7808                                                        const SCEV *ExitCount) {
7809   if (ExitCount == getCouldNotCompute())
7810     return 1;
7811 
7812   // Get the trip count
7813   const SCEV *TCExpr = getTripCountFromExitCount(ExitCount);
7814 
7815   const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr);
7816   if (!TC)
7817     // Attempt to factor more general cases. Returns the greatest power of
7818     // two divisor. If overflow happens, the trip count expression is still
7819     // divisible by the greatest power of 2 divisor returned.
7820     return 1U << std::min((uint32_t)31,
7821                           GetMinTrailingZeros(applyLoopGuards(TCExpr, L)));
7822 
7823   ConstantInt *Result = TC->getValue();
7824 
7825   // Guard against huge trip counts (this requires checking
7826   // for zero to handle the case where the trip count == -1 and the
7827   // addition wraps).
7828   if (!Result || Result->getValue().getActiveBits() > 32 ||
7829       Result->getValue().getActiveBits() == 0)
7830     return 1;
7831 
7832   return (unsigned)Result->getZExtValue();
7833 }
7834 
7835 /// Returns the largest constant divisor of the trip count of this loop as a
7836 /// normal unsigned value, if possible. This means that the actual trip count is
7837 /// always a multiple of the returned value (don't forget the trip count could
7838 /// very well be zero as well!).
7839 ///
7840 /// Returns 1 if the trip count is unknown or not guaranteed to be the
7841 /// multiple of a constant (which is also the case if the trip count is simply
7842 /// constant, use getSmallConstantTripCount for that case), Will also return 1
7843 /// if the trip count is very large (>= 2^32).
7844 ///
7845 /// As explained in the comments for getSmallConstantTripCount, this assumes
7846 /// that control exits the loop via ExitingBlock.
7847 unsigned
7848 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
7849                                               const BasicBlock *ExitingBlock) {
7850   assert(ExitingBlock && "Must pass a non-null exiting block!");
7851   assert(L->isLoopExiting(ExitingBlock) &&
7852          "Exiting block must actually branch out of the loop!");
7853   const SCEV *ExitCount = getExitCount(L, ExitingBlock);
7854   return getSmallConstantTripMultiple(L, ExitCount);
7855 }
7856 
7857 const SCEV *ScalarEvolution::getExitCount(const Loop *L,
7858                                           const BasicBlock *ExitingBlock,
7859                                           ExitCountKind Kind) {
7860   switch (Kind) {
7861   case Exact:
7862   case SymbolicMaximum:
7863     return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
7864   case ConstantMaximum:
7865     return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this);
7866   };
7867   llvm_unreachable("Invalid ExitCountKind!");
7868 }
7869 
7870 const SCEV *
7871 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
7872                                                  SmallVector<const SCEVPredicate *, 4> &Preds) {
7873   return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds);
7874 }
7875 
7876 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L,
7877                                                    ExitCountKind Kind) {
7878   switch (Kind) {
7879   case Exact:
7880     return getBackedgeTakenInfo(L).getExact(L, this);
7881   case ConstantMaximum:
7882     return getBackedgeTakenInfo(L).getConstantMax(this);
7883   case SymbolicMaximum:
7884     return getBackedgeTakenInfo(L).getSymbolicMax(L, this);
7885   };
7886   llvm_unreachable("Invalid ExitCountKind!");
7887 }
7888 
7889 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) {
7890   return getBackedgeTakenInfo(L).isConstantMaxOrZero(this);
7891 }
7892 
7893 /// Push PHI nodes in the header of the given loop onto the given Worklist.
7894 static void PushLoopPHIs(const Loop *L,
7895                          SmallVectorImpl<Instruction *> &Worklist,
7896                          SmallPtrSetImpl<Instruction *> &Visited) {
7897   BasicBlock *Header = L->getHeader();
7898 
7899   // Push all Loop-header PHIs onto the Worklist stack.
7900   for (PHINode &PN : Header->phis())
7901     if (Visited.insert(&PN).second)
7902       Worklist.push_back(&PN);
7903 }
7904 
7905 const ScalarEvolution::BackedgeTakenInfo &
7906 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
7907   auto &BTI = getBackedgeTakenInfo(L);
7908   if (BTI.hasFullInfo())
7909     return BTI;
7910 
7911   auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
7912 
7913   if (!Pair.second)
7914     return Pair.first->second;
7915 
7916   BackedgeTakenInfo Result =
7917       computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
7918 
7919   return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
7920 }
7921 
7922 ScalarEvolution::BackedgeTakenInfo &
7923 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
7924   // Initially insert an invalid entry for this loop. If the insertion
7925   // succeeds, proceed to actually compute a backedge-taken count and
7926   // update the value. The temporary CouldNotCompute value tells SCEV
7927   // code elsewhere that it shouldn't attempt to request a new
7928   // backedge-taken count, which could result in infinite recursion.
7929   std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
7930       BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
7931   if (!Pair.second)
7932     return Pair.first->second;
7933 
7934   // computeBackedgeTakenCount may allocate memory for its result. Inserting it
7935   // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
7936   // must be cleared in this scope.
7937   BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
7938 
7939   // In product build, there are no usage of statistic.
7940   (void)NumTripCountsComputed;
7941   (void)NumTripCountsNotComputed;
7942 #if LLVM_ENABLE_STATS || !defined(NDEBUG)
7943   const SCEV *BEExact = Result.getExact(L, this);
7944   if (BEExact != getCouldNotCompute()) {
7945     assert(isLoopInvariant(BEExact, L) &&
7946            isLoopInvariant(Result.getConstantMax(this), L) &&
7947            "Computed backedge-taken count isn't loop invariant for loop!");
7948     ++NumTripCountsComputed;
7949   } else if (Result.getConstantMax(this) == getCouldNotCompute() &&
7950              isa<PHINode>(L->getHeader()->begin())) {
7951     // Only count loops that have phi nodes as not being computable.
7952     ++NumTripCountsNotComputed;
7953   }
7954 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG)
7955 
7956   // Now that we know more about the trip count for this loop, forget any
7957   // existing SCEV values for PHI nodes in this loop since they are only
7958   // conservative estimates made without the benefit of trip count
7959   // information. This invalidation is not necessary for correctness, and is
7960   // only done to produce more precise results.
7961   if (Result.hasAnyInfo()) {
7962     // Invalidate any expression using an addrec in this loop.
7963     SmallVector<const SCEV *, 8> ToForget;
7964     auto LoopUsersIt = LoopUsers.find(L);
7965     if (LoopUsersIt != LoopUsers.end())
7966       append_range(ToForget, LoopUsersIt->second);
7967     forgetMemoizedResults(ToForget);
7968 
7969     // Invalidate constant-evolved loop header phis.
7970     for (PHINode &PN : L->getHeader()->phis())
7971       ConstantEvolutionLoopExitValue.erase(&PN);
7972   }
7973 
7974   // Re-lookup the insert position, since the call to
7975   // computeBackedgeTakenCount above could result in a
7976   // recusive call to getBackedgeTakenInfo (on a different
7977   // loop), which would invalidate the iterator computed
7978   // earlier.
7979   return BackedgeTakenCounts.find(L)->second = std::move(Result);
7980 }
7981 
7982 void ScalarEvolution::forgetAllLoops() {
7983   // This method is intended to forget all info about loops. It should
7984   // invalidate caches as if the following happened:
7985   // - The trip counts of all loops have changed arbitrarily
7986   // - Every llvm::Value has been updated in place to produce a different
7987   // result.
7988   BackedgeTakenCounts.clear();
7989   PredicatedBackedgeTakenCounts.clear();
7990   BECountUsers.clear();
7991   LoopPropertiesCache.clear();
7992   ConstantEvolutionLoopExitValue.clear();
7993   ValueExprMap.clear();
7994   ValuesAtScopes.clear();
7995   ValuesAtScopesUsers.clear();
7996   LoopDispositions.clear();
7997   BlockDispositions.clear();
7998   UnsignedRanges.clear();
7999   SignedRanges.clear();
8000   ExprValueMap.clear();
8001   HasRecMap.clear();
8002   MinTrailingZerosCache.clear();
8003   PredicatedSCEVRewrites.clear();
8004 }
8005 
8006 void ScalarEvolution::forgetLoop(const Loop *L) {
8007   SmallVector<const Loop *, 16> LoopWorklist(1, L);
8008   SmallVector<Instruction *, 32> Worklist;
8009   SmallPtrSet<Instruction *, 16> Visited;
8010   SmallVector<const SCEV *, 16> ToForget;
8011 
8012   // Iterate over all the loops and sub-loops to drop SCEV information.
8013   while (!LoopWorklist.empty()) {
8014     auto *CurrL = LoopWorklist.pop_back_val();
8015 
8016     // Drop any stored trip count value.
8017     forgetBackedgeTakenCounts(CurrL, /* Predicated */ false);
8018     forgetBackedgeTakenCounts(CurrL, /* Predicated */ true);
8019 
8020     // Drop information about predicated SCEV rewrites for this loop.
8021     for (auto I = PredicatedSCEVRewrites.begin();
8022          I != PredicatedSCEVRewrites.end();) {
8023       std::pair<const SCEV *, const Loop *> Entry = I->first;
8024       if (Entry.second == CurrL)
8025         PredicatedSCEVRewrites.erase(I++);
8026       else
8027         ++I;
8028     }
8029 
8030     auto LoopUsersItr = LoopUsers.find(CurrL);
8031     if (LoopUsersItr != LoopUsers.end()) {
8032       ToForget.insert(ToForget.end(), LoopUsersItr->second.begin(),
8033                 LoopUsersItr->second.end());
8034     }
8035 
8036     // Drop information about expressions based on loop-header PHIs.
8037     PushLoopPHIs(CurrL, Worklist, Visited);
8038 
8039     while (!Worklist.empty()) {
8040       Instruction *I = Worklist.pop_back_val();
8041 
8042       ValueExprMapType::iterator It =
8043           ValueExprMap.find_as(static_cast<Value *>(I));
8044       if (It != ValueExprMap.end()) {
8045         eraseValueFromMap(It->first);
8046         ToForget.push_back(It->second);
8047         if (PHINode *PN = dyn_cast<PHINode>(I))
8048           ConstantEvolutionLoopExitValue.erase(PN);
8049       }
8050 
8051       PushDefUseChildren(I, Worklist, Visited);
8052     }
8053 
8054     LoopPropertiesCache.erase(CurrL);
8055     // Forget all contained loops too, to avoid dangling entries in the
8056     // ValuesAtScopes map.
8057     LoopWorklist.append(CurrL->begin(), CurrL->end());
8058   }
8059   forgetMemoizedResults(ToForget);
8060 }
8061 
8062 void ScalarEvolution::forgetTopmostLoop(const Loop *L) {
8063   while (Loop *Parent = L->getParentLoop())
8064     L = Parent;
8065   forgetLoop(L);
8066 }
8067 
8068 void ScalarEvolution::forgetValue(Value *V) {
8069   Instruction *I = dyn_cast<Instruction>(V);
8070   if (!I) return;
8071 
8072   // Drop information about expressions based on loop-header PHIs.
8073   SmallVector<Instruction *, 16> Worklist;
8074   SmallPtrSet<Instruction *, 8> Visited;
8075   SmallVector<const SCEV *, 8> ToForget;
8076   Worklist.push_back(I);
8077   Visited.insert(I);
8078 
8079   while (!Worklist.empty()) {
8080     I = Worklist.pop_back_val();
8081     ValueExprMapType::iterator It =
8082       ValueExprMap.find_as(static_cast<Value *>(I));
8083     if (It != ValueExprMap.end()) {
8084       eraseValueFromMap(It->first);
8085       ToForget.push_back(It->second);
8086       if (PHINode *PN = dyn_cast<PHINode>(I))
8087         ConstantEvolutionLoopExitValue.erase(PN);
8088     }
8089 
8090     PushDefUseChildren(I, Worklist, Visited);
8091   }
8092   forgetMemoizedResults(ToForget);
8093 }
8094 
8095 void ScalarEvolution::forgetLoopDispositions(const Loop *L) {
8096   LoopDispositions.clear();
8097 }
8098 
8099 /// Get the exact loop backedge taken count considering all loop exits. A
8100 /// computable result can only be returned for loops with all exiting blocks
8101 /// dominating the latch. howFarToZero assumes that the limit of each loop test
8102 /// is never skipped. This is a valid assumption as long as the loop exits via
8103 /// that test. For precise results, it is the caller's responsibility to specify
8104 /// the relevant loop exiting block using getExact(ExitingBlock, SE).
8105 const SCEV *
8106 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE,
8107                                              SmallVector<const SCEVPredicate *, 4> *Preds) const {
8108   // If any exits were not computable, the loop is not computable.
8109   if (!isComplete() || ExitNotTaken.empty())
8110     return SE->getCouldNotCompute();
8111 
8112   const BasicBlock *Latch = L->getLoopLatch();
8113   // All exiting blocks we have collected must dominate the only backedge.
8114   if (!Latch)
8115     return SE->getCouldNotCompute();
8116 
8117   // All exiting blocks we have gathered dominate loop's latch, so exact trip
8118   // count is simply a minimum out of all these calculated exit counts.
8119   SmallVector<const SCEV *, 2> Ops;
8120   for (auto &ENT : ExitNotTaken) {
8121     const SCEV *BECount = ENT.ExactNotTaken;
8122     assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!");
8123     assert(SE->DT.dominates(ENT.ExitingBlock, Latch) &&
8124            "We should only have known counts for exiting blocks that dominate "
8125            "latch!");
8126 
8127     Ops.push_back(BECount);
8128 
8129     if (Preds)
8130       for (auto *P : ENT.Predicates)
8131         Preds->push_back(P);
8132 
8133     assert((Preds || ENT.hasAlwaysTruePredicate()) &&
8134            "Predicate should be always true!");
8135   }
8136 
8137   return SE->getUMinFromMismatchedTypes(Ops);
8138 }
8139 
8140 /// Get the exact not taken count for this loop exit.
8141 const SCEV *
8142 ScalarEvolution::BackedgeTakenInfo::getExact(const BasicBlock *ExitingBlock,
8143                                              ScalarEvolution *SE) const {
8144   for (auto &ENT : ExitNotTaken)
8145     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
8146       return ENT.ExactNotTaken;
8147 
8148   return SE->getCouldNotCompute();
8149 }
8150 
8151 const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax(
8152     const BasicBlock *ExitingBlock, ScalarEvolution *SE) const {
8153   for (auto &ENT : ExitNotTaken)
8154     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
8155       return ENT.MaxNotTaken;
8156 
8157   return SE->getCouldNotCompute();
8158 }
8159 
8160 /// getConstantMax - Get the constant max backedge taken count for the loop.
8161 const SCEV *
8162 ScalarEvolution::BackedgeTakenInfo::getConstantMax(ScalarEvolution *SE) const {
8163   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
8164     return !ENT.hasAlwaysTruePredicate();
8165   };
8166 
8167   if (!getConstantMax() || any_of(ExitNotTaken, PredicateNotAlwaysTrue))
8168     return SE->getCouldNotCompute();
8169 
8170   assert((isa<SCEVCouldNotCompute>(getConstantMax()) ||
8171           isa<SCEVConstant>(getConstantMax())) &&
8172          "No point in having a non-constant max backedge taken count!");
8173   return getConstantMax();
8174 }
8175 
8176 const SCEV *
8177 ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(const Loop *L,
8178                                                    ScalarEvolution *SE) {
8179   if (!SymbolicMax)
8180     SymbolicMax = SE->computeSymbolicMaxBackedgeTakenCount(L);
8181   return SymbolicMax;
8182 }
8183 
8184 bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero(
8185     ScalarEvolution *SE) const {
8186   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
8187     return !ENT.hasAlwaysTruePredicate();
8188   };
8189   return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
8190 }
8191 
8192 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E)
8193     : ExitLimit(E, E, false, None) {
8194 }
8195 
8196 ScalarEvolution::ExitLimit::ExitLimit(
8197     const SCEV *E, const SCEV *M, bool MaxOrZero,
8198     ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList)
8199     : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) {
8200   // If we prove the max count is zero, so is the symbolic bound.  This happens
8201   // in practice due to differences in a) how context sensitive we've chosen
8202   // to be and b) how we reason about bounds impied by UB.
8203   if (MaxNotTaken->isZero())
8204     ExactNotTaken = MaxNotTaken;
8205 
8206   assert((isa<SCEVCouldNotCompute>(ExactNotTaken) ||
8207           !isa<SCEVCouldNotCompute>(MaxNotTaken)) &&
8208          "Exact is not allowed to be less precise than Max");
8209   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
8210           isa<SCEVConstant>(MaxNotTaken)) &&
8211          "No point in having a non-constant max backedge taken count!");
8212   for (auto *PredSet : PredSetList)
8213     for (auto *P : *PredSet)
8214       addPredicate(P);
8215   assert((isa<SCEVCouldNotCompute>(E) || !E->getType()->isPointerTy()) &&
8216          "Backedge count should be int");
8217   assert((isa<SCEVCouldNotCompute>(M) || !M->getType()->isPointerTy()) &&
8218          "Max backedge count should be int");
8219 }
8220 
8221 ScalarEvolution::ExitLimit::ExitLimit(
8222     const SCEV *E, const SCEV *M, bool MaxOrZero,
8223     const SmallPtrSetImpl<const SCEVPredicate *> &PredSet)
8224     : ExitLimit(E, M, MaxOrZero, {&PredSet}) {
8225 }
8226 
8227 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M,
8228                                       bool MaxOrZero)
8229     : ExitLimit(E, M, MaxOrZero, None) {
8230 }
8231 
8232 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
8233 /// computable exit into a persistent ExitNotTakenInfo array.
8234 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
8235     ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> ExitCounts,
8236     bool IsComplete, const SCEV *ConstantMax, bool MaxOrZero)
8237     : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) {
8238   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
8239 
8240   ExitNotTaken.reserve(ExitCounts.size());
8241   std::transform(
8242       ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken),
8243       [&](const EdgeExitInfo &EEI) {
8244         BasicBlock *ExitBB = EEI.first;
8245         const ExitLimit &EL = EEI.second;
8246         return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken,
8247                                 EL.Predicates);
8248       });
8249   assert((isa<SCEVCouldNotCompute>(ConstantMax) ||
8250           isa<SCEVConstant>(ConstantMax)) &&
8251          "No point in having a non-constant max backedge taken count!");
8252 }
8253 
8254 /// Compute the number of times the backedge of the specified loop will execute.
8255 ScalarEvolution::BackedgeTakenInfo
8256 ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
8257                                            bool AllowPredicates) {
8258   SmallVector<BasicBlock *, 8> ExitingBlocks;
8259   L->getExitingBlocks(ExitingBlocks);
8260 
8261   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
8262 
8263   SmallVector<EdgeExitInfo, 4> ExitCounts;
8264   bool CouldComputeBECount = true;
8265   BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
8266   const SCEV *MustExitMaxBECount = nullptr;
8267   const SCEV *MayExitMaxBECount = nullptr;
8268   bool MustExitMaxOrZero = false;
8269 
8270   // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
8271   // and compute maxBECount.
8272   // Do a union of all the predicates here.
8273   for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
8274     BasicBlock *ExitBB = ExitingBlocks[i];
8275 
8276     // We canonicalize untaken exits to br (constant), ignore them so that
8277     // proving an exit untaken doesn't negatively impact our ability to reason
8278     // about the loop as whole.
8279     if (auto *BI = dyn_cast<BranchInst>(ExitBB->getTerminator()))
8280       if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
8281         bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
8282         if (ExitIfTrue == CI->isZero())
8283           continue;
8284       }
8285 
8286     ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
8287 
8288     assert((AllowPredicates || EL.Predicates.empty()) &&
8289            "Predicated exit limit when predicates are not allowed!");
8290 
8291     // 1. For each exit that can be computed, add an entry to ExitCounts.
8292     // CouldComputeBECount is true only if all exits can be computed.
8293     if (EL.ExactNotTaken == getCouldNotCompute())
8294       // We couldn't compute an exact value for this exit, so
8295       // we won't be able to compute an exact value for the loop.
8296       CouldComputeBECount = false;
8297     else
8298       ExitCounts.emplace_back(ExitBB, EL);
8299 
8300     // 2. Derive the loop's MaxBECount from each exit's max number of
8301     // non-exiting iterations. Partition the loop exits into two kinds:
8302     // LoopMustExits and LoopMayExits.
8303     //
8304     // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
8305     // is a LoopMayExit.  If any computable LoopMustExit is found, then
8306     // MaxBECount is the minimum EL.MaxNotTaken of computable
8307     // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
8308     // EL.MaxNotTaken, where CouldNotCompute is considered greater than any
8309     // computable EL.MaxNotTaken.
8310     if (EL.MaxNotTaken != getCouldNotCompute() && Latch &&
8311         DT.dominates(ExitBB, Latch)) {
8312       if (!MustExitMaxBECount) {
8313         MustExitMaxBECount = EL.MaxNotTaken;
8314         MustExitMaxOrZero = EL.MaxOrZero;
8315       } else {
8316         MustExitMaxBECount =
8317             getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken);
8318       }
8319     } else if (MayExitMaxBECount != getCouldNotCompute()) {
8320       if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute())
8321         MayExitMaxBECount = EL.MaxNotTaken;
8322       else {
8323         MayExitMaxBECount =
8324             getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken);
8325       }
8326     }
8327   }
8328   const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
8329     (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
8330   // The loop backedge will be taken the maximum or zero times if there's
8331   // a single exit that must be taken the maximum or zero times.
8332   bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
8333 
8334   // Remember which SCEVs are used in exit limits for invalidation purposes.
8335   // We only care about non-constant SCEVs here, so we can ignore EL.MaxNotTaken
8336   // and MaxBECount, which must be SCEVConstant.
8337   for (const auto &Pair : ExitCounts)
8338     if (!isa<SCEVConstant>(Pair.second.ExactNotTaken))
8339       BECountUsers[Pair.second.ExactNotTaken].insert({L, AllowPredicates});
8340   return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
8341                            MaxBECount, MaxOrZero);
8342 }
8343 
8344 ScalarEvolution::ExitLimit
8345 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
8346                                       bool AllowPredicates) {
8347   assert(L->contains(ExitingBlock) && "Exit count for non-loop block?");
8348   // If our exiting block does not dominate the latch, then its connection with
8349   // loop's exit limit may be far from trivial.
8350   const BasicBlock *Latch = L->getLoopLatch();
8351   if (!Latch || !DT.dominates(ExitingBlock, Latch))
8352     return getCouldNotCompute();
8353 
8354   bool IsOnlyExit = (L->getExitingBlock() != nullptr);
8355   Instruction *Term = ExitingBlock->getTerminator();
8356   if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
8357     assert(BI->isConditional() && "If unconditional, it can't be in loop!");
8358     bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
8359     assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) &&
8360            "It should have one successor in loop and one exit block!");
8361     // Proceed to the next level to examine the exit condition expression.
8362     return computeExitLimitFromCond(
8363         L, BI->getCondition(), ExitIfTrue,
8364         /*ControlsExit=*/IsOnlyExit, AllowPredicates);
8365   }
8366 
8367   if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) {
8368     // For switch, make sure that there is a single exit from the loop.
8369     BasicBlock *Exit = nullptr;
8370     for (auto *SBB : successors(ExitingBlock))
8371       if (!L->contains(SBB)) {
8372         if (Exit) // Multiple exit successors.
8373           return getCouldNotCompute();
8374         Exit = SBB;
8375       }
8376     assert(Exit && "Exiting block must have at least one exit");
8377     return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
8378                                                 /*ControlsExit=*/IsOnlyExit);
8379   }
8380 
8381   return getCouldNotCompute();
8382 }
8383 
8384 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond(
8385     const Loop *L, Value *ExitCond, bool ExitIfTrue,
8386     bool ControlsExit, bool AllowPredicates) {
8387   ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates);
8388   return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue,
8389                                         ControlsExit, AllowPredicates);
8390 }
8391 
8392 Optional<ScalarEvolution::ExitLimit>
8393 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
8394                                       bool ExitIfTrue, bool ControlsExit,
8395                                       bool AllowPredicates) {
8396   (void)this->L;
8397   (void)this->ExitIfTrue;
8398   (void)this->AllowPredicates;
8399 
8400   assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
8401          this->AllowPredicates == AllowPredicates &&
8402          "Variance in assumed invariant key components!");
8403   auto Itr = TripCountMap.find({ExitCond, ControlsExit});
8404   if (Itr == TripCountMap.end())
8405     return None;
8406   return Itr->second;
8407 }
8408 
8409 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
8410                                              bool ExitIfTrue,
8411                                              bool ControlsExit,
8412                                              bool AllowPredicates,
8413                                              const ExitLimit &EL) {
8414   assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
8415          this->AllowPredicates == AllowPredicates &&
8416          "Variance in assumed invariant key components!");
8417 
8418   auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL});
8419   assert(InsertResult.second && "Expected successful insertion!");
8420   (void)InsertResult;
8421   (void)ExitIfTrue;
8422 }
8423 
8424 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
8425     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
8426     bool ControlsExit, bool AllowPredicates) {
8427 
8428   if (auto MaybeEL =
8429           Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates))
8430     return *MaybeEL;
8431 
8432   ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue,
8433                                               ControlsExit, AllowPredicates);
8434   Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL);
8435   return EL;
8436 }
8437 
8438 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
8439     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
8440     bool ControlsExit, bool AllowPredicates) {
8441   // Handle BinOp conditions (And, Or).
8442   if (auto LimitFromBinOp = computeExitLimitFromCondFromBinOp(
8443           Cache, L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates))
8444     return *LimitFromBinOp;
8445 
8446   // With an icmp, it may be feasible to compute an exact backedge-taken count.
8447   // Proceed to the next level to examine the icmp.
8448   if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
8449     ExitLimit EL =
8450         computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit);
8451     if (EL.hasFullInfo() || !AllowPredicates)
8452       return EL;
8453 
8454     // Try again, but use SCEV predicates this time.
8455     return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit,
8456                                     /*AllowPredicates=*/true);
8457   }
8458 
8459   // Check for a constant condition. These are normally stripped out by
8460   // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
8461   // preserve the CFG and is temporarily leaving constant conditions
8462   // in place.
8463   if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
8464     if (ExitIfTrue == !CI->getZExtValue())
8465       // The backedge is always taken.
8466       return getCouldNotCompute();
8467     else
8468       // The backedge is never taken.
8469       return getZero(CI->getType());
8470   }
8471 
8472   // If we're exiting based on the overflow flag of an x.with.overflow intrinsic
8473   // with a constant step, we can form an equivalent icmp predicate and figure
8474   // out how many iterations will be taken before we exit.
8475   const WithOverflowInst *WO;
8476   const APInt *C;
8477   if (match(ExitCond, m_ExtractValue<1>(m_WithOverflowInst(WO))) &&
8478       match(WO->getRHS(), m_APInt(C))) {
8479     ConstantRange NWR =
8480       ConstantRange::makeExactNoWrapRegion(WO->getBinaryOp(), *C,
8481                                            WO->getNoWrapKind());
8482     CmpInst::Predicate Pred;
8483     APInt NewRHSC, Offset;
8484     NWR.getEquivalentICmp(Pred, NewRHSC, Offset);
8485     if (!ExitIfTrue)
8486       Pred = ICmpInst::getInversePredicate(Pred);
8487     auto *LHS = getSCEV(WO->getLHS());
8488     if (Offset != 0)
8489       LHS = getAddExpr(LHS, getConstant(Offset));
8490     auto EL = computeExitLimitFromICmp(L, Pred, LHS, getConstant(NewRHSC),
8491                                        ControlsExit, AllowPredicates);
8492     if (EL.hasAnyInfo()) return EL;
8493   }
8494 
8495   // If it's not an integer or pointer comparison then compute it the hard way.
8496   return computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
8497 }
8498 
8499 Optional<ScalarEvolution::ExitLimit>
8500 ScalarEvolution::computeExitLimitFromCondFromBinOp(
8501     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
8502     bool ControlsExit, bool AllowPredicates) {
8503   // Check if the controlling expression for this loop is an And or Or.
8504   Value *Op0, *Op1;
8505   bool IsAnd = false;
8506   if (match(ExitCond, m_LogicalAnd(m_Value(Op0), m_Value(Op1))))
8507     IsAnd = true;
8508   else if (match(ExitCond, m_LogicalOr(m_Value(Op0), m_Value(Op1))))
8509     IsAnd = false;
8510   else
8511     return None;
8512 
8513   // EitherMayExit is true in these two cases:
8514   //   br (and Op0 Op1), loop, exit
8515   //   br (or  Op0 Op1), exit, loop
8516   bool EitherMayExit = IsAnd ^ ExitIfTrue;
8517   ExitLimit EL0 = computeExitLimitFromCondCached(Cache, L, Op0, ExitIfTrue,
8518                                                  ControlsExit && !EitherMayExit,
8519                                                  AllowPredicates);
8520   ExitLimit EL1 = computeExitLimitFromCondCached(Cache, L, Op1, ExitIfTrue,
8521                                                  ControlsExit && !EitherMayExit,
8522                                                  AllowPredicates);
8523 
8524   // Be robust against unsimplified IR for the form "op i1 X, NeutralElement"
8525   const Constant *NeutralElement = ConstantInt::get(ExitCond->getType(), IsAnd);
8526   if (isa<ConstantInt>(Op1))
8527     return Op1 == NeutralElement ? EL0 : EL1;
8528   if (isa<ConstantInt>(Op0))
8529     return Op0 == NeutralElement ? EL1 : EL0;
8530 
8531   const SCEV *BECount = getCouldNotCompute();
8532   const SCEV *MaxBECount = getCouldNotCompute();
8533   if (EitherMayExit) {
8534     // Both conditions must be same for the loop to continue executing.
8535     // Choose the less conservative count.
8536     if (EL0.ExactNotTaken != getCouldNotCompute() &&
8537         EL1.ExactNotTaken != getCouldNotCompute()) {
8538       BECount = getUMinFromMismatchedTypes(
8539           EL0.ExactNotTaken, EL1.ExactNotTaken,
8540           /*Sequential=*/!isa<BinaryOperator>(ExitCond));
8541     }
8542     if (EL0.MaxNotTaken == getCouldNotCompute())
8543       MaxBECount = EL1.MaxNotTaken;
8544     else if (EL1.MaxNotTaken == getCouldNotCompute())
8545       MaxBECount = EL0.MaxNotTaken;
8546     else
8547       MaxBECount = getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
8548   } else {
8549     // Both conditions must be same at the same time for the loop to exit.
8550     // For now, be conservative.
8551     if (EL0.ExactNotTaken == EL1.ExactNotTaken)
8552       BECount = EL0.ExactNotTaken;
8553   }
8554 
8555   // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
8556   // to be more aggressive when computing BECount than when computing
8557   // MaxBECount.  In these cases it is possible for EL0.ExactNotTaken and
8558   // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
8559   // to not.
8560   if (isa<SCEVCouldNotCompute>(MaxBECount) &&
8561       !isa<SCEVCouldNotCompute>(BECount))
8562     MaxBECount = getConstant(getUnsignedRangeMax(BECount));
8563 
8564   return ExitLimit(BECount, MaxBECount, false,
8565                    { &EL0.Predicates, &EL1.Predicates });
8566 }
8567 
8568 ScalarEvolution::ExitLimit
8569 ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
8570                                           ICmpInst *ExitCond,
8571                                           bool ExitIfTrue,
8572                                           bool ControlsExit,
8573                                           bool AllowPredicates) {
8574   // If the condition was exit on true, convert the condition to exit on false
8575   ICmpInst::Predicate Pred;
8576   if (!ExitIfTrue)
8577     Pred = ExitCond->getPredicate();
8578   else
8579     Pred = ExitCond->getInversePredicate();
8580   const ICmpInst::Predicate OriginalPred = Pred;
8581 
8582   const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
8583   const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
8584 
8585   ExitLimit EL = computeExitLimitFromICmp(L, Pred, LHS, RHS, ControlsExit,
8586                                           AllowPredicates);
8587   if (EL.hasAnyInfo()) return EL;
8588 
8589   auto *ExhaustiveCount =
8590       computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
8591 
8592   if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
8593     return ExhaustiveCount;
8594 
8595   return computeShiftCompareExitLimit(ExitCond->getOperand(0),
8596                                       ExitCond->getOperand(1), L, OriginalPred);
8597 }
8598 ScalarEvolution::ExitLimit
8599 ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
8600                                           ICmpInst::Predicate Pred,
8601                                           const SCEV *LHS, const SCEV *RHS,
8602                                           bool ControlsExit,
8603                                           bool AllowPredicates) {
8604 
8605   // Try to evaluate any dependencies out of the loop.
8606   LHS = getSCEVAtScope(LHS, L);
8607   RHS = getSCEVAtScope(RHS, L);
8608 
8609   // At this point, we would like to compute how many iterations of the
8610   // loop the predicate will return true for these inputs.
8611   if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
8612     // If there is a loop-invariant, force it into the RHS.
8613     std::swap(LHS, RHS);
8614     Pred = ICmpInst::getSwappedPredicate(Pred);
8615   }
8616 
8617   bool ControllingFiniteLoop =
8618       ControlsExit && loopHasNoAbnormalExits(L) && loopIsFiniteByAssumption(L);
8619   // Simplify the operands before analyzing them.
8620   (void)SimplifyICmpOperands(Pred, LHS, RHS, /*Depth=*/0,
8621                              (EnableFiniteLoopControl ? ControllingFiniteLoop
8622                                                      : false));
8623 
8624   // If we have a comparison of a chrec against a constant, try to use value
8625   // ranges to answer this query.
8626   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
8627     if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
8628       if (AddRec->getLoop() == L) {
8629         // Form the constant range.
8630         ConstantRange CompRange =
8631             ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt());
8632 
8633         const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
8634         if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
8635       }
8636 
8637   // If this loop must exit based on this condition (or execute undefined
8638   // behaviour), and we can prove the test sequence produced must repeat
8639   // the same values on self-wrap of the IV, then we can infer that IV
8640   // doesn't self wrap because if it did, we'd have an infinite (undefined)
8641   // loop.
8642   if (ControllingFiniteLoop && isLoopInvariant(RHS, L)) {
8643     // TODO: We can peel off any functions which are invertible *in L*.  Loop
8644     // invariant terms are effectively constants for our purposes here.
8645     auto *InnerLHS = LHS;
8646     if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS))
8647       InnerLHS = ZExt->getOperand();
8648     if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(InnerLHS)) {
8649       auto *StrideC = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this));
8650       if (!AR->hasNoSelfWrap() && AR->getLoop() == L && AR->isAffine() &&
8651           StrideC && StrideC->getAPInt().isPowerOf2()) {
8652         auto Flags = AR->getNoWrapFlags();
8653         Flags = setFlags(Flags, SCEV::FlagNW);
8654         SmallVector<const SCEV*> Operands{AR->operands()};
8655         Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
8656         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
8657       }
8658     }
8659   }
8660 
8661   switch (Pred) {
8662   case ICmpInst::ICMP_NE: {                     // while (X != Y)
8663     // Convert to: while (X-Y != 0)
8664     if (LHS->getType()->isPointerTy()) {
8665       LHS = getLosslessPtrToIntExpr(LHS);
8666       if (isa<SCEVCouldNotCompute>(LHS))
8667         return LHS;
8668     }
8669     if (RHS->getType()->isPointerTy()) {
8670       RHS = getLosslessPtrToIntExpr(RHS);
8671       if (isa<SCEVCouldNotCompute>(RHS))
8672         return RHS;
8673     }
8674     ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit,
8675                                 AllowPredicates);
8676     if (EL.hasAnyInfo()) return EL;
8677     break;
8678   }
8679   case ICmpInst::ICMP_EQ: {                     // while (X == Y)
8680     // Convert to: while (X-Y == 0)
8681     if (LHS->getType()->isPointerTy()) {
8682       LHS = getLosslessPtrToIntExpr(LHS);
8683       if (isa<SCEVCouldNotCompute>(LHS))
8684         return LHS;
8685     }
8686     if (RHS->getType()->isPointerTy()) {
8687       RHS = getLosslessPtrToIntExpr(RHS);
8688       if (isa<SCEVCouldNotCompute>(RHS))
8689         return RHS;
8690     }
8691     ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
8692     if (EL.hasAnyInfo()) return EL;
8693     break;
8694   }
8695   case ICmpInst::ICMP_SLT:
8696   case ICmpInst::ICMP_ULT: {                    // while (X < Y)
8697     bool IsSigned = Pred == ICmpInst::ICMP_SLT;
8698     ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit,
8699                                     AllowPredicates);
8700     if (EL.hasAnyInfo()) return EL;
8701     break;
8702   }
8703   case ICmpInst::ICMP_SGT:
8704   case ICmpInst::ICMP_UGT: {                    // while (X > Y)
8705     bool IsSigned = Pred == ICmpInst::ICMP_SGT;
8706     ExitLimit EL =
8707         howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
8708                             AllowPredicates);
8709     if (EL.hasAnyInfo()) return EL;
8710     break;
8711   }
8712   default:
8713     break;
8714   }
8715 
8716   return getCouldNotCompute();
8717 }
8718 
8719 ScalarEvolution::ExitLimit
8720 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
8721                                                       SwitchInst *Switch,
8722                                                       BasicBlock *ExitingBlock,
8723                                                       bool ControlsExit) {
8724   assert(!L->contains(ExitingBlock) && "Not an exiting block!");
8725 
8726   // Give up if the exit is the default dest of a switch.
8727   if (Switch->getDefaultDest() == ExitingBlock)
8728     return getCouldNotCompute();
8729 
8730   assert(L->contains(Switch->getDefaultDest()) &&
8731          "Default case must not exit the loop!");
8732   const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
8733   const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
8734 
8735   // while (X != Y) --> while (X-Y != 0)
8736   ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
8737   if (EL.hasAnyInfo())
8738     return EL;
8739 
8740   return getCouldNotCompute();
8741 }
8742 
8743 static ConstantInt *
8744 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
8745                                 ScalarEvolution &SE) {
8746   const SCEV *InVal = SE.getConstant(C);
8747   const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
8748   assert(isa<SCEVConstant>(Val) &&
8749          "Evaluation of SCEV at constant didn't fold correctly?");
8750   return cast<SCEVConstant>(Val)->getValue();
8751 }
8752 
8753 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
8754     Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
8755   ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
8756   if (!RHS)
8757     return getCouldNotCompute();
8758 
8759   const BasicBlock *Latch = L->getLoopLatch();
8760   if (!Latch)
8761     return getCouldNotCompute();
8762 
8763   const BasicBlock *Predecessor = L->getLoopPredecessor();
8764   if (!Predecessor)
8765     return getCouldNotCompute();
8766 
8767   // Return true if V is of the form "LHS `shift_op` <positive constant>".
8768   // Return LHS in OutLHS and shift_opt in OutOpCode.
8769   auto MatchPositiveShift =
8770       [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
8771 
8772     using namespace PatternMatch;
8773 
8774     ConstantInt *ShiftAmt;
8775     if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
8776       OutOpCode = Instruction::LShr;
8777     else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
8778       OutOpCode = Instruction::AShr;
8779     else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
8780       OutOpCode = Instruction::Shl;
8781     else
8782       return false;
8783 
8784     return ShiftAmt->getValue().isStrictlyPositive();
8785   };
8786 
8787   // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
8788   //
8789   // loop:
8790   //   %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
8791   //   %iv.shifted = lshr i32 %iv, <positive constant>
8792   //
8793   // Return true on a successful match.  Return the corresponding PHI node (%iv
8794   // above) in PNOut and the opcode of the shift operation in OpCodeOut.
8795   auto MatchShiftRecurrence =
8796       [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
8797     Optional<Instruction::BinaryOps> PostShiftOpCode;
8798 
8799     {
8800       Instruction::BinaryOps OpC;
8801       Value *V;
8802 
8803       // If we encounter a shift instruction, "peel off" the shift operation,
8804       // and remember that we did so.  Later when we inspect %iv's backedge
8805       // value, we will make sure that the backedge value uses the same
8806       // operation.
8807       //
8808       // Note: the peeled shift operation does not have to be the same
8809       // instruction as the one feeding into the PHI's backedge value.  We only
8810       // really care about it being the same *kind* of shift instruction --
8811       // that's all that is required for our later inferences to hold.
8812       if (MatchPositiveShift(LHS, V, OpC)) {
8813         PostShiftOpCode = OpC;
8814         LHS = V;
8815       }
8816     }
8817 
8818     PNOut = dyn_cast<PHINode>(LHS);
8819     if (!PNOut || PNOut->getParent() != L->getHeader())
8820       return false;
8821 
8822     Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
8823     Value *OpLHS;
8824 
8825     return
8826         // The backedge value for the PHI node must be a shift by a positive
8827         // amount
8828         MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
8829 
8830         // of the PHI node itself
8831         OpLHS == PNOut &&
8832 
8833         // and the kind of shift should be match the kind of shift we peeled
8834         // off, if any.
8835         (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut);
8836   };
8837 
8838   PHINode *PN;
8839   Instruction::BinaryOps OpCode;
8840   if (!MatchShiftRecurrence(LHS, PN, OpCode))
8841     return getCouldNotCompute();
8842 
8843   const DataLayout &DL = getDataLayout();
8844 
8845   // The key rationale for this optimization is that for some kinds of shift
8846   // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
8847   // within a finite number of iterations.  If the condition guarding the
8848   // backedge (in the sense that the backedge is taken if the condition is true)
8849   // is false for the value the shift recurrence stabilizes to, then we know
8850   // that the backedge is taken only a finite number of times.
8851 
8852   ConstantInt *StableValue = nullptr;
8853   switch (OpCode) {
8854   default:
8855     llvm_unreachable("Impossible case!");
8856 
8857   case Instruction::AShr: {
8858     // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
8859     // bitwidth(K) iterations.
8860     Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
8861     KnownBits Known = computeKnownBits(FirstValue, DL, 0, &AC,
8862                                        Predecessor->getTerminator(), &DT);
8863     auto *Ty = cast<IntegerType>(RHS->getType());
8864     if (Known.isNonNegative())
8865       StableValue = ConstantInt::get(Ty, 0);
8866     else if (Known.isNegative())
8867       StableValue = ConstantInt::get(Ty, -1, true);
8868     else
8869       return getCouldNotCompute();
8870 
8871     break;
8872   }
8873   case Instruction::LShr:
8874   case Instruction::Shl:
8875     // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
8876     // stabilize to 0 in at most bitwidth(K) iterations.
8877     StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
8878     break;
8879   }
8880 
8881   auto *Result =
8882       ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
8883   assert(Result->getType()->isIntegerTy(1) &&
8884          "Otherwise cannot be an operand to a branch instruction");
8885 
8886   if (Result->isZeroValue()) {
8887     unsigned BitWidth = getTypeSizeInBits(RHS->getType());
8888     const SCEV *UpperBound =
8889         getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
8890     return ExitLimit(getCouldNotCompute(), UpperBound, false);
8891   }
8892 
8893   return getCouldNotCompute();
8894 }
8895 
8896 /// Return true if we can constant fold an instruction of the specified type,
8897 /// assuming that all operands were constants.
8898 static bool CanConstantFold(const Instruction *I) {
8899   if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
8900       isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
8901       isa<LoadInst>(I) || isa<ExtractValueInst>(I))
8902     return true;
8903 
8904   if (const CallInst *CI = dyn_cast<CallInst>(I))
8905     if (const Function *F = CI->getCalledFunction())
8906       return canConstantFoldCallTo(CI, F);
8907   return false;
8908 }
8909 
8910 /// Determine whether this instruction can constant evolve within this loop
8911 /// assuming its operands can all constant evolve.
8912 static bool canConstantEvolve(Instruction *I, const Loop *L) {
8913   // An instruction outside of the loop can't be derived from a loop PHI.
8914   if (!L->contains(I)) return false;
8915 
8916   if (isa<PHINode>(I)) {
8917     // We don't currently keep track of the control flow needed to evaluate
8918     // PHIs, so we cannot handle PHIs inside of loops.
8919     return L->getHeader() == I->getParent();
8920   }
8921 
8922   // If we won't be able to constant fold this expression even if the operands
8923   // are constants, bail early.
8924   return CanConstantFold(I);
8925 }
8926 
8927 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
8928 /// recursing through each instruction operand until reaching a loop header phi.
8929 static PHINode *
8930 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
8931                                DenseMap<Instruction *, PHINode *> &PHIMap,
8932                                unsigned Depth) {
8933   if (Depth > MaxConstantEvolvingDepth)
8934     return nullptr;
8935 
8936   // Otherwise, we can evaluate this instruction if all of its operands are
8937   // constant or derived from a PHI node themselves.
8938   PHINode *PHI = nullptr;
8939   for (Value *Op : UseInst->operands()) {
8940     if (isa<Constant>(Op)) continue;
8941 
8942     Instruction *OpInst = dyn_cast<Instruction>(Op);
8943     if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
8944 
8945     PHINode *P = dyn_cast<PHINode>(OpInst);
8946     if (!P)
8947       // If this operand is already visited, reuse the prior result.
8948       // We may have P != PHI if this is the deepest point at which the
8949       // inconsistent paths meet.
8950       P = PHIMap.lookup(OpInst);
8951     if (!P) {
8952       // Recurse and memoize the results, whether a phi is found or not.
8953       // This recursive call invalidates pointers into PHIMap.
8954       P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1);
8955       PHIMap[OpInst] = P;
8956     }
8957     if (!P)
8958       return nullptr;  // Not evolving from PHI
8959     if (PHI && PHI != P)
8960       return nullptr;  // Evolving from multiple different PHIs.
8961     PHI = P;
8962   }
8963   // This is a expression evolving from a constant PHI!
8964   return PHI;
8965 }
8966 
8967 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
8968 /// in the loop that V is derived from.  We allow arbitrary operations along the
8969 /// way, but the operands of an operation must either be constants or a value
8970 /// derived from a constant PHI.  If this expression does not fit with these
8971 /// constraints, return null.
8972 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
8973   Instruction *I = dyn_cast<Instruction>(V);
8974   if (!I || !canConstantEvolve(I, L)) return nullptr;
8975 
8976   if (PHINode *PN = dyn_cast<PHINode>(I))
8977     return PN;
8978 
8979   // Record non-constant instructions contained by the loop.
8980   DenseMap<Instruction *, PHINode *> PHIMap;
8981   return getConstantEvolvingPHIOperands(I, L, PHIMap, 0);
8982 }
8983 
8984 /// EvaluateExpression - Given an expression that passes the
8985 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
8986 /// in the loop has the value PHIVal.  If we can't fold this expression for some
8987 /// reason, return null.
8988 static Constant *EvaluateExpression(Value *V, const Loop *L,
8989                                     DenseMap<Instruction *, Constant *> &Vals,
8990                                     const DataLayout &DL,
8991                                     const TargetLibraryInfo *TLI) {
8992   // Convenient constant check, but redundant for recursive calls.
8993   if (Constant *C = dyn_cast<Constant>(V)) return C;
8994   Instruction *I = dyn_cast<Instruction>(V);
8995   if (!I) return nullptr;
8996 
8997   if (Constant *C = Vals.lookup(I)) return C;
8998 
8999   // An instruction inside the loop depends on a value outside the loop that we
9000   // weren't given a mapping for, or a value such as a call inside the loop.
9001   if (!canConstantEvolve(I, L)) return nullptr;
9002 
9003   // An unmapped PHI can be due to a branch or another loop inside this loop,
9004   // or due to this not being the initial iteration through a loop where we
9005   // couldn't compute the evolution of this particular PHI last time.
9006   if (isa<PHINode>(I)) return nullptr;
9007 
9008   std::vector<Constant*> Operands(I->getNumOperands());
9009 
9010   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
9011     Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
9012     if (!Operand) {
9013       Operands[i] = dyn_cast<Constant>(I->getOperand(i));
9014       if (!Operands[i]) return nullptr;
9015       continue;
9016     }
9017     Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
9018     Vals[Operand] = C;
9019     if (!C) return nullptr;
9020     Operands[i] = C;
9021   }
9022 
9023   if (CmpInst *CI = dyn_cast<CmpInst>(I))
9024     return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
9025                                            Operands[1], DL, TLI);
9026   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
9027     if (!LI->isVolatile())
9028       return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
9029   }
9030   return ConstantFoldInstOperands(I, Operands, DL, TLI);
9031 }
9032 
9033 
9034 // If every incoming value to PN except the one for BB is a specific Constant,
9035 // return that, else return nullptr.
9036 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
9037   Constant *IncomingVal = nullptr;
9038 
9039   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9040     if (PN->getIncomingBlock(i) == BB)
9041       continue;
9042 
9043     auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
9044     if (!CurrentVal)
9045       return nullptr;
9046 
9047     if (IncomingVal != CurrentVal) {
9048       if (IncomingVal)
9049         return nullptr;
9050       IncomingVal = CurrentVal;
9051     }
9052   }
9053 
9054   return IncomingVal;
9055 }
9056 
9057 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
9058 /// in the header of its containing loop, we know the loop executes a
9059 /// constant number of times, and the PHI node is just a recurrence
9060 /// involving constants, fold it.
9061 Constant *
9062 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
9063                                                    const APInt &BEs,
9064                                                    const Loop *L) {
9065   auto I = ConstantEvolutionLoopExitValue.find(PN);
9066   if (I != ConstantEvolutionLoopExitValue.end())
9067     return I->second;
9068 
9069   if (BEs.ugt(MaxBruteForceIterations))
9070     return ConstantEvolutionLoopExitValue[PN] = nullptr;  // Not going to evaluate it.
9071 
9072   Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
9073 
9074   DenseMap<Instruction *, Constant *> CurrentIterVals;
9075   BasicBlock *Header = L->getHeader();
9076   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
9077 
9078   BasicBlock *Latch = L->getLoopLatch();
9079   if (!Latch)
9080     return nullptr;
9081 
9082   for (PHINode &PHI : Header->phis()) {
9083     if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
9084       CurrentIterVals[&PHI] = StartCST;
9085   }
9086   if (!CurrentIterVals.count(PN))
9087     return RetVal = nullptr;
9088 
9089   Value *BEValue = PN->getIncomingValueForBlock(Latch);
9090 
9091   // Execute the loop symbolically to determine the exit value.
9092   assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) &&
9093          "BEs is <= MaxBruteForceIterations which is an 'unsigned'!");
9094 
9095   unsigned NumIterations = BEs.getZExtValue(); // must be in range
9096   unsigned IterationNum = 0;
9097   const DataLayout &DL = getDataLayout();
9098   for (; ; ++IterationNum) {
9099     if (IterationNum == NumIterations)
9100       return RetVal = CurrentIterVals[PN];  // Got exit value!
9101 
9102     // Compute the value of the PHIs for the next iteration.
9103     // EvaluateExpression adds non-phi values to the CurrentIterVals map.
9104     DenseMap<Instruction *, Constant *> NextIterVals;
9105     Constant *NextPHI =
9106         EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
9107     if (!NextPHI)
9108       return nullptr;        // Couldn't evaluate!
9109     NextIterVals[PN] = NextPHI;
9110 
9111     bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
9112 
9113     // Also evaluate the other PHI nodes.  However, we don't get to stop if we
9114     // cease to be able to evaluate one of them or if they stop evolving,
9115     // because that doesn't necessarily prevent us from computing PN.
9116     SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
9117     for (const auto &I : CurrentIterVals) {
9118       PHINode *PHI = dyn_cast<PHINode>(I.first);
9119       if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
9120       PHIsToCompute.emplace_back(PHI, I.second);
9121     }
9122     // We use two distinct loops because EvaluateExpression may invalidate any
9123     // iterators into CurrentIterVals.
9124     for (const auto &I : PHIsToCompute) {
9125       PHINode *PHI = I.first;
9126       Constant *&NextPHI = NextIterVals[PHI];
9127       if (!NextPHI) {   // Not already computed.
9128         Value *BEValue = PHI->getIncomingValueForBlock(Latch);
9129         NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
9130       }
9131       if (NextPHI != I.second)
9132         StoppedEvolving = false;
9133     }
9134 
9135     // If all entries in CurrentIterVals == NextIterVals then we can stop
9136     // iterating, the loop can't continue to change.
9137     if (StoppedEvolving)
9138       return RetVal = CurrentIterVals[PN];
9139 
9140     CurrentIterVals.swap(NextIterVals);
9141   }
9142 }
9143 
9144 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
9145                                                           Value *Cond,
9146                                                           bool ExitWhen) {
9147   PHINode *PN = getConstantEvolvingPHI(Cond, L);
9148   if (!PN) return getCouldNotCompute();
9149 
9150   // If the loop is canonicalized, the PHI will have exactly two entries.
9151   // That's the only form we support here.
9152   if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
9153 
9154   DenseMap<Instruction *, Constant *> CurrentIterVals;
9155   BasicBlock *Header = L->getHeader();
9156   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
9157 
9158   BasicBlock *Latch = L->getLoopLatch();
9159   assert(Latch && "Should follow from NumIncomingValues == 2!");
9160 
9161   for (PHINode &PHI : Header->phis()) {
9162     if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
9163       CurrentIterVals[&PHI] = StartCST;
9164   }
9165   if (!CurrentIterVals.count(PN))
9166     return getCouldNotCompute();
9167 
9168   // Okay, we find a PHI node that defines the trip count of this loop.  Execute
9169   // the loop symbolically to determine when the condition gets a value of
9170   // "ExitWhen".
9171   unsigned MaxIterations = MaxBruteForceIterations;   // Limit analysis.
9172   const DataLayout &DL = getDataLayout();
9173   for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
9174     auto *CondVal = dyn_cast_or_null<ConstantInt>(
9175         EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
9176 
9177     // Couldn't symbolically evaluate.
9178     if (!CondVal) return getCouldNotCompute();
9179 
9180     if (CondVal->getValue() == uint64_t(ExitWhen)) {
9181       ++NumBruteForceTripCountsComputed;
9182       return getConstant(Type::getInt32Ty(getContext()), IterationNum);
9183     }
9184 
9185     // Update all the PHI nodes for the next iteration.
9186     DenseMap<Instruction *, Constant *> NextIterVals;
9187 
9188     // Create a list of which PHIs we need to compute. We want to do this before
9189     // calling EvaluateExpression on them because that may invalidate iterators
9190     // into CurrentIterVals.
9191     SmallVector<PHINode *, 8> PHIsToCompute;
9192     for (const auto &I : CurrentIterVals) {
9193       PHINode *PHI = dyn_cast<PHINode>(I.first);
9194       if (!PHI || PHI->getParent() != Header) continue;
9195       PHIsToCompute.push_back(PHI);
9196     }
9197     for (PHINode *PHI : PHIsToCompute) {
9198       Constant *&NextPHI = NextIterVals[PHI];
9199       if (NextPHI) continue;    // Already computed!
9200 
9201       Value *BEValue = PHI->getIncomingValueForBlock(Latch);
9202       NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
9203     }
9204     CurrentIterVals.swap(NextIterVals);
9205   }
9206 
9207   // Too many iterations were needed to evaluate.
9208   return getCouldNotCompute();
9209 }
9210 
9211 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
9212   SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
9213       ValuesAtScopes[V];
9214   // Check to see if we've folded this expression at this loop before.
9215   for (auto &LS : Values)
9216     if (LS.first == L)
9217       return LS.second ? LS.second : V;
9218 
9219   Values.emplace_back(L, nullptr);
9220 
9221   // Otherwise compute it.
9222   const SCEV *C = computeSCEVAtScope(V, L);
9223   for (auto &LS : reverse(ValuesAtScopes[V]))
9224     if (LS.first == L) {
9225       LS.second = C;
9226       if (!isa<SCEVConstant>(C))
9227         ValuesAtScopesUsers[C].push_back({L, V});
9228       break;
9229     }
9230   return C;
9231 }
9232 
9233 /// This builds up a Constant using the ConstantExpr interface.  That way, we
9234 /// will return Constants for objects which aren't represented by a
9235 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
9236 /// Returns NULL if the SCEV isn't representable as a Constant.
9237 static Constant *BuildConstantFromSCEV(const SCEV *V) {
9238   switch (V->getSCEVType()) {
9239   case scCouldNotCompute:
9240   case scAddRecExpr:
9241     return nullptr;
9242   case scConstant:
9243     return cast<SCEVConstant>(V)->getValue();
9244   case scUnknown:
9245     return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
9246   case scSignExtend: {
9247     const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
9248     if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
9249       return ConstantExpr::getSExt(CastOp, SS->getType());
9250     return nullptr;
9251   }
9252   case scZeroExtend: {
9253     const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
9254     if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
9255       return ConstantExpr::getZExt(CastOp, SZ->getType());
9256     return nullptr;
9257   }
9258   case scPtrToInt: {
9259     const SCEVPtrToIntExpr *P2I = cast<SCEVPtrToIntExpr>(V);
9260     if (Constant *CastOp = BuildConstantFromSCEV(P2I->getOperand()))
9261       return ConstantExpr::getPtrToInt(CastOp, P2I->getType());
9262 
9263     return nullptr;
9264   }
9265   case scTruncate: {
9266     const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
9267     if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
9268       return ConstantExpr::getTrunc(CastOp, ST->getType());
9269     return nullptr;
9270   }
9271   case scAddExpr: {
9272     const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
9273     if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
9274       if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
9275         unsigned AS = PTy->getAddressSpace();
9276         Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
9277         C = ConstantExpr::getBitCast(C, DestPtrTy);
9278       }
9279       for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
9280         Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
9281         if (!C2)
9282           return nullptr;
9283 
9284         // First pointer!
9285         if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
9286           unsigned AS = C2->getType()->getPointerAddressSpace();
9287           std::swap(C, C2);
9288           Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
9289           // The offsets have been converted to bytes.  We can add bytes to an
9290           // i8* by GEP with the byte count in the first index.
9291           C = ConstantExpr::getBitCast(C, DestPtrTy);
9292         }
9293 
9294         // Don't bother trying to sum two pointers. We probably can't
9295         // statically compute a load that results from it anyway.
9296         if (C2->getType()->isPointerTy())
9297           return nullptr;
9298 
9299         if (C->getType()->isPointerTy()) {
9300           C = ConstantExpr::getGetElementPtr(Type::getInt8Ty(C->getContext()),
9301                                              C, C2);
9302         } else {
9303           C = ConstantExpr::getAdd(C, C2);
9304         }
9305       }
9306       return C;
9307     }
9308     return nullptr;
9309   }
9310   case scMulExpr: {
9311     const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
9312     if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
9313       // Don't bother with pointers at all.
9314       if (C->getType()->isPointerTy())
9315         return nullptr;
9316       for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
9317         Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
9318         if (!C2 || C2->getType()->isPointerTy())
9319           return nullptr;
9320         C = ConstantExpr::getMul(C, C2);
9321       }
9322       return C;
9323     }
9324     return nullptr;
9325   }
9326   case scUDivExpr: {
9327     const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
9328     if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
9329       if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
9330         if (LHS->getType() == RHS->getType())
9331           return ConstantExpr::getUDiv(LHS, RHS);
9332     return nullptr;
9333   }
9334   case scSMaxExpr:
9335   case scUMaxExpr:
9336   case scSMinExpr:
9337   case scUMinExpr:
9338   case scSequentialUMinExpr:
9339     return nullptr; // TODO: smax, umax, smin, umax, umin_seq.
9340   }
9341   llvm_unreachable("Unknown SCEV kind!");
9342 }
9343 
9344 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
9345   if (isa<SCEVConstant>(V)) return V;
9346 
9347   // If this instruction is evolved from a constant-evolving PHI, compute the
9348   // exit value from the loop without using SCEVs.
9349   if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
9350     if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
9351       if (PHINode *PN = dyn_cast<PHINode>(I)) {
9352         const Loop *CurrLoop = this->LI[I->getParent()];
9353         // Looking for loop exit value.
9354         if (CurrLoop && CurrLoop->getParentLoop() == L &&
9355             PN->getParent() == CurrLoop->getHeader()) {
9356           // Okay, there is no closed form solution for the PHI node.  Check
9357           // to see if the loop that contains it has a known backedge-taken
9358           // count.  If so, we may be able to force computation of the exit
9359           // value.
9360           const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop);
9361           // This trivial case can show up in some degenerate cases where
9362           // the incoming IR has not yet been fully simplified.
9363           if (BackedgeTakenCount->isZero()) {
9364             Value *InitValue = nullptr;
9365             bool MultipleInitValues = false;
9366             for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
9367               if (!CurrLoop->contains(PN->getIncomingBlock(i))) {
9368                 if (!InitValue)
9369                   InitValue = PN->getIncomingValue(i);
9370                 else if (InitValue != PN->getIncomingValue(i)) {
9371                   MultipleInitValues = true;
9372                   break;
9373                 }
9374               }
9375             }
9376             if (!MultipleInitValues && InitValue)
9377               return getSCEV(InitValue);
9378           }
9379           // Do we have a loop invariant value flowing around the backedge
9380           // for a loop which must execute the backedge?
9381           if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
9382               isKnownPositive(BackedgeTakenCount) &&
9383               PN->getNumIncomingValues() == 2) {
9384 
9385             unsigned InLoopPred =
9386                 CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1;
9387             Value *BackedgeVal = PN->getIncomingValue(InLoopPred);
9388             if (CurrLoop->isLoopInvariant(BackedgeVal))
9389               return getSCEV(BackedgeVal);
9390           }
9391           if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
9392             // Okay, we know how many times the containing loop executes.  If
9393             // this is a constant evolving PHI node, get the final value at
9394             // the specified iteration number.
9395             Constant *RV = getConstantEvolutionLoopExitValue(
9396                 PN, BTCC->getAPInt(), CurrLoop);
9397             if (RV) return getSCEV(RV);
9398           }
9399         }
9400 
9401         // If there is a single-input Phi, evaluate it at our scope. If we can
9402         // prove that this replacement does not break LCSSA form, use new value.
9403         if (PN->getNumOperands() == 1) {
9404           const SCEV *Input = getSCEV(PN->getOperand(0));
9405           const SCEV *InputAtScope = getSCEVAtScope(Input, L);
9406           // TODO: We can generalize it using LI.replacementPreservesLCSSAForm,
9407           // for the simplest case just support constants.
9408           if (isa<SCEVConstant>(InputAtScope)) return InputAtScope;
9409         }
9410       }
9411 
9412       // Okay, this is an expression that we cannot symbolically evaluate
9413       // into a SCEV.  Check to see if it's possible to symbolically evaluate
9414       // the arguments into constants, and if so, try to constant propagate the
9415       // result.  This is particularly useful for computing loop exit values.
9416       if (CanConstantFold(I)) {
9417         SmallVector<Constant *, 4> Operands;
9418         bool MadeImprovement = false;
9419         for (Value *Op : I->operands()) {
9420           if (Constant *C = dyn_cast<Constant>(Op)) {
9421             Operands.push_back(C);
9422             continue;
9423           }
9424 
9425           // If any of the operands is non-constant and if they are
9426           // non-integer and non-pointer, don't even try to analyze them
9427           // with scev techniques.
9428           if (!isSCEVable(Op->getType()))
9429             return V;
9430 
9431           const SCEV *OrigV = getSCEV(Op);
9432           const SCEV *OpV = getSCEVAtScope(OrigV, L);
9433           MadeImprovement |= OrigV != OpV;
9434 
9435           Constant *C = BuildConstantFromSCEV(OpV);
9436           if (!C) return V;
9437           if (C->getType() != Op->getType())
9438             C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
9439                                                               Op->getType(),
9440                                                               false),
9441                                       C, Op->getType());
9442           Operands.push_back(C);
9443         }
9444 
9445         // Check to see if getSCEVAtScope actually made an improvement.
9446         if (MadeImprovement) {
9447           Constant *C = nullptr;
9448           const DataLayout &DL = getDataLayout();
9449           if (const CmpInst *CI = dyn_cast<CmpInst>(I))
9450             C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
9451                                                 Operands[1], DL, &TLI);
9452           else if (const LoadInst *Load = dyn_cast<LoadInst>(I)) {
9453             if (!Load->isVolatile())
9454               C = ConstantFoldLoadFromConstPtr(Operands[0], Load->getType(),
9455                                                DL);
9456           } else
9457             C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
9458           if (!C) return V;
9459           return getSCEV(C);
9460         }
9461       }
9462     }
9463 
9464     // This is some other type of SCEVUnknown, just return it.
9465     return V;
9466   }
9467 
9468   if (isa<SCEVCommutativeExpr>(V) || isa<SCEVSequentialMinMaxExpr>(V)) {
9469     const auto *Comm = cast<SCEVNAryExpr>(V);
9470     // Avoid performing the look-up in the common case where the specified
9471     // expression has no loop-variant portions.
9472     for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
9473       const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
9474       if (OpAtScope != Comm->getOperand(i)) {
9475         // Okay, at least one of these operands is loop variant but might be
9476         // foldable.  Build a new instance of the folded commutative expression.
9477         SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
9478                                             Comm->op_begin()+i);
9479         NewOps.push_back(OpAtScope);
9480 
9481         for (++i; i != e; ++i) {
9482           OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
9483           NewOps.push_back(OpAtScope);
9484         }
9485         if (isa<SCEVAddExpr>(Comm))
9486           return getAddExpr(NewOps, Comm->getNoWrapFlags());
9487         if (isa<SCEVMulExpr>(Comm))
9488           return getMulExpr(NewOps, Comm->getNoWrapFlags());
9489         if (isa<SCEVMinMaxExpr>(Comm))
9490           return getMinMaxExpr(Comm->getSCEVType(), NewOps);
9491         if (isa<SCEVSequentialMinMaxExpr>(Comm))
9492           return getSequentialMinMaxExpr(Comm->getSCEVType(), NewOps);
9493         llvm_unreachable("Unknown commutative / sequential min/max SCEV type!");
9494       }
9495     }
9496     // If we got here, all operands are loop invariant.
9497     return Comm;
9498   }
9499 
9500   if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
9501     const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
9502     const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
9503     if (LHS == Div->getLHS() && RHS == Div->getRHS())
9504       return Div;   // must be loop invariant
9505     return getUDivExpr(LHS, RHS);
9506   }
9507 
9508   // If this is a loop recurrence for a loop that does not contain L, then we
9509   // are dealing with the final value computed by the loop.
9510   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
9511     // First, attempt to evaluate each operand.
9512     // Avoid performing the look-up in the common case where the specified
9513     // expression has no loop-variant portions.
9514     for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
9515       const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
9516       if (OpAtScope == AddRec->getOperand(i))
9517         continue;
9518 
9519       // Okay, at least one of these operands is loop variant but might be
9520       // foldable.  Build a new instance of the folded commutative expression.
9521       SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
9522                                           AddRec->op_begin()+i);
9523       NewOps.push_back(OpAtScope);
9524       for (++i; i != e; ++i)
9525         NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
9526 
9527       const SCEV *FoldedRec =
9528         getAddRecExpr(NewOps, AddRec->getLoop(),
9529                       AddRec->getNoWrapFlags(SCEV::FlagNW));
9530       AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
9531       // The addrec may be folded to a nonrecurrence, for example, if the
9532       // induction variable is multiplied by zero after constant folding. Go
9533       // ahead and return the folded value.
9534       if (!AddRec)
9535         return FoldedRec;
9536       break;
9537     }
9538 
9539     // If the scope is outside the addrec's loop, evaluate it by using the
9540     // loop exit value of the addrec.
9541     if (!AddRec->getLoop()->contains(L)) {
9542       // To evaluate this recurrence, we need to know how many times the AddRec
9543       // loop iterates.  Compute this now.
9544       const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
9545       if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
9546 
9547       // Then, evaluate the AddRec.
9548       return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
9549     }
9550 
9551     return AddRec;
9552   }
9553 
9554   if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
9555     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
9556     if (Op == Cast->getOperand())
9557       return Cast;  // must be loop invariant
9558     return getCastExpr(Cast->getSCEVType(), Op, Cast->getType());
9559   }
9560 
9561   llvm_unreachable("Unknown SCEV type!");
9562 }
9563 
9564 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
9565   return getSCEVAtScope(getSCEV(V), L);
9566 }
9567 
9568 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const {
9569   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S))
9570     return stripInjectiveFunctions(ZExt->getOperand());
9571   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S))
9572     return stripInjectiveFunctions(SExt->getOperand());
9573   return S;
9574 }
9575 
9576 /// Finds the minimum unsigned root of the following equation:
9577 ///
9578 ///     A * X = B (mod N)
9579 ///
9580 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
9581 /// A and B isn't important.
9582 ///
9583 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
9584 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B,
9585                                                ScalarEvolution &SE) {
9586   uint32_t BW = A.getBitWidth();
9587   assert(BW == SE.getTypeSizeInBits(B->getType()));
9588   assert(A != 0 && "A must be non-zero.");
9589 
9590   // 1. D = gcd(A, N)
9591   //
9592   // The gcd of A and N may have only one prime factor: 2. The number of
9593   // trailing zeros in A is its multiplicity
9594   uint32_t Mult2 = A.countTrailingZeros();
9595   // D = 2^Mult2
9596 
9597   // 2. Check if B is divisible by D.
9598   //
9599   // B is divisible by D if and only if the multiplicity of prime factor 2 for B
9600   // is not less than multiplicity of this prime factor for D.
9601   if (SE.GetMinTrailingZeros(B) < Mult2)
9602     return SE.getCouldNotCompute();
9603 
9604   // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
9605   // modulo (N / D).
9606   //
9607   // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
9608   // (N / D) in general. The inverse itself always fits into BW bits, though,
9609   // so we immediately truncate it.
9610   APInt AD = A.lshr(Mult2).zext(BW + 1);  // AD = A / D
9611   APInt Mod(BW + 1, 0);
9612   Mod.setBit(BW - Mult2);  // Mod = N / D
9613   APInt I = AD.multiplicativeInverse(Mod).trunc(BW);
9614 
9615   // 4. Compute the minimum unsigned root of the equation:
9616   // I * (B / D) mod (N / D)
9617   // To simplify the computation, we factor out the divide by D:
9618   // (I * B mod N) / D
9619   const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
9620   return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
9621 }
9622 
9623 /// For a given quadratic addrec, generate coefficients of the corresponding
9624 /// quadratic equation, multiplied by a common value to ensure that they are
9625 /// integers.
9626 /// The returned value is a tuple { A, B, C, M, BitWidth }, where
9627 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C
9628 /// were multiplied by, and BitWidth is the bit width of the original addrec
9629 /// coefficients.
9630 /// This function returns None if the addrec coefficients are not compile-
9631 /// time constants.
9632 static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>>
9633 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) {
9634   assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
9635   const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
9636   const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
9637   const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
9638   LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: "
9639                     << *AddRec << '\n');
9640 
9641   // We currently can only solve this if the coefficients are constants.
9642   if (!LC || !MC || !NC) {
9643     LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n");
9644     return None;
9645   }
9646 
9647   APInt L = LC->getAPInt();
9648   APInt M = MC->getAPInt();
9649   APInt N = NC->getAPInt();
9650   assert(!N.isZero() && "This is not a quadratic addrec");
9651 
9652   unsigned BitWidth = LC->getAPInt().getBitWidth();
9653   unsigned NewWidth = BitWidth + 1;
9654   LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: "
9655                     << BitWidth << '\n');
9656   // The sign-extension (as opposed to a zero-extension) here matches the
9657   // extension used in SolveQuadraticEquationWrap (with the same motivation).
9658   N = N.sext(NewWidth);
9659   M = M.sext(NewWidth);
9660   L = L.sext(NewWidth);
9661 
9662   // The increments are M, M+N, M+2N, ..., so the accumulated values are
9663   //   L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is,
9664   //   L+M, L+2M+N, L+3M+3N, ...
9665   // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N.
9666   //
9667   // The equation Acc = 0 is then
9668   //   L + nM + n(n-1)/2 N = 0,  or  2L + 2M n + n(n-1) N = 0.
9669   // In a quadratic form it becomes:
9670   //   N n^2 + (2M-N) n + 2L = 0.
9671 
9672   APInt A = N;
9673   APInt B = 2 * M - A;
9674   APInt C = 2 * L;
9675   APInt T = APInt(NewWidth, 2);
9676   LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B
9677                     << "x + " << C << ", coeff bw: " << NewWidth
9678                     << ", multiplied by " << T << '\n');
9679   return std::make_tuple(A, B, C, T, BitWidth);
9680 }
9681 
9682 /// Helper function to compare optional APInts:
9683 /// (a) if X and Y both exist, return min(X, Y),
9684 /// (b) if neither X nor Y exist, return None,
9685 /// (c) if exactly one of X and Y exists, return that value.
9686 static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) {
9687   if (X.hasValue() && Y.hasValue()) {
9688     unsigned W = std::max(X->getBitWidth(), Y->getBitWidth());
9689     APInt XW = X->sextOrSelf(W);
9690     APInt YW = Y->sextOrSelf(W);
9691     return XW.slt(YW) ? *X : *Y;
9692   }
9693   if (!X.hasValue() && !Y.hasValue())
9694     return None;
9695   return X.hasValue() ? *X : *Y;
9696 }
9697 
9698 /// Helper function to truncate an optional APInt to a given BitWidth.
9699 /// When solving addrec-related equations, it is preferable to return a value
9700 /// that has the same bit width as the original addrec's coefficients. If the
9701 /// solution fits in the original bit width, truncate it (except for i1).
9702 /// Returning a value of a different bit width may inhibit some optimizations.
9703 ///
9704 /// In general, a solution to a quadratic equation generated from an addrec
9705 /// may require BW+1 bits, where BW is the bit width of the addrec's
9706 /// coefficients. The reason is that the coefficients of the quadratic
9707 /// equation are BW+1 bits wide (to avoid truncation when converting from
9708 /// the addrec to the equation).
9709 static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) {
9710   if (!X.hasValue())
9711     return None;
9712   unsigned W = X->getBitWidth();
9713   if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth))
9714     return X->trunc(BitWidth);
9715   return X;
9716 }
9717 
9718 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n
9719 /// iterations. The values L, M, N are assumed to be signed, and they
9720 /// should all have the same bit widths.
9721 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW,
9722 /// where BW is the bit width of the addrec's coefficients.
9723 /// If the calculated value is a BW-bit integer (for BW > 1), it will be
9724 /// returned as such, otherwise the bit width of the returned value may
9725 /// be greater than BW.
9726 ///
9727 /// This function returns None if
9728 /// (a) the addrec coefficients are not constant, or
9729 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases
9730 ///     like x^2 = 5, no integer solutions exist, in other cases an integer
9731 ///     solution may exist, but SolveQuadraticEquationWrap may fail to find it.
9732 static Optional<APInt>
9733 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
9734   APInt A, B, C, M;
9735   unsigned BitWidth;
9736   auto T = GetQuadraticEquation(AddRec);
9737   if (!T.hasValue())
9738     return None;
9739 
9740   std::tie(A, B, C, M, BitWidth) = *T;
9741   LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n");
9742   Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1);
9743   if (!X.hasValue())
9744     return None;
9745 
9746   ConstantInt *CX = ConstantInt::get(SE.getContext(), *X);
9747   ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE);
9748   if (!V->isZero())
9749     return None;
9750 
9751   return TruncIfPossible(X, BitWidth);
9752 }
9753 
9754 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n
9755 /// iterations. The values M, N are assumed to be signed, and they
9756 /// should all have the same bit widths.
9757 /// Find the least n such that c(n) does not belong to the given range,
9758 /// while c(n-1) does.
9759 ///
9760 /// This function returns None if
9761 /// (a) the addrec coefficients are not constant, or
9762 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the
9763 ///     bounds of the range.
9764 static Optional<APInt>
9765 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec,
9766                           const ConstantRange &Range, ScalarEvolution &SE) {
9767   assert(AddRec->getOperand(0)->isZero() &&
9768          "Starting value of addrec should be 0");
9769   LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range "
9770                     << Range << ", addrec " << *AddRec << '\n');
9771   // This case is handled in getNumIterationsInRange. Here we can assume that
9772   // we start in the range.
9773   assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) &&
9774          "Addrec's initial value should be in range");
9775 
9776   APInt A, B, C, M;
9777   unsigned BitWidth;
9778   auto T = GetQuadraticEquation(AddRec);
9779   if (!T.hasValue())
9780     return None;
9781 
9782   // Be careful about the return value: there can be two reasons for not
9783   // returning an actual number. First, if no solutions to the equations
9784   // were found, and second, if the solutions don't leave the given range.
9785   // The first case means that the actual solution is "unknown", the second
9786   // means that it's known, but not valid. If the solution is unknown, we
9787   // cannot make any conclusions.
9788   // Return a pair: the optional solution and a flag indicating if the
9789   // solution was found.
9790   auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> {
9791     // Solve for signed overflow and unsigned overflow, pick the lower
9792     // solution.
9793     LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary "
9794                       << Bound << " (before multiplying by " << M << ")\n");
9795     Bound *= M; // The quadratic equation multiplier.
9796 
9797     Optional<APInt> SO = None;
9798     if (BitWidth > 1) {
9799       LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
9800                            "signed overflow\n");
9801       SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth);
9802     }
9803     LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
9804                          "unsigned overflow\n");
9805     Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound,
9806                                                               BitWidth+1);
9807 
9808     auto LeavesRange = [&] (const APInt &X) {
9809       ConstantInt *C0 = ConstantInt::get(SE.getContext(), X);
9810       ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE);
9811       if (Range.contains(V0->getValue()))
9812         return false;
9813       // X should be at least 1, so X-1 is non-negative.
9814       ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1);
9815       ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE);
9816       if (Range.contains(V1->getValue()))
9817         return true;
9818       return false;
9819     };
9820 
9821     // If SolveQuadraticEquationWrap returns None, it means that there can
9822     // be a solution, but the function failed to find it. We cannot treat it
9823     // as "no solution".
9824     if (!SO.hasValue() || !UO.hasValue())
9825       return { None, false };
9826 
9827     // Check the smaller value first to see if it leaves the range.
9828     // At this point, both SO and UO must have values.
9829     Optional<APInt> Min = MinOptional(SO, UO);
9830     if (LeavesRange(*Min))
9831       return { Min, true };
9832     Optional<APInt> Max = Min == SO ? UO : SO;
9833     if (LeavesRange(*Max))
9834       return { Max, true };
9835 
9836     // Solutions were found, but were eliminated, hence the "true".
9837     return { None, true };
9838   };
9839 
9840   std::tie(A, B, C, M, BitWidth) = *T;
9841   // Lower bound is inclusive, subtract 1 to represent the exiting value.
9842   APInt Lower = Range.getLower().sextOrSelf(A.getBitWidth()) - 1;
9843   APInt Upper = Range.getUpper().sextOrSelf(A.getBitWidth());
9844   auto SL = SolveForBoundary(Lower);
9845   auto SU = SolveForBoundary(Upper);
9846   // If any of the solutions was unknown, no meaninigful conclusions can
9847   // be made.
9848   if (!SL.second || !SU.second)
9849     return None;
9850 
9851   // Claim: The correct solution is not some value between Min and Max.
9852   //
9853   // Justification: Assuming that Min and Max are different values, one of
9854   // them is when the first signed overflow happens, the other is when the
9855   // first unsigned overflow happens. Crossing the range boundary is only
9856   // possible via an overflow (treating 0 as a special case of it, modeling
9857   // an overflow as crossing k*2^W for some k).
9858   //
9859   // The interesting case here is when Min was eliminated as an invalid
9860   // solution, but Max was not. The argument is that if there was another
9861   // overflow between Min and Max, it would also have been eliminated if
9862   // it was considered.
9863   //
9864   // For a given boundary, it is possible to have two overflows of the same
9865   // type (signed/unsigned) without having the other type in between: this
9866   // can happen when the vertex of the parabola is between the iterations
9867   // corresponding to the overflows. This is only possible when the two
9868   // overflows cross k*2^W for the same k. In such case, if the second one
9869   // left the range (and was the first one to do so), the first overflow
9870   // would have to enter the range, which would mean that either we had left
9871   // the range before or that we started outside of it. Both of these cases
9872   // are contradictions.
9873   //
9874   // Claim: In the case where SolveForBoundary returns None, the correct
9875   // solution is not some value between the Max for this boundary and the
9876   // Min of the other boundary.
9877   //
9878   // Justification: Assume that we had such Max_A and Min_B corresponding
9879   // to range boundaries A and B and such that Max_A < Min_B. If there was
9880   // a solution between Max_A and Min_B, it would have to be caused by an
9881   // overflow corresponding to either A or B. It cannot correspond to B,
9882   // since Min_B is the first occurrence of such an overflow. If it
9883   // corresponded to A, it would have to be either a signed or an unsigned
9884   // overflow that is larger than both eliminated overflows for A. But
9885   // between the eliminated overflows and this overflow, the values would
9886   // cover the entire value space, thus crossing the other boundary, which
9887   // is a contradiction.
9888 
9889   return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth);
9890 }
9891 
9892 ScalarEvolution::ExitLimit
9893 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit,
9894                               bool AllowPredicates) {
9895 
9896   // This is only used for loops with a "x != y" exit test. The exit condition
9897   // is now expressed as a single expression, V = x-y. So the exit test is
9898   // effectively V != 0.  We know and take advantage of the fact that this
9899   // expression only being used in a comparison by zero context.
9900 
9901   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
9902   // If the value is a constant
9903   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
9904     // If the value is already zero, the branch will execute zero times.
9905     if (C->getValue()->isZero()) return C;
9906     return getCouldNotCompute();  // Otherwise it will loop infinitely.
9907   }
9908 
9909   const SCEVAddRecExpr *AddRec =
9910       dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V));
9911 
9912   if (!AddRec && AllowPredicates)
9913     // Try to make this an AddRec using runtime tests, in the first X
9914     // iterations of this loop, where X is the SCEV expression found by the
9915     // algorithm below.
9916     AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
9917 
9918   if (!AddRec || AddRec->getLoop() != L)
9919     return getCouldNotCompute();
9920 
9921   // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
9922   // the quadratic equation to solve it.
9923   if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
9924     // We can only use this value if the chrec ends up with an exact zero
9925     // value at this index.  When solving for "X*X != 5", for example, we
9926     // should not accept a root of 2.
9927     if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) {
9928       const auto *R = cast<SCEVConstant>(getConstant(S.getValue()));
9929       return ExitLimit(R, R, false, Predicates);
9930     }
9931     return getCouldNotCompute();
9932   }
9933 
9934   // Otherwise we can only handle this if it is affine.
9935   if (!AddRec->isAffine())
9936     return getCouldNotCompute();
9937 
9938   // If this is an affine expression, the execution count of this branch is
9939   // the minimum unsigned root of the following equation:
9940   //
9941   //     Start + Step*N = 0 (mod 2^BW)
9942   //
9943   // equivalent to:
9944   //
9945   //             Step*N = -Start (mod 2^BW)
9946   //
9947   // where BW is the common bit width of Start and Step.
9948 
9949   // Get the initial value for the loop.
9950   const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
9951   const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
9952 
9953   // For now we handle only constant steps.
9954   //
9955   // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
9956   // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
9957   // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
9958   // We have not yet seen any such cases.
9959   const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
9960   if (!StepC || StepC->getValue()->isZero())
9961     return getCouldNotCompute();
9962 
9963   // For positive steps (counting up until unsigned overflow):
9964   //   N = -Start/Step (as unsigned)
9965   // For negative steps (counting down to zero):
9966   //   N = Start/-Step
9967   // First compute the unsigned distance from zero in the direction of Step.
9968   bool CountDown = StepC->getAPInt().isNegative();
9969   const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
9970 
9971   // Handle unitary steps, which cannot wraparound.
9972   // 1*N = -Start; -1*N = Start (mod 2^BW), so:
9973   //   N = Distance (as unsigned)
9974   if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) {
9975     APInt MaxBECount = getUnsignedRangeMax(applyLoopGuards(Distance, L));
9976     MaxBECount = APIntOps::umin(MaxBECount, getUnsignedRangeMax(Distance));
9977 
9978     // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
9979     // we end up with a loop whose backedge-taken count is n - 1.  Detect this
9980     // case, and see if we can improve the bound.
9981     //
9982     // Explicitly handling this here is necessary because getUnsignedRange
9983     // isn't context-sensitive; it doesn't know that we only care about the
9984     // range inside the loop.
9985     const SCEV *Zero = getZero(Distance->getType());
9986     const SCEV *One = getOne(Distance->getType());
9987     const SCEV *DistancePlusOne = getAddExpr(Distance, One);
9988     if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
9989       // If Distance + 1 doesn't overflow, we can compute the maximum distance
9990       // as "unsigned_max(Distance + 1) - 1".
9991       ConstantRange CR = getUnsignedRange(DistancePlusOne);
9992       MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1);
9993     }
9994     return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates);
9995   }
9996 
9997   // If the condition controls loop exit (the loop exits only if the expression
9998   // is true) and the addition is no-wrap we can use unsigned divide to
9999   // compute the backedge count.  In this case, the step may not divide the
10000   // distance, but we don't care because if the condition is "missed" the loop
10001   // will have undefined behavior due to wrapping.
10002   if (ControlsExit && AddRec->hasNoSelfWrap() &&
10003       loopHasNoAbnormalExits(AddRec->getLoop())) {
10004     const SCEV *Exact =
10005         getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
10006     const SCEV *Max = getCouldNotCompute();
10007     if (Exact != getCouldNotCompute()) {
10008       APInt MaxInt = getUnsignedRangeMax(applyLoopGuards(Exact, L));
10009       Max = getConstant(APIntOps::umin(MaxInt, getUnsignedRangeMax(Exact)));
10010     }
10011     return ExitLimit(Exact, Max, false, Predicates);
10012   }
10013 
10014   // Solve the general equation.
10015   const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(),
10016                                                getNegativeSCEV(Start), *this);
10017 
10018   const SCEV *M = E;
10019   if (E != getCouldNotCompute()) {
10020     APInt MaxWithGuards = getUnsignedRangeMax(applyLoopGuards(E, L));
10021     M = getConstant(APIntOps::umin(MaxWithGuards, getUnsignedRangeMax(E)));
10022   }
10023   return ExitLimit(E, M, false, Predicates);
10024 }
10025 
10026 ScalarEvolution::ExitLimit
10027 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
10028   // Loops that look like: while (X == 0) are very strange indeed.  We don't
10029   // handle them yet except for the trivial case.  This could be expanded in the
10030   // future as needed.
10031 
10032   // If the value is a constant, check to see if it is known to be non-zero
10033   // already.  If so, the backedge will execute zero times.
10034   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
10035     if (!C->getValue()->isZero())
10036       return getZero(C->getType());
10037     return getCouldNotCompute();  // Otherwise it will loop infinitely.
10038   }
10039 
10040   // We could implement others, but I really doubt anyone writes loops like
10041   // this, and if they did, they would already be constant folded.
10042   return getCouldNotCompute();
10043 }
10044 
10045 std::pair<const BasicBlock *, const BasicBlock *>
10046 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB)
10047     const {
10048   // If the block has a unique predecessor, then there is no path from the
10049   // predecessor to the block that does not go through the direct edge
10050   // from the predecessor to the block.
10051   if (const BasicBlock *Pred = BB->getSinglePredecessor())
10052     return {Pred, BB};
10053 
10054   // A loop's header is defined to be a block that dominates the loop.
10055   // If the header has a unique predecessor outside the loop, it must be
10056   // a block that has exactly one successor that can reach the loop.
10057   if (const Loop *L = LI.getLoopFor(BB))
10058     return {L->getLoopPredecessor(), L->getHeader()};
10059 
10060   return {nullptr, nullptr};
10061 }
10062 
10063 /// SCEV structural equivalence is usually sufficient for testing whether two
10064 /// expressions are equal, however for the purposes of looking for a condition
10065 /// guarding a loop, it can be useful to be a little more general, since a
10066 /// front-end may have replicated the controlling expression.
10067 static bool HasSameValue(const SCEV *A, const SCEV *B) {
10068   // Quick check to see if they are the same SCEV.
10069   if (A == B) return true;
10070 
10071   auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
10072     // Not all instructions that are "identical" compute the same value.  For
10073     // instance, two distinct alloca instructions allocating the same type are
10074     // identical and do not read memory; but compute distinct values.
10075     return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
10076   };
10077 
10078   // Otherwise, if they're both SCEVUnknown, it's possible that they hold
10079   // two different instructions with the same value. Check for this case.
10080   if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
10081     if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
10082       if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
10083         if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
10084           if (ComputesEqualValues(AI, BI))
10085             return true;
10086 
10087   // Otherwise assume they may have a different value.
10088   return false;
10089 }
10090 
10091 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
10092                                            const SCEV *&LHS, const SCEV *&RHS,
10093                                            unsigned Depth,
10094                                            bool ControllingFiniteLoop) {
10095   bool Changed = false;
10096   // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or
10097   // '0 != 0'.
10098   auto TrivialCase = [&](bool TriviallyTrue) {
10099     LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
10100     Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
10101     return true;
10102   };
10103   // If we hit the max recursion limit bail out.
10104   if (Depth >= 3)
10105     return false;
10106 
10107   // Canonicalize a constant to the right side.
10108   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
10109     // Check for both operands constant.
10110     if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
10111       if (ConstantExpr::getICmp(Pred,
10112                                 LHSC->getValue(),
10113                                 RHSC->getValue())->isNullValue())
10114         return TrivialCase(false);
10115       else
10116         return TrivialCase(true);
10117     }
10118     // Otherwise swap the operands to put the constant on the right.
10119     std::swap(LHS, RHS);
10120     Pred = ICmpInst::getSwappedPredicate(Pred);
10121     Changed = true;
10122   }
10123 
10124   // If we're comparing an addrec with a value which is loop-invariant in the
10125   // addrec's loop, put the addrec on the left. Also make a dominance check,
10126   // as both operands could be addrecs loop-invariant in each other's loop.
10127   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
10128     const Loop *L = AR->getLoop();
10129     if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
10130       std::swap(LHS, RHS);
10131       Pred = ICmpInst::getSwappedPredicate(Pred);
10132       Changed = true;
10133     }
10134   }
10135 
10136   // If there's a constant operand, canonicalize comparisons with boundary
10137   // cases, and canonicalize *-or-equal comparisons to regular comparisons.
10138   if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
10139     const APInt &RA = RC->getAPInt();
10140 
10141     bool SimplifiedByConstantRange = false;
10142 
10143     if (!ICmpInst::isEquality(Pred)) {
10144       ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA);
10145       if (ExactCR.isFullSet())
10146         return TrivialCase(true);
10147       else if (ExactCR.isEmptySet())
10148         return TrivialCase(false);
10149 
10150       APInt NewRHS;
10151       CmpInst::Predicate NewPred;
10152       if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
10153           ICmpInst::isEquality(NewPred)) {
10154         // We were able to convert an inequality to an equality.
10155         Pred = NewPred;
10156         RHS = getConstant(NewRHS);
10157         Changed = SimplifiedByConstantRange = true;
10158       }
10159     }
10160 
10161     if (!SimplifiedByConstantRange) {
10162       switch (Pred) {
10163       default:
10164         break;
10165       case ICmpInst::ICMP_EQ:
10166       case ICmpInst::ICMP_NE:
10167         // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
10168         if (!RA)
10169           if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
10170             if (const SCEVMulExpr *ME =
10171                     dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
10172               if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
10173                   ME->getOperand(0)->isAllOnesValue()) {
10174                 RHS = AE->getOperand(1);
10175                 LHS = ME->getOperand(1);
10176                 Changed = true;
10177               }
10178         break;
10179 
10180 
10181         // The "Should have been caught earlier!" messages refer to the fact
10182         // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
10183         // should have fired on the corresponding cases, and canonicalized the
10184         // check to trivial case.
10185 
10186       case ICmpInst::ICMP_UGE:
10187         assert(!RA.isMinValue() && "Should have been caught earlier!");
10188         Pred = ICmpInst::ICMP_UGT;
10189         RHS = getConstant(RA - 1);
10190         Changed = true;
10191         break;
10192       case ICmpInst::ICMP_ULE:
10193         assert(!RA.isMaxValue() && "Should have been caught earlier!");
10194         Pred = ICmpInst::ICMP_ULT;
10195         RHS = getConstant(RA + 1);
10196         Changed = true;
10197         break;
10198       case ICmpInst::ICMP_SGE:
10199         assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
10200         Pred = ICmpInst::ICMP_SGT;
10201         RHS = getConstant(RA - 1);
10202         Changed = true;
10203         break;
10204       case ICmpInst::ICMP_SLE:
10205         assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
10206         Pred = ICmpInst::ICMP_SLT;
10207         RHS = getConstant(RA + 1);
10208         Changed = true;
10209         break;
10210       }
10211     }
10212   }
10213 
10214   // Check for obvious equality.
10215   if (HasSameValue(LHS, RHS)) {
10216     if (ICmpInst::isTrueWhenEqual(Pred))
10217       return TrivialCase(true);
10218     if (ICmpInst::isFalseWhenEqual(Pred))
10219       return TrivialCase(false);
10220   }
10221 
10222   // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
10223   // adding or subtracting 1 from one of the operands. This can be done for
10224   // one of two reasons:
10225   // 1) The range of the RHS does not include the (signed/unsigned) boundaries
10226   // 2) The loop is finite, with this comparison controlling the exit. Since the
10227   // loop is finite, the bound cannot include the corresponding boundary
10228   // (otherwise it would loop forever).
10229   switch (Pred) {
10230   case ICmpInst::ICMP_SLE:
10231     if (ControllingFiniteLoop || !getSignedRangeMax(RHS).isMaxSignedValue()) {
10232       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
10233                        SCEV::FlagNSW);
10234       Pred = ICmpInst::ICMP_SLT;
10235       Changed = true;
10236     } else if (!getSignedRangeMin(LHS).isMinSignedValue()) {
10237       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
10238                        SCEV::FlagNSW);
10239       Pred = ICmpInst::ICMP_SLT;
10240       Changed = true;
10241     }
10242     break;
10243   case ICmpInst::ICMP_SGE:
10244     if (ControllingFiniteLoop || !getSignedRangeMin(RHS).isMinSignedValue()) {
10245       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
10246                        SCEV::FlagNSW);
10247       Pred = ICmpInst::ICMP_SGT;
10248       Changed = true;
10249     } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) {
10250       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
10251                        SCEV::FlagNSW);
10252       Pred = ICmpInst::ICMP_SGT;
10253       Changed = true;
10254     }
10255     break;
10256   case ICmpInst::ICMP_ULE:
10257     if (ControllingFiniteLoop || !getUnsignedRangeMax(RHS).isMaxValue()) {
10258       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
10259                        SCEV::FlagNUW);
10260       Pred = ICmpInst::ICMP_ULT;
10261       Changed = true;
10262     } else if (!getUnsignedRangeMin(LHS).isMinValue()) {
10263       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
10264       Pred = ICmpInst::ICMP_ULT;
10265       Changed = true;
10266     }
10267     break;
10268   case ICmpInst::ICMP_UGE:
10269     if (ControllingFiniteLoop || !getUnsignedRangeMin(RHS).isMinValue()) {
10270       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
10271       Pred = ICmpInst::ICMP_UGT;
10272       Changed = true;
10273     } else if (!getUnsignedRangeMax(LHS).isMaxValue()) {
10274       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
10275                        SCEV::FlagNUW);
10276       Pred = ICmpInst::ICMP_UGT;
10277       Changed = true;
10278     }
10279     break;
10280   default:
10281     break;
10282   }
10283 
10284   // TODO: More simplifications are possible here.
10285 
10286   // Recursively simplify until we either hit a recursion limit or nothing
10287   // changes.
10288   if (Changed)
10289     return SimplifyICmpOperands(Pred, LHS, RHS, Depth + 1,
10290                                 ControllingFiniteLoop);
10291 
10292   return Changed;
10293 }
10294 
10295 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
10296   return getSignedRangeMax(S).isNegative();
10297 }
10298 
10299 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
10300   return getSignedRangeMin(S).isStrictlyPositive();
10301 }
10302 
10303 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
10304   return !getSignedRangeMin(S).isNegative();
10305 }
10306 
10307 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
10308   return !getSignedRangeMax(S).isStrictlyPositive();
10309 }
10310 
10311 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
10312   return getUnsignedRangeMin(S) != 0;
10313 }
10314 
10315 std::pair<const SCEV *, const SCEV *>
10316 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) {
10317   // Compute SCEV on entry of loop L.
10318   const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this);
10319   if (Start == getCouldNotCompute())
10320     return { Start, Start };
10321   // Compute post increment SCEV for loop L.
10322   const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this);
10323   assert(PostInc != getCouldNotCompute() && "Unexpected could not compute");
10324   return { Start, PostInc };
10325 }
10326 
10327 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred,
10328                                           const SCEV *LHS, const SCEV *RHS) {
10329   // First collect all loops.
10330   SmallPtrSet<const Loop *, 8> LoopsUsed;
10331   getUsedLoops(LHS, LoopsUsed);
10332   getUsedLoops(RHS, LoopsUsed);
10333 
10334   if (LoopsUsed.empty())
10335     return false;
10336 
10337   // Domination relationship must be a linear order on collected loops.
10338 #ifndef NDEBUG
10339   for (auto *L1 : LoopsUsed)
10340     for (auto *L2 : LoopsUsed)
10341       assert((DT.dominates(L1->getHeader(), L2->getHeader()) ||
10342               DT.dominates(L2->getHeader(), L1->getHeader())) &&
10343              "Domination relationship is not a linear order");
10344 #endif
10345 
10346   const Loop *MDL =
10347       *std::max_element(LoopsUsed.begin(), LoopsUsed.end(),
10348                         [&](const Loop *L1, const Loop *L2) {
10349          return DT.properlyDominates(L1->getHeader(), L2->getHeader());
10350        });
10351 
10352   // Get init and post increment value for LHS.
10353   auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS);
10354   // if LHS contains unknown non-invariant SCEV then bail out.
10355   if (SplitLHS.first == getCouldNotCompute())
10356     return false;
10357   assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC");
10358   // Get init and post increment value for RHS.
10359   auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS);
10360   // if RHS contains unknown non-invariant SCEV then bail out.
10361   if (SplitRHS.first == getCouldNotCompute())
10362     return false;
10363   assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC");
10364   // It is possible that init SCEV contains an invariant load but it does
10365   // not dominate MDL and is not available at MDL loop entry, so we should
10366   // check it here.
10367   if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) ||
10368       !isAvailableAtLoopEntry(SplitRHS.first, MDL))
10369     return false;
10370 
10371   // It seems backedge guard check is faster than entry one so in some cases
10372   // it can speed up whole estimation by short circuit
10373   return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second,
10374                                      SplitRHS.second) &&
10375          isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first);
10376 }
10377 
10378 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
10379                                        const SCEV *LHS, const SCEV *RHS) {
10380   // Canonicalize the inputs first.
10381   (void)SimplifyICmpOperands(Pred, LHS, RHS);
10382 
10383   if (isKnownViaInduction(Pred, LHS, RHS))
10384     return true;
10385 
10386   if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
10387     return true;
10388 
10389   // Otherwise see what can be done with some simple reasoning.
10390   return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS);
10391 }
10392 
10393 Optional<bool> ScalarEvolution::evaluatePredicate(ICmpInst::Predicate Pred,
10394                                                   const SCEV *LHS,
10395                                                   const SCEV *RHS) {
10396   if (isKnownPredicate(Pred, LHS, RHS))
10397     return true;
10398   else if (isKnownPredicate(ICmpInst::getInversePredicate(Pred), LHS, RHS))
10399     return false;
10400   return None;
10401 }
10402 
10403 bool ScalarEvolution::isKnownPredicateAt(ICmpInst::Predicate Pred,
10404                                          const SCEV *LHS, const SCEV *RHS,
10405                                          const Instruction *CtxI) {
10406   // TODO: Analyze guards and assumes from Context's block.
10407   return isKnownPredicate(Pred, LHS, RHS) ||
10408          isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS);
10409 }
10410 
10411 Optional<bool> ScalarEvolution::evaluatePredicateAt(ICmpInst::Predicate Pred,
10412                                                     const SCEV *LHS,
10413                                                     const SCEV *RHS,
10414                                                     const Instruction *CtxI) {
10415   Optional<bool> KnownWithoutContext = evaluatePredicate(Pred, LHS, RHS);
10416   if (KnownWithoutContext)
10417     return KnownWithoutContext;
10418 
10419   if (isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS))
10420     return true;
10421   else if (isBasicBlockEntryGuardedByCond(CtxI->getParent(),
10422                                           ICmpInst::getInversePredicate(Pred),
10423                                           LHS, RHS))
10424     return false;
10425   return None;
10426 }
10427 
10428 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred,
10429                                               const SCEVAddRecExpr *LHS,
10430                                               const SCEV *RHS) {
10431   const Loop *L = LHS->getLoop();
10432   return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) &&
10433          isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS);
10434 }
10435 
10436 Optional<ScalarEvolution::MonotonicPredicateType>
10437 ScalarEvolution::getMonotonicPredicateType(const SCEVAddRecExpr *LHS,
10438                                            ICmpInst::Predicate Pred) {
10439   auto Result = getMonotonicPredicateTypeImpl(LHS, Pred);
10440 
10441 #ifndef NDEBUG
10442   // Verify an invariant: inverting the predicate should turn a monotonically
10443   // increasing change to a monotonically decreasing one, and vice versa.
10444   if (Result) {
10445     auto ResultSwapped =
10446         getMonotonicPredicateTypeImpl(LHS, ICmpInst::getSwappedPredicate(Pred));
10447 
10448     assert(ResultSwapped.hasValue() && "should be able to analyze both!");
10449     assert(ResultSwapped.getValue() != Result.getValue() &&
10450            "monotonicity should flip as we flip the predicate");
10451   }
10452 #endif
10453 
10454   return Result;
10455 }
10456 
10457 Optional<ScalarEvolution::MonotonicPredicateType>
10458 ScalarEvolution::getMonotonicPredicateTypeImpl(const SCEVAddRecExpr *LHS,
10459                                                ICmpInst::Predicate Pred) {
10460   // A zero step value for LHS means the induction variable is essentially a
10461   // loop invariant value. We don't really depend on the predicate actually
10462   // flipping from false to true (for increasing predicates, and the other way
10463   // around for decreasing predicates), all we care about is that *if* the
10464   // predicate changes then it only changes from false to true.
10465   //
10466   // A zero step value in itself is not very useful, but there may be places
10467   // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
10468   // as general as possible.
10469 
10470   // Only handle LE/LT/GE/GT predicates.
10471   if (!ICmpInst::isRelational(Pred))
10472     return None;
10473 
10474   bool IsGreater = ICmpInst::isGE(Pred) || ICmpInst::isGT(Pred);
10475   assert((IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) &&
10476          "Should be greater or less!");
10477 
10478   // Check that AR does not wrap.
10479   if (ICmpInst::isUnsigned(Pred)) {
10480     if (!LHS->hasNoUnsignedWrap())
10481       return None;
10482     return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
10483   } else {
10484     assert(ICmpInst::isSigned(Pred) &&
10485            "Relational predicate is either signed or unsigned!");
10486     if (!LHS->hasNoSignedWrap())
10487       return None;
10488 
10489     const SCEV *Step = LHS->getStepRecurrence(*this);
10490 
10491     if (isKnownNonNegative(Step))
10492       return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
10493 
10494     if (isKnownNonPositive(Step))
10495       return !IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
10496 
10497     return None;
10498   }
10499 }
10500 
10501 Optional<ScalarEvolution::LoopInvariantPredicate>
10502 ScalarEvolution::getLoopInvariantPredicate(ICmpInst::Predicate Pred,
10503                                            const SCEV *LHS, const SCEV *RHS,
10504                                            const Loop *L) {
10505 
10506   // If there is a loop-invariant, force it into the RHS, otherwise bail out.
10507   if (!isLoopInvariant(RHS, L)) {
10508     if (!isLoopInvariant(LHS, L))
10509       return None;
10510 
10511     std::swap(LHS, RHS);
10512     Pred = ICmpInst::getSwappedPredicate(Pred);
10513   }
10514 
10515   const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
10516   if (!ArLHS || ArLHS->getLoop() != L)
10517     return None;
10518 
10519   auto MonotonicType = getMonotonicPredicateType(ArLHS, Pred);
10520   if (!MonotonicType)
10521     return None;
10522   // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
10523   // true as the loop iterates, and the backedge is control dependent on
10524   // "ArLHS `Pred` RHS" == true then we can reason as follows:
10525   //
10526   //   * if the predicate was false in the first iteration then the predicate
10527   //     is never evaluated again, since the loop exits without taking the
10528   //     backedge.
10529   //   * if the predicate was true in the first iteration then it will
10530   //     continue to be true for all future iterations since it is
10531   //     monotonically increasing.
10532   //
10533   // For both the above possibilities, we can replace the loop varying
10534   // predicate with its value on the first iteration of the loop (which is
10535   // loop invariant).
10536   //
10537   // A similar reasoning applies for a monotonically decreasing predicate, by
10538   // replacing true with false and false with true in the above two bullets.
10539   bool Increasing = *MonotonicType == ScalarEvolution::MonotonicallyIncreasing;
10540   auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
10541 
10542   if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
10543     return None;
10544 
10545   return ScalarEvolution::LoopInvariantPredicate(Pred, ArLHS->getStart(), RHS);
10546 }
10547 
10548 Optional<ScalarEvolution::LoopInvariantPredicate>
10549 ScalarEvolution::getLoopInvariantExitCondDuringFirstIterations(
10550     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
10551     const Instruction *CtxI, const SCEV *MaxIter) {
10552   // Try to prove the following set of facts:
10553   // - The predicate is monotonic in the iteration space.
10554   // - If the check does not fail on the 1st iteration:
10555   //   - No overflow will happen during first MaxIter iterations;
10556   //   - It will not fail on the MaxIter'th iteration.
10557   // If the check does fail on the 1st iteration, we leave the loop and no
10558   // other checks matter.
10559 
10560   // If there is a loop-invariant, force it into the RHS, otherwise bail out.
10561   if (!isLoopInvariant(RHS, L)) {
10562     if (!isLoopInvariant(LHS, L))
10563       return None;
10564 
10565     std::swap(LHS, RHS);
10566     Pred = ICmpInst::getSwappedPredicate(Pred);
10567   }
10568 
10569   auto *AR = dyn_cast<SCEVAddRecExpr>(LHS);
10570   if (!AR || AR->getLoop() != L)
10571     return None;
10572 
10573   // The predicate must be relational (i.e. <, <=, >=, >).
10574   if (!ICmpInst::isRelational(Pred))
10575     return None;
10576 
10577   // TODO: Support steps other than +/- 1.
10578   const SCEV *Step = AR->getStepRecurrence(*this);
10579   auto *One = getOne(Step->getType());
10580   auto *MinusOne = getNegativeSCEV(One);
10581   if (Step != One && Step != MinusOne)
10582     return None;
10583 
10584   // Type mismatch here means that MaxIter is potentially larger than max
10585   // unsigned value in start type, which mean we cannot prove no wrap for the
10586   // indvar.
10587   if (AR->getType() != MaxIter->getType())
10588     return None;
10589 
10590   // Value of IV on suggested last iteration.
10591   const SCEV *Last = AR->evaluateAtIteration(MaxIter, *this);
10592   // Does it still meet the requirement?
10593   if (!isLoopBackedgeGuardedByCond(L, Pred, Last, RHS))
10594     return None;
10595   // Because step is +/- 1 and MaxIter has same type as Start (i.e. it does
10596   // not exceed max unsigned value of this type), this effectively proves
10597   // that there is no wrap during the iteration. To prove that there is no
10598   // signed/unsigned wrap, we need to check that
10599   // Start <= Last for step = 1 or Start >= Last for step = -1.
10600   ICmpInst::Predicate NoOverflowPred =
10601       CmpInst::isSigned(Pred) ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
10602   if (Step == MinusOne)
10603     NoOverflowPred = CmpInst::getSwappedPredicate(NoOverflowPred);
10604   const SCEV *Start = AR->getStart();
10605   if (!isKnownPredicateAt(NoOverflowPred, Start, Last, CtxI))
10606     return None;
10607 
10608   // Everything is fine.
10609   return ScalarEvolution::LoopInvariantPredicate(Pred, Start, RHS);
10610 }
10611 
10612 bool ScalarEvolution::isKnownPredicateViaConstantRanges(
10613     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
10614   if (HasSameValue(LHS, RHS))
10615     return ICmpInst::isTrueWhenEqual(Pred);
10616 
10617   // This code is split out from isKnownPredicate because it is called from
10618   // within isLoopEntryGuardedByCond.
10619 
10620   auto CheckRanges = [&](const ConstantRange &RangeLHS,
10621                          const ConstantRange &RangeRHS) {
10622     return RangeLHS.icmp(Pred, RangeRHS);
10623   };
10624 
10625   // The check at the top of the function catches the case where the values are
10626   // known to be equal.
10627   if (Pred == CmpInst::ICMP_EQ)
10628     return false;
10629 
10630   if (Pred == CmpInst::ICMP_NE) {
10631     if (CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) ||
10632         CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)))
10633       return true;
10634     auto *Diff = getMinusSCEV(LHS, RHS);
10635     return !isa<SCEVCouldNotCompute>(Diff) && isKnownNonZero(Diff);
10636   }
10637 
10638   if (CmpInst::isSigned(Pred))
10639     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS));
10640 
10641   return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS));
10642 }
10643 
10644 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
10645                                                     const SCEV *LHS,
10646                                                     const SCEV *RHS) {
10647   // Match X to (A + C1)<ExpectedFlags> and Y to (A + C2)<ExpectedFlags>, where
10648   // C1 and C2 are constant integers. If either X or Y are not add expressions,
10649   // consider them as X + 0 and Y + 0 respectively. C1 and C2 are returned via
10650   // OutC1 and OutC2.
10651   auto MatchBinaryAddToConst = [this](const SCEV *X, const SCEV *Y,
10652                                       APInt &OutC1, APInt &OutC2,
10653                                       SCEV::NoWrapFlags ExpectedFlags) {
10654     const SCEV *XNonConstOp, *XConstOp;
10655     const SCEV *YNonConstOp, *YConstOp;
10656     SCEV::NoWrapFlags XFlagsPresent;
10657     SCEV::NoWrapFlags YFlagsPresent;
10658 
10659     if (!splitBinaryAdd(X, XConstOp, XNonConstOp, XFlagsPresent)) {
10660       XConstOp = getZero(X->getType());
10661       XNonConstOp = X;
10662       XFlagsPresent = ExpectedFlags;
10663     }
10664     if (!isa<SCEVConstant>(XConstOp) ||
10665         (XFlagsPresent & ExpectedFlags) != ExpectedFlags)
10666       return false;
10667 
10668     if (!splitBinaryAdd(Y, YConstOp, YNonConstOp, YFlagsPresent)) {
10669       YConstOp = getZero(Y->getType());
10670       YNonConstOp = Y;
10671       YFlagsPresent = ExpectedFlags;
10672     }
10673 
10674     if (!isa<SCEVConstant>(YConstOp) ||
10675         (YFlagsPresent & ExpectedFlags) != ExpectedFlags)
10676       return false;
10677 
10678     if (YNonConstOp != XNonConstOp)
10679       return false;
10680 
10681     OutC1 = cast<SCEVConstant>(XConstOp)->getAPInt();
10682     OutC2 = cast<SCEVConstant>(YConstOp)->getAPInt();
10683 
10684     return true;
10685   };
10686 
10687   APInt C1;
10688   APInt C2;
10689 
10690   switch (Pred) {
10691   default:
10692     break;
10693 
10694   case ICmpInst::ICMP_SGE:
10695     std::swap(LHS, RHS);
10696     LLVM_FALLTHROUGH;
10697   case ICmpInst::ICMP_SLE:
10698     // (X + C1)<nsw> s<= (X + C2)<nsw> if C1 s<= C2.
10699     if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.sle(C2))
10700       return true;
10701 
10702     break;
10703 
10704   case ICmpInst::ICMP_SGT:
10705     std::swap(LHS, RHS);
10706     LLVM_FALLTHROUGH;
10707   case ICmpInst::ICMP_SLT:
10708     // (X + C1)<nsw> s< (X + C2)<nsw> if C1 s< C2.
10709     if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.slt(C2))
10710       return true;
10711 
10712     break;
10713 
10714   case ICmpInst::ICMP_UGE:
10715     std::swap(LHS, RHS);
10716     LLVM_FALLTHROUGH;
10717   case ICmpInst::ICMP_ULE:
10718     // (X + C1)<nuw> u<= (X + C2)<nuw> for C1 u<= C2.
10719     if (MatchBinaryAddToConst(RHS, LHS, C2, C1, SCEV::FlagNUW) && C1.ule(C2))
10720       return true;
10721 
10722     break;
10723 
10724   case ICmpInst::ICMP_UGT:
10725     std::swap(LHS, RHS);
10726     LLVM_FALLTHROUGH;
10727   case ICmpInst::ICMP_ULT:
10728     // (X + C1)<nuw> u< (X + C2)<nuw> if C1 u< C2.
10729     if (MatchBinaryAddToConst(RHS, LHS, C2, C1, SCEV::FlagNUW) && C1.ult(C2))
10730       return true;
10731     break;
10732   }
10733 
10734   return false;
10735 }
10736 
10737 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
10738                                                    const SCEV *LHS,
10739                                                    const SCEV *RHS) {
10740   if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
10741     return false;
10742 
10743   // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
10744   // the stack can result in exponential time complexity.
10745   SaveAndRestore<bool> Restore(ProvingSplitPredicate, true);
10746 
10747   // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
10748   //
10749   // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
10750   // isKnownPredicate.  isKnownPredicate is more powerful, but also more
10751   // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
10752   // interesting cases seen in practice.  We can consider "upgrading" L >= 0 to
10753   // use isKnownPredicate later if needed.
10754   return isKnownNonNegative(RHS) &&
10755          isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
10756          isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
10757 }
10758 
10759 bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB,
10760                                         ICmpInst::Predicate Pred,
10761                                         const SCEV *LHS, const SCEV *RHS) {
10762   // No need to even try if we know the module has no guards.
10763   if (!HasGuards)
10764     return false;
10765 
10766   return any_of(*BB, [&](const Instruction &I) {
10767     using namespace llvm::PatternMatch;
10768 
10769     Value *Condition;
10770     return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
10771                          m_Value(Condition))) &&
10772            isImpliedCond(Pred, LHS, RHS, Condition, false);
10773   });
10774 }
10775 
10776 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
10777 /// protected by a conditional between LHS and RHS.  This is used to
10778 /// to eliminate casts.
10779 bool
10780 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
10781                                              ICmpInst::Predicate Pred,
10782                                              const SCEV *LHS, const SCEV *RHS) {
10783   // Interpret a null as meaning no loop, where there is obviously no guard
10784   // (interprocedural conditions notwithstanding).
10785   if (!L) return true;
10786 
10787   if (VerifyIR)
10788     assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) &&
10789            "This cannot be done on broken IR!");
10790 
10791 
10792   if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
10793     return true;
10794 
10795   BasicBlock *Latch = L->getLoopLatch();
10796   if (!Latch)
10797     return false;
10798 
10799   BranchInst *LoopContinuePredicate =
10800     dyn_cast<BranchInst>(Latch->getTerminator());
10801   if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
10802       isImpliedCond(Pred, LHS, RHS,
10803                     LoopContinuePredicate->getCondition(),
10804                     LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
10805     return true;
10806 
10807   // We don't want more than one activation of the following loops on the stack
10808   // -- that can lead to O(n!) time complexity.
10809   if (WalkingBEDominatingConds)
10810     return false;
10811 
10812   SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true);
10813 
10814   // See if we can exploit a trip count to prove the predicate.
10815   const auto &BETakenInfo = getBackedgeTakenInfo(L);
10816   const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
10817   if (LatchBECount != getCouldNotCompute()) {
10818     // We know that Latch branches back to the loop header exactly
10819     // LatchBECount times.  This means the backdege condition at Latch is
10820     // equivalent to  "{0,+,1} u< LatchBECount".
10821     Type *Ty = LatchBECount->getType();
10822     auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
10823     const SCEV *LoopCounter =
10824       getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
10825     if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
10826                       LatchBECount))
10827       return true;
10828   }
10829 
10830   // Check conditions due to any @llvm.assume intrinsics.
10831   for (auto &AssumeVH : AC.assumptions()) {
10832     if (!AssumeVH)
10833       continue;
10834     auto *CI = cast<CallInst>(AssumeVH);
10835     if (!DT.dominates(CI, Latch->getTerminator()))
10836       continue;
10837 
10838     if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
10839       return true;
10840   }
10841 
10842   // If the loop is not reachable from the entry block, we risk running into an
10843   // infinite loop as we walk up into the dom tree.  These loops do not matter
10844   // anyway, so we just return a conservative answer when we see them.
10845   if (!DT.isReachableFromEntry(L->getHeader()))
10846     return false;
10847 
10848   if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
10849     return true;
10850 
10851   for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
10852        DTN != HeaderDTN; DTN = DTN->getIDom()) {
10853     assert(DTN && "should reach the loop header before reaching the root!");
10854 
10855     BasicBlock *BB = DTN->getBlock();
10856     if (isImpliedViaGuard(BB, Pred, LHS, RHS))
10857       return true;
10858 
10859     BasicBlock *PBB = BB->getSinglePredecessor();
10860     if (!PBB)
10861       continue;
10862 
10863     BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
10864     if (!ContinuePredicate || !ContinuePredicate->isConditional())
10865       continue;
10866 
10867     Value *Condition = ContinuePredicate->getCondition();
10868 
10869     // If we have an edge `E` within the loop body that dominates the only
10870     // latch, the condition guarding `E` also guards the backedge.  This
10871     // reasoning works only for loops with a single latch.
10872 
10873     BasicBlockEdge DominatingEdge(PBB, BB);
10874     if (DominatingEdge.isSingleEdge()) {
10875       // We're constructively (and conservatively) enumerating edges within the
10876       // loop body that dominate the latch.  The dominator tree better agree
10877       // with us on this:
10878       assert(DT.dominates(DominatingEdge, Latch) && "should be!");
10879 
10880       if (isImpliedCond(Pred, LHS, RHS, Condition,
10881                         BB != ContinuePredicate->getSuccessor(0)))
10882         return true;
10883     }
10884   }
10885 
10886   return false;
10887 }
10888 
10889 bool ScalarEvolution::isBasicBlockEntryGuardedByCond(const BasicBlock *BB,
10890                                                      ICmpInst::Predicate Pred,
10891                                                      const SCEV *LHS,
10892                                                      const SCEV *RHS) {
10893   if (VerifyIR)
10894     assert(!verifyFunction(*BB->getParent(), &dbgs()) &&
10895            "This cannot be done on broken IR!");
10896 
10897   // If we cannot prove strict comparison (e.g. a > b), maybe we can prove
10898   // the facts (a >= b && a != b) separately. A typical situation is when the
10899   // non-strict comparison is known from ranges and non-equality is known from
10900   // dominating predicates. If we are proving strict comparison, we always try
10901   // to prove non-equality and non-strict comparison separately.
10902   auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred);
10903   const bool ProvingStrictComparison = (Pred != NonStrictPredicate);
10904   bool ProvedNonStrictComparison = false;
10905   bool ProvedNonEquality = false;
10906 
10907   auto SplitAndProve =
10908     [&](std::function<bool(ICmpInst::Predicate)> Fn) -> bool {
10909     if (!ProvedNonStrictComparison)
10910       ProvedNonStrictComparison = Fn(NonStrictPredicate);
10911     if (!ProvedNonEquality)
10912       ProvedNonEquality = Fn(ICmpInst::ICMP_NE);
10913     if (ProvedNonStrictComparison && ProvedNonEquality)
10914       return true;
10915     return false;
10916   };
10917 
10918   if (ProvingStrictComparison) {
10919     auto ProofFn = [&](ICmpInst::Predicate P) {
10920       return isKnownViaNonRecursiveReasoning(P, LHS, RHS);
10921     };
10922     if (SplitAndProve(ProofFn))
10923       return true;
10924   }
10925 
10926   // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard.
10927   auto ProveViaGuard = [&](const BasicBlock *Block) {
10928     if (isImpliedViaGuard(Block, Pred, LHS, RHS))
10929       return true;
10930     if (ProvingStrictComparison) {
10931       auto ProofFn = [&](ICmpInst::Predicate P) {
10932         return isImpliedViaGuard(Block, P, LHS, RHS);
10933       };
10934       if (SplitAndProve(ProofFn))
10935         return true;
10936     }
10937     return false;
10938   };
10939 
10940   // Try to prove (Pred, LHS, RHS) using isImpliedCond.
10941   auto ProveViaCond = [&](const Value *Condition, bool Inverse) {
10942     const Instruction *CtxI = &BB->front();
10943     if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse, CtxI))
10944       return true;
10945     if (ProvingStrictComparison) {
10946       auto ProofFn = [&](ICmpInst::Predicate P) {
10947         return isImpliedCond(P, LHS, RHS, Condition, Inverse, CtxI);
10948       };
10949       if (SplitAndProve(ProofFn))
10950         return true;
10951     }
10952     return false;
10953   };
10954 
10955   // Starting at the block's predecessor, climb up the predecessor chain, as long
10956   // as there are predecessors that can be found that have unique successors
10957   // leading to the original block.
10958   const Loop *ContainingLoop = LI.getLoopFor(BB);
10959   const BasicBlock *PredBB;
10960   if (ContainingLoop && ContainingLoop->getHeader() == BB)
10961     PredBB = ContainingLoop->getLoopPredecessor();
10962   else
10963     PredBB = BB->getSinglePredecessor();
10964   for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB);
10965        Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
10966     if (ProveViaGuard(Pair.first))
10967       return true;
10968 
10969     const BranchInst *LoopEntryPredicate =
10970         dyn_cast<BranchInst>(Pair.first->getTerminator());
10971     if (!LoopEntryPredicate ||
10972         LoopEntryPredicate->isUnconditional())
10973       continue;
10974 
10975     if (ProveViaCond(LoopEntryPredicate->getCondition(),
10976                      LoopEntryPredicate->getSuccessor(0) != Pair.second))
10977       return true;
10978   }
10979 
10980   // Check conditions due to any @llvm.assume intrinsics.
10981   for (auto &AssumeVH : AC.assumptions()) {
10982     if (!AssumeVH)
10983       continue;
10984     auto *CI = cast<CallInst>(AssumeVH);
10985     if (!DT.dominates(CI, BB))
10986       continue;
10987 
10988     if (ProveViaCond(CI->getArgOperand(0), false))
10989       return true;
10990   }
10991 
10992   return false;
10993 }
10994 
10995 bool ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
10996                                                ICmpInst::Predicate Pred,
10997                                                const SCEV *LHS,
10998                                                const SCEV *RHS) {
10999   // Interpret a null as meaning no loop, where there is obviously no guard
11000   // (interprocedural conditions notwithstanding).
11001   if (!L)
11002     return false;
11003 
11004   // Both LHS and RHS must be available at loop entry.
11005   assert(isAvailableAtLoopEntry(LHS, L) &&
11006          "LHS is not available at Loop Entry");
11007   assert(isAvailableAtLoopEntry(RHS, L) &&
11008          "RHS is not available at Loop Entry");
11009 
11010   if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
11011     return true;
11012 
11013   return isBasicBlockEntryGuardedByCond(L->getHeader(), Pred, LHS, RHS);
11014 }
11015 
11016 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
11017                                     const SCEV *RHS,
11018                                     const Value *FoundCondValue, bool Inverse,
11019                                     const Instruction *CtxI) {
11020   // False conditions implies anything. Do not bother analyzing it further.
11021   if (FoundCondValue ==
11022       ConstantInt::getBool(FoundCondValue->getContext(), Inverse))
11023     return true;
11024 
11025   if (!PendingLoopPredicates.insert(FoundCondValue).second)
11026     return false;
11027 
11028   auto ClearOnExit =
11029       make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
11030 
11031   // Recursively handle And and Or conditions.
11032   const Value *Op0, *Op1;
11033   if (match(FoundCondValue, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
11034     if (!Inverse)
11035       return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) ||
11036              isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI);
11037   } else if (match(FoundCondValue, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) {
11038     if (Inverse)
11039       return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) ||
11040              isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI);
11041   }
11042 
11043   const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
11044   if (!ICI) return false;
11045 
11046   // Now that we found a conditional branch that dominates the loop or controls
11047   // the loop latch. Check to see if it is the comparison we are looking for.
11048   ICmpInst::Predicate FoundPred;
11049   if (Inverse)
11050     FoundPred = ICI->getInversePredicate();
11051   else
11052     FoundPred = ICI->getPredicate();
11053 
11054   const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
11055   const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
11056 
11057   return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, CtxI);
11058 }
11059 
11060 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
11061                                     const SCEV *RHS,
11062                                     ICmpInst::Predicate FoundPred,
11063                                     const SCEV *FoundLHS, const SCEV *FoundRHS,
11064                                     const Instruction *CtxI) {
11065   // Balance the types.
11066   if (getTypeSizeInBits(LHS->getType()) <
11067       getTypeSizeInBits(FoundLHS->getType())) {
11068     // For unsigned and equality predicates, try to prove that both found
11069     // operands fit into narrow unsigned range. If so, try to prove facts in
11070     // narrow types.
11071     if (!CmpInst::isSigned(FoundPred) && !FoundLHS->getType()->isPointerTy() &&
11072         !FoundRHS->getType()->isPointerTy()) {
11073       auto *NarrowType = LHS->getType();
11074       auto *WideType = FoundLHS->getType();
11075       auto BitWidth = getTypeSizeInBits(NarrowType);
11076       const SCEV *MaxValue = getZeroExtendExpr(
11077           getConstant(APInt::getMaxValue(BitWidth)), WideType);
11078       if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundLHS,
11079                                           MaxValue) &&
11080           isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundRHS,
11081                                           MaxValue)) {
11082         const SCEV *TruncFoundLHS = getTruncateExpr(FoundLHS, NarrowType);
11083         const SCEV *TruncFoundRHS = getTruncateExpr(FoundRHS, NarrowType);
11084         if (isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, TruncFoundLHS,
11085                                        TruncFoundRHS, CtxI))
11086           return true;
11087       }
11088     }
11089 
11090     if (LHS->getType()->isPointerTy() || RHS->getType()->isPointerTy())
11091       return false;
11092     if (CmpInst::isSigned(Pred)) {
11093       LHS = getSignExtendExpr(LHS, FoundLHS->getType());
11094       RHS = getSignExtendExpr(RHS, FoundLHS->getType());
11095     } else {
11096       LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
11097       RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
11098     }
11099   } else if (getTypeSizeInBits(LHS->getType()) >
11100       getTypeSizeInBits(FoundLHS->getType())) {
11101     if (FoundLHS->getType()->isPointerTy() || FoundRHS->getType()->isPointerTy())
11102       return false;
11103     if (CmpInst::isSigned(FoundPred)) {
11104       FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
11105       FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
11106     } else {
11107       FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
11108       FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
11109     }
11110   }
11111   return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS,
11112                                     FoundRHS, CtxI);
11113 }
11114 
11115 bool ScalarEvolution::isImpliedCondBalancedTypes(
11116     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
11117     ICmpInst::Predicate FoundPred, const SCEV *FoundLHS, const SCEV *FoundRHS,
11118     const Instruction *CtxI) {
11119   assert(getTypeSizeInBits(LHS->getType()) ==
11120              getTypeSizeInBits(FoundLHS->getType()) &&
11121          "Types should be balanced!");
11122   // Canonicalize the query to match the way instcombine will have
11123   // canonicalized the comparison.
11124   if (SimplifyICmpOperands(Pred, LHS, RHS))
11125     if (LHS == RHS)
11126       return CmpInst::isTrueWhenEqual(Pred);
11127   if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
11128     if (FoundLHS == FoundRHS)
11129       return CmpInst::isFalseWhenEqual(FoundPred);
11130 
11131   // Check to see if we can make the LHS or RHS match.
11132   if (LHS == FoundRHS || RHS == FoundLHS) {
11133     if (isa<SCEVConstant>(RHS)) {
11134       std::swap(FoundLHS, FoundRHS);
11135       FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
11136     } else {
11137       std::swap(LHS, RHS);
11138       Pred = ICmpInst::getSwappedPredicate(Pred);
11139     }
11140   }
11141 
11142   // Check whether the found predicate is the same as the desired predicate.
11143   if (FoundPred == Pred)
11144     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI);
11145 
11146   // Check whether swapping the found predicate makes it the same as the
11147   // desired predicate.
11148   if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
11149     // We can write the implication
11150     // 0.  LHS Pred      RHS  <-   FoundLHS SwapPred  FoundRHS
11151     // using one of the following ways:
11152     // 1.  LHS Pred      RHS  <-   FoundRHS Pred      FoundLHS
11153     // 2.  RHS SwapPred  LHS  <-   FoundLHS SwapPred  FoundRHS
11154     // 3.  LHS Pred      RHS  <-  ~FoundLHS Pred     ~FoundRHS
11155     // 4. ~LHS SwapPred ~RHS  <-   FoundLHS SwapPred  FoundRHS
11156     // Forms 1. and 2. require swapping the operands of one condition. Don't
11157     // do this if it would break canonical constant/addrec ordering.
11158     if (!isa<SCEVConstant>(RHS) && !isa<SCEVAddRecExpr>(LHS))
11159       return isImpliedCondOperands(FoundPred, RHS, LHS, FoundLHS, FoundRHS,
11160                                    CtxI);
11161     if (!isa<SCEVConstant>(FoundRHS) && !isa<SCEVAddRecExpr>(FoundLHS))
11162       return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS, CtxI);
11163 
11164     // There's no clear preference between forms 3. and 4., try both.  Avoid
11165     // forming getNotSCEV of pointer values as the resulting subtract is
11166     // not legal.
11167     if (!LHS->getType()->isPointerTy() && !RHS->getType()->isPointerTy() &&
11168         isImpliedCondOperands(FoundPred, getNotSCEV(LHS), getNotSCEV(RHS),
11169                               FoundLHS, FoundRHS, CtxI))
11170       return true;
11171 
11172     if (!FoundLHS->getType()->isPointerTy() &&
11173         !FoundRHS->getType()->isPointerTy() &&
11174         isImpliedCondOperands(Pred, LHS, RHS, getNotSCEV(FoundLHS),
11175                               getNotSCEV(FoundRHS), CtxI))
11176       return true;
11177 
11178     return false;
11179   }
11180 
11181   auto IsSignFlippedPredicate = [](CmpInst::Predicate P1,
11182                                    CmpInst::Predicate P2) {
11183     assert(P1 != P2 && "Handled earlier!");
11184     return CmpInst::isRelational(P2) &&
11185            P1 == CmpInst::getFlippedSignednessPredicate(P2);
11186   };
11187   if (IsSignFlippedPredicate(Pred, FoundPred)) {
11188     // Unsigned comparison is the same as signed comparison when both the
11189     // operands are non-negative or negative.
11190     if ((isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) ||
11191         (isKnownNegative(FoundLHS) && isKnownNegative(FoundRHS)))
11192       return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI);
11193     // Create local copies that we can freely swap and canonicalize our
11194     // conditions to "le/lt".
11195     ICmpInst::Predicate CanonicalPred = Pred, CanonicalFoundPred = FoundPred;
11196     const SCEV *CanonicalLHS = LHS, *CanonicalRHS = RHS,
11197                *CanonicalFoundLHS = FoundLHS, *CanonicalFoundRHS = FoundRHS;
11198     if (ICmpInst::isGT(CanonicalPred) || ICmpInst::isGE(CanonicalPred)) {
11199       CanonicalPred = ICmpInst::getSwappedPredicate(CanonicalPred);
11200       CanonicalFoundPred = ICmpInst::getSwappedPredicate(CanonicalFoundPred);
11201       std::swap(CanonicalLHS, CanonicalRHS);
11202       std::swap(CanonicalFoundLHS, CanonicalFoundRHS);
11203     }
11204     assert((ICmpInst::isLT(CanonicalPred) || ICmpInst::isLE(CanonicalPred)) &&
11205            "Must be!");
11206     assert((ICmpInst::isLT(CanonicalFoundPred) ||
11207             ICmpInst::isLE(CanonicalFoundPred)) &&
11208            "Must be!");
11209     if (ICmpInst::isSigned(CanonicalPred) && isKnownNonNegative(CanonicalRHS))
11210       // Use implication:
11211       // x <u y && y >=s 0 --> x <s y.
11212       // If we can prove the left part, the right part is also proven.
11213       return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS,
11214                                    CanonicalRHS, CanonicalFoundLHS,
11215                                    CanonicalFoundRHS);
11216     if (ICmpInst::isUnsigned(CanonicalPred) && isKnownNegative(CanonicalRHS))
11217       // Use implication:
11218       // x <s y && y <s 0 --> x <u y.
11219       // If we can prove the left part, the right part is also proven.
11220       return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS,
11221                                    CanonicalRHS, CanonicalFoundLHS,
11222                                    CanonicalFoundRHS);
11223   }
11224 
11225   // Check if we can make progress by sharpening ranges.
11226   if (FoundPred == ICmpInst::ICMP_NE &&
11227       (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
11228 
11229     const SCEVConstant *C = nullptr;
11230     const SCEV *V = nullptr;
11231 
11232     if (isa<SCEVConstant>(FoundLHS)) {
11233       C = cast<SCEVConstant>(FoundLHS);
11234       V = FoundRHS;
11235     } else {
11236       C = cast<SCEVConstant>(FoundRHS);
11237       V = FoundLHS;
11238     }
11239 
11240     // The guarding predicate tells us that C != V. If the known range
11241     // of V is [C, t), we can sharpen the range to [C + 1, t).  The
11242     // range we consider has to correspond to same signedness as the
11243     // predicate we're interested in folding.
11244 
11245     APInt Min = ICmpInst::isSigned(Pred) ?
11246         getSignedRangeMin(V) : getUnsignedRangeMin(V);
11247 
11248     if (Min == C->getAPInt()) {
11249       // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
11250       // This is true even if (Min + 1) wraps around -- in case of
11251       // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
11252 
11253       APInt SharperMin = Min + 1;
11254 
11255       switch (Pred) {
11256         case ICmpInst::ICMP_SGE:
11257         case ICmpInst::ICMP_UGE:
11258           // We know V `Pred` SharperMin.  If this implies LHS `Pred`
11259           // RHS, we're done.
11260           if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(SharperMin),
11261                                     CtxI))
11262             return true;
11263           LLVM_FALLTHROUGH;
11264 
11265         case ICmpInst::ICMP_SGT:
11266         case ICmpInst::ICMP_UGT:
11267           // We know from the range information that (V `Pred` Min ||
11268           // V == Min).  We know from the guarding condition that !(V
11269           // == Min).  This gives us
11270           //
11271           //       V `Pred` Min || V == Min && !(V == Min)
11272           //   =>  V `Pred` Min
11273           //
11274           // If V `Pred` Min implies LHS `Pred` RHS, we're done.
11275 
11276           if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min), CtxI))
11277             return true;
11278           break;
11279 
11280         // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively.
11281         case ICmpInst::ICMP_SLE:
11282         case ICmpInst::ICMP_ULE:
11283           if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS,
11284                                     LHS, V, getConstant(SharperMin), CtxI))
11285             return true;
11286           LLVM_FALLTHROUGH;
11287 
11288         case ICmpInst::ICMP_SLT:
11289         case ICmpInst::ICMP_ULT:
11290           if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS,
11291                                     LHS, V, getConstant(Min), CtxI))
11292             return true;
11293           break;
11294 
11295         default:
11296           // No change
11297           break;
11298       }
11299     }
11300   }
11301 
11302   // Check whether the actual condition is beyond sufficient.
11303   if (FoundPred == ICmpInst::ICMP_EQ)
11304     if (ICmpInst::isTrueWhenEqual(Pred))
11305       if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
11306         return true;
11307   if (Pred == ICmpInst::ICMP_NE)
11308     if (!ICmpInst::isTrueWhenEqual(FoundPred))
11309       if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
11310         return true;
11311 
11312   // Otherwise assume the worst.
11313   return false;
11314 }
11315 
11316 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
11317                                      const SCEV *&L, const SCEV *&R,
11318                                      SCEV::NoWrapFlags &Flags) {
11319   const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
11320   if (!AE || AE->getNumOperands() != 2)
11321     return false;
11322 
11323   L = AE->getOperand(0);
11324   R = AE->getOperand(1);
11325   Flags = AE->getNoWrapFlags();
11326   return true;
11327 }
11328 
11329 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More,
11330                                                            const SCEV *Less) {
11331   // We avoid subtracting expressions here because this function is usually
11332   // fairly deep in the call stack (i.e. is called many times).
11333 
11334   // X - X = 0.
11335   if (More == Less)
11336     return APInt(getTypeSizeInBits(More->getType()), 0);
11337 
11338   if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
11339     const auto *LAR = cast<SCEVAddRecExpr>(Less);
11340     const auto *MAR = cast<SCEVAddRecExpr>(More);
11341 
11342     if (LAR->getLoop() != MAR->getLoop())
11343       return None;
11344 
11345     // We look at affine expressions only; not for correctness but to keep
11346     // getStepRecurrence cheap.
11347     if (!LAR->isAffine() || !MAR->isAffine())
11348       return None;
11349 
11350     if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
11351       return None;
11352 
11353     Less = LAR->getStart();
11354     More = MAR->getStart();
11355 
11356     // fall through
11357   }
11358 
11359   if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
11360     const auto &M = cast<SCEVConstant>(More)->getAPInt();
11361     const auto &L = cast<SCEVConstant>(Less)->getAPInt();
11362     return M - L;
11363   }
11364 
11365   SCEV::NoWrapFlags Flags;
11366   const SCEV *LLess = nullptr, *RLess = nullptr;
11367   const SCEV *LMore = nullptr, *RMore = nullptr;
11368   const SCEVConstant *C1 = nullptr, *C2 = nullptr;
11369   // Compare (X + C1) vs X.
11370   if (splitBinaryAdd(Less, LLess, RLess, Flags))
11371     if ((C1 = dyn_cast<SCEVConstant>(LLess)))
11372       if (RLess == More)
11373         return -(C1->getAPInt());
11374 
11375   // Compare X vs (X + C2).
11376   if (splitBinaryAdd(More, LMore, RMore, Flags))
11377     if ((C2 = dyn_cast<SCEVConstant>(LMore)))
11378       if (RMore == Less)
11379         return C2->getAPInt();
11380 
11381   // Compare (X + C1) vs (X + C2).
11382   if (C1 && C2 && RLess == RMore)
11383     return C2->getAPInt() - C1->getAPInt();
11384 
11385   return None;
11386 }
11387 
11388 bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart(
11389     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
11390     const SCEV *FoundLHS, const SCEV *FoundRHS, const Instruction *CtxI) {
11391   // Try to recognize the following pattern:
11392   //
11393   //   FoundRHS = ...
11394   // ...
11395   // loop:
11396   //   FoundLHS = {Start,+,W}
11397   // context_bb: // Basic block from the same loop
11398   //   known(Pred, FoundLHS, FoundRHS)
11399   //
11400   // If some predicate is known in the context of a loop, it is also known on
11401   // each iteration of this loop, including the first iteration. Therefore, in
11402   // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to
11403   // prove the original pred using this fact.
11404   if (!CtxI)
11405     return false;
11406   const BasicBlock *ContextBB = CtxI->getParent();
11407   // Make sure AR varies in the context block.
11408   if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) {
11409     const Loop *L = AR->getLoop();
11410     // Make sure that context belongs to the loop and executes on 1st iteration
11411     // (if it ever executes at all).
11412     if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch()))
11413       return false;
11414     if (!isAvailableAtLoopEntry(FoundRHS, AR->getLoop()))
11415       return false;
11416     return isImpliedCondOperands(Pred, LHS, RHS, AR->getStart(), FoundRHS);
11417   }
11418 
11419   if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) {
11420     const Loop *L = AR->getLoop();
11421     // Make sure that context belongs to the loop and executes on 1st iteration
11422     // (if it ever executes at all).
11423     if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch()))
11424       return false;
11425     if (!isAvailableAtLoopEntry(FoundLHS, AR->getLoop()))
11426       return false;
11427     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->getStart());
11428   }
11429 
11430   return false;
11431 }
11432 
11433 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
11434     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
11435     const SCEV *FoundLHS, const SCEV *FoundRHS) {
11436   if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
11437     return false;
11438 
11439   const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
11440   if (!AddRecLHS)
11441     return false;
11442 
11443   const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
11444   if (!AddRecFoundLHS)
11445     return false;
11446 
11447   // We'd like to let SCEV reason about control dependencies, so we constrain
11448   // both the inequalities to be about add recurrences on the same loop.  This
11449   // way we can use isLoopEntryGuardedByCond later.
11450 
11451   const Loop *L = AddRecFoundLHS->getLoop();
11452   if (L != AddRecLHS->getLoop())
11453     return false;
11454 
11455   //  FoundLHS u< FoundRHS u< -C =>  (FoundLHS + C) u< (FoundRHS + C) ... (1)
11456   //
11457   //  FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
11458   //                                                                  ... (2)
11459   //
11460   // Informal proof for (2), assuming (1) [*]:
11461   //
11462   // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
11463   //
11464   // Then
11465   //
11466   //       FoundLHS s< FoundRHS s< INT_MIN - C
11467   // <=>  (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C   [ using (3) ]
11468   // <=>  (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
11469   // <=>  (FoundLHS + INT_MIN + C + INT_MIN) s<
11470   //                        (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
11471   // <=>  FoundLHS + C s< FoundRHS + C
11472   //
11473   // [*]: (1) can be proved by ruling out overflow.
11474   //
11475   // [**]: This can be proved by analyzing all the four possibilities:
11476   //    (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
11477   //    (A s>= 0, B s>= 0).
11478   //
11479   // Note:
11480   // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
11481   // will not sign underflow.  For instance, say FoundLHS = (i8 -128), FoundRHS
11482   // = (i8 -127) and C = (i8 -100).  Then INT_MIN - C = (i8 -28), and FoundRHS
11483   // s< (INT_MIN - C).  Lack of sign overflow / underflow in "FoundRHS + C" is
11484   // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
11485   // C)".
11486 
11487   Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
11488   Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
11489   if (!LDiff || !RDiff || *LDiff != *RDiff)
11490     return false;
11491 
11492   if (LDiff->isMinValue())
11493     return true;
11494 
11495   APInt FoundRHSLimit;
11496 
11497   if (Pred == CmpInst::ICMP_ULT) {
11498     FoundRHSLimit = -(*RDiff);
11499   } else {
11500     assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
11501     FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
11502   }
11503 
11504   // Try to prove (1) or (2), as needed.
11505   return isAvailableAtLoopEntry(FoundRHS, L) &&
11506          isLoopEntryGuardedByCond(L, Pred, FoundRHS,
11507                                   getConstant(FoundRHSLimit));
11508 }
11509 
11510 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred,
11511                                         const SCEV *LHS, const SCEV *RHS,
11512                                         const SCEV *FoundLHS,
11513                                         const SCEV *FoundRHS, unsigned Depth) {
11514   const PHINode *LPhi = nullptr, *RPhi = nullptr;
11515 
11516   auto ClearOnExit = make_scope_exit([&]() {
11517     if (LPhi) {
11518       bool Erased = PendingMerges.erase(LPhi);
11519       assert(Erased && "Failed to erase LPhi!");
11520       (void)Erased;
11521     }
11522     if (RPhi) {
11523       bool Erased = PendingMerges.erase(RPhi);
11524       assert(Erased && "Failed to erase RPhi!");
11525       (void)Erased;
11526     }
11527   });
11528 
11529   // Find respective Phis and check that they are not being pending.
11530   if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS))
11531     if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) {
11532       if (!PendingMerges.insert(Phi).second)
11533         return false;
11534       LPhi = Phi;
11535     }
11536   if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS))
11537     if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) {
11538       // If we detect a loop of Phi nodes being processed by this method, for
11539       // example:
11540       //
11541       //   %a = phi i32 [ %some1, %preheader ], [ %b, %latch ]
11542       //   %b = phi i32 [ %some2, %preheader ], [ %a, %latch ]
11543       //
11544       // we don't want to deal with a case that complex, so return conservative
11545       // answer false.
11546       if (!PendingMerges.insert(Phi).second)
11547         return false;
11548       RPhi = Phi;
11549     }
11550 
11551   // If none of LHS, RHS is a Phi, nothing to do here.
11552   if (!LPhi && !RPhi)
11553     return false;
11554 
11555   // If there is a SCEVUnknown Phi we are interested in, make it left.
11556   if (!LPhi) {
11557     std::swap(LHS, RHS);
11558     std::swap(FoundLHS, FoundRHS);
11559     std::swap(LPhi, RPhi);
11560     Pred = ICmpInst::getSwappedPredicate(Pred);
11561   }
11562 
11563   assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!");
11564   const BasicBlock *LBB = LPhi->getParent();
11565   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
11566 
11567   auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) {
11568     return isKnownViaNonRecursiveReasoning(Pred, S1, S2) ||
11569            isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) ||
11570            isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth);
11571   };
11572 
11573   if (RPhi && RPhi->getParent() == LBB) {
11574     // Case one: RHS is also a SCEVUnknown Phi from the same basic block.
11575     // If we compare two Phis from the same block, and for each entry block
11576     // the predicate is true for incoming values from this block, then the
11577     // predicate is also true for the Phis.
11578     for (const BasicBlock *IncBB : predecessors(LBB)) {
11579       const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
11580       const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB));
11581       if (!ProvedEasily(L, R))
11582         return false;
11583     }
11584   } else if (RAR && RAR->getLoop()->getHeader() == LBB) {
11585     // Case two: RHS is also a Phi from the same basic block, and it is an
11586     // AddRec. It means that there is a loop which has both AddRec and Unknown
11587     // PHIs, for it we can compare incoming values of AddRec from above the loop
11588     // and latch with their respective incoming values of LPhi.
11589     // TODO: Generalize to handle loops with many inputs in a header.
11590     if (LPhi->getNumIncomingValues() != 2) return false;
11591 
11592     auto *RLoop = RAR->getLoop();
11593     auto *Predecessor = RLoop->getLoopPredecessor();
11594     assert(Predecessor && "Loop with AddRec with no predecessor?");
11595     const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor));
11596     if (!ProvedEasily(L1, RAR->getStart()))
11597       return false;
11598     auto *Latch = RLoop->getLoopLatch();
11599     assert(Latch && "Loop with AddRec with no latch?");
11600     const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch));
11601     if (!ProvedEasily(L2, RAR->getPostIncExpr(*this)))
11602       return false;
11603   } else {
11604     // In all other cases go over inputs of LHS and compare each of them to RHS,
11605     // the predicate is true for (LHS, RHS) if it is true for all such pairs.
11606     // At this point RHS is either a non-Phi, or it is a Phi from some block
11607     // different from LBB.
11608     for (const BasicBlock *IncBB : predecessors(LBB)) {
11609       // Check that RHS is available in this block.
11610       if (!dominates(RHS, IncBB))
11611         return false;
11612       const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
11613       // Make sure L does not refer to a value from a potentially previous
11614       // iteration of a loop.
11615       if (!properlyDominates(L, IncBB))
11616         return false;
11617       if (!ProvedEasily(L, RHS))
11618         return false;
11619     }
11620   }
11621   return true;
11622 }
11623 
11624 bool ScalarEvolution::isImpliedCondOperandsViaShift(ICmpInst::Predicate Pred,
11625                                                     const SCEV *LHS,
11626                                                     const SCEV *RHS,
11627                                                     const SCEV *FoundLHS,
11628                                                     const SCEV *FoundRHS) {
11629   // We want to imply LHS < RHS from LHS < (RHS >> shiftvalue).  First, make
11630   // sure that we are dealing with same LHS.
11631   if (RHS == FoundRHS) {
11632     std::swap(LHS, RHS);
11633     std::swap(FoundLHS, FoundRHS);
11634     Pred = ICmpInst::getSwappedPredicate(Pred);
11635   }
11636   if (LHS != FoundLHS)
11637     return false;
11638 
11639   auto *SUFoundRHS = dyn_cast<SCEVUnknown>(FoundRHS);
11640   if (!SUFoundRHS)
11641     return false;
11642 
11643   Value *Shiftee, *ShiftValue;
11644 
11645   using namespace PatternMatch;
11646   if (match(SUFoundRHS->getValue(),
11647             m_LShr(m_Value(Shiftee), m_Value(ShiftValue)))) {
11648     auto *ShifteeS = getSCEV(Shiftee);
11649     // Prove one of the following:
11650     // LHS <u (shiftee >> shiftvalue) && shiftee <=u RHS ---> LHS <u RHS
11651     // LHS <=u (shiftee >> shiftvalue) && shiftee <=u RHS ---> LHS <=u RHS
11652     // LHS <s (shiftee >> shiftvalue) && shiftee <=s RHS && shiftee >=s 0
11653     //   ---> LHS <s RHS
11654     // LHS <=s (shiftee >> shiftvalue) && shiftee <=s RHS && shiftee >=s 0
11655     //   ---> LHS <=s RHS
11656     if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE)
11657       return isKnownPredicate(ICmpInst::ICMP_ULE, ShifteeS, RHS);
11658     if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
11659       if (isKnownNonNegative(ShifteeS))
11660         return isKnownPredicate(ICmpInst::ICMP_SLE, ShifteeS, RHS);
11661   }
11662 
11663   return false;
11664 }
11665 
11666 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
11667                                             const SCEV *LHS, const SCEV *RHS,
11668                                             const SCEV *FoundLHS,
11669                                             const SCEV *FoundRHS,
11670                                             const Instruction *CtxI) {
11671   if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
11672     return true;
11673 
11674   if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
11675     return true;
11676 
11677   if (isImpliedCondOperandsViaShift(Pred, LHS, RHS, FoundLHS, FoundRHS))
11678     return true;
11679 
11680   if (isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS,
11681                                           CtxI))
11682     return true;
11683 
11684   return isImpliedCondOperandsHelper(Pred, LHS, RHS,
11685                                      FoundLHS, FoundRHS);
11686 }
11687 
11688 /// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values?
11689 template <typename MinMaxExprType>
11690 static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr,
11691                                  const SCEV *Candidate) {
11692   const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr);
11693   if (!MinMaxExpr)
11694     return false;
11695 
11696   return is_contained(MinMaxExpr->operands(), Candidate);
11697 }
11698 
11699 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
11700                                            ICmpInst::Predicate Pred,
11701                                            const SCEV *LHS, const SCEV *RHS) {
11702   // If both sides are affine addrecs for the same loop, with equal
11703   // steps, and we know the recurrences don't wrap, then we only
11704   // need to check the predicate on the starting values.
11705 
11706   if (!ICmpInst::isRelational(Pred))
11707     return false;
11708 
11709   const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
11710   if (!LAR)
11711     return false;
11712   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
11713   if (!RAR)
11714     return false;
11715   if (LAR->getLoop() != RAR->getLoop())
11716     return false;
11717   if (!LAR->isAffine() || !RAR->isAffine())
11718     return false;
11719 
11720   if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
11721     return false;
11722 
11723   SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
11724                          SCEV::FlagNSW : SCEV::FlagNUW;
11725   if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
11726     return false;
11727 
11728   return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
11729 }
11730 
11731 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
11732 /// expression?
11733 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
11734                                         ICmpInst::Predicate Pred,
11735                                         const SCEV *LHS, const SCEV *RHS) {
11736   switch (Pred) {
11737   default:
11738     return false;
11739 
11740   case ICmpInst::ICMP_SGE:
11741     std::swap(LHS, RHS);
11742     LLVM_FALLTHROUGH;
11743   case ICmpInst::ICMP_SLE:
11744     return
11745         // min(A, ...) <= A
11746         IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) ||
11747         // A <= max(A, ...)
11748         IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
11749 
11750   case ICmpInst::ICMP_UGE:
11751     std::swap(LHS, RHS);
11752     LLVM_FALLTHROUGH;
11753   case ICmpInst::ICMP_ULE:
11754     return
11755         // min(A, ...) <= A
11756         // FIXME: what about umin_seq?
11757         IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) ||
11758         // A <= max(A, ...)
11759         IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
11760   }
11761 
11762   llvm_unreachable("covered switch fell through?!");
11763 }
11764 
11765 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred,
11766                                              const SCEV *LHS, const SCEV *RHS,
11767                                              const SCEV *FoundLHS,
11768                                              const SCEV *FoundRHS,
11769                                              unsigned Depth) {
11770   assert(getTypeSizeInBits(LHS->getType()) ==
11771              getTypeSizeInBits(RHS->getType()) &&
11772          "LHS and RHS have different sizes?");
11773   assert(getTypeSizeInBits(FoundLHS->getType()) ==
11774              getTypeSizeInBits(FoundRHS->getType()) &&
11775          "FoundLHS and FoundRHS have different sizes?");
11776   // We want to avoid hurting the compile time with analysis of too big trees.
11777   if (Depth > MaxSCEVOperationsImplicationDepth)
11778     return false;
11779 
11780   // We only want to work with GT comparison so far.
11781   if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT) {
11782     Pred = CmpInst::getSwappedPredicate(Pred);
11783     std::swap(LHS, RHS);
11784     std::swap(FoundLHS, FoundRHS);
11785   }
11786 
11787   // For unsigned, try to reduce it to corresponding signed comparison.
11788   if (Pred == ICmpInst::ICMP_UGT)
11789     // We can replace unsigned predicate with its signed counterpart if all
11790     // involved values are non-negative.
11791     // TODO: We could have better support for unsigned.
11792     if (isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) {
11793       // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing
11794       // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us
11795       // use this fact to prove that LHS and RHS are non-negative.
11796       const SCEV *MinusOne = getMinusOne(LHS->getType());
11797       if (isImpliedCondOperands(ICmpInst::ICMP_SGT, LHS, MinusOne, FoundLHS,
11798                                 FoundRHS) &&
11799           isImpliedCondOperands(ICmpInst::ICMP_SGT, RHS, MinusOne, FoundLHS,
11800                                 FoundRHS))
11801         Pred = ICmpInst::ICMP_SGT;
11802     }
11803 
11804   if (Pred != ICmpInst::ICMP_SGT)
11805     return false;
11806 
11807   auto GetOpFromSExt = [&](const SCEV *S) {
11808     if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
11809       return Ext->getOperand();
11810     // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
11811     // the constant in some cases.
11812     return S;
11813   };
11814 
11815   // Acquire values from extensions.
11816   auto *OrigLHS = LHS;
11817   auto *OrigFoundLHS = FoundLHS;
11818   LHS = GetOpFromSExt(LHS);
11819   FoundLHS = GetOpFromSExt(FoundLHS);
11820 
11821   // Is the SGT predicate can be proved trivially or using the found context.
11822   auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
11823     return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
11824            isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
11825                                   FoundRHS, Depth + 1);
11826   };
11827 
11828   if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
11829     // We want to avoid creation of any new non-constant SCEV. Since we are
11830     // going to compare the operands to RHS, we should be certain that we don't
11831     // need any size extensions for this. So let's decline all cases when the
11832     // sizes of types of LHS and RHS do not match.
11833     // TODO: Maybe try to get RHS from sext to catch more cases?
11834     if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType()))
11835       return false;
11836 
11837     // Should not overflow.
11838     if (!LHSAddExpr->hasNoSignedWrap())
11839       return false;
11840 
11841     auto *LL = LHSAddExpr->getOperand(0);
11842     auto *LR = LHSAddExpr->getOperand(1);
11843     auto *MinusOne = getMinusOne(RHS->getType());
11844 
11845     // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
11846     auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
11847       return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
11848     };
11849     // Try to prove the following rule:
11850     // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
11851     // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
11852     if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
11853       return true;
11854   } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
11855     Value *LL, *LR;
11856     // FIXME: Once we have SDiv implemented, we can get rid of this matching.
11857 
11858     using namespace llvm::PatternMatch;
11859 
11860     if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
11861       // Rules for division.
11862       // We are going to perform some comparisons with Denominator and its
11863       // derivative expressions. In general case, creating a SCEV for it may
11864       // lead to a complex analysis of the entire graph, and in particular it
11865       // can request trip count recalculation for the same loop. This would
11866       // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
11867       // this, we only want to create SCEVs that are constants in this section.
11868       // So we bail if Denominator is not a constant.
11869       if (!isa<ConstantInt>(LR))
11870         return false;
11871 
11872       auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
11873 
11874       // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
11875       // then a SCEV for the numerator already exists and matches with FoundLHS.
11876       auto *Numerator = getExistingSCEV(LL);
11877       if (!Numerator || Numerator->getType() != FoundLHS->getType())
11878         return false;
11879 
11880       // Make sure that the numerator matches with FoundLHS and the denominator
11881       // is positive.
11882       if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
11883         return false;
11884 
11885       auto *DTy = Denominator->getType();
11886       auto *FRHSTy = FoundRHS->getType();
11887       if (DTy->isPointerTy() != FRHSTy->isPointerTy())
11888         // One of types is a pointer and another one is not. We cannot extend
11889         // them properly to a wider type, so let us just reject this case.
11890         // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
11891         // to avoid this check.
11892         return false;
11893 
11894       // Given that:
11895       // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
11896       auto *WTy = getWiderType(DTy, FRHSTy);
11897       auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
11898       auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
11899 
11900       // Try to prove the following rule:
11901       // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
11902       // For example, given that FoundLHS > 2. It means that FoundLHS is at
11903       // least 3. If we divide it by Denominator < 4, we will have at least 1.
11904       auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
11905       if (isKnownNonPositive(RHS) &&
11906           IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
11907         return true;
11908 
11909       // Try to prove the following rule:
11910       // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
11911       // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
11912       // If we divide it by Denominator > 2, then:
11913       // 1. If FoundLHS is negative, then the result is 0.
11914       // 2. If FoundLHS is non-negative, then the result is non-negative.
11915       // Anyways, the result is non-negative.
11916       auto *MinusOne = getMinusOne(WTy);
11917       auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
11918       if (isKnownNegative(RHS) &&
11919           IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
11920         return true;
11921     }
11922   }
11923 
11924   // If our expression contained SCEVUnknown Phis, and we split it down and now
11925   // need to prove something for them, try to prove the predicate for every
11926   // possible incoming values of those Phis.
11927   if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1))
11928     return true;
11929 
11930   return false;
11931 }
11932 
11933 static bool isKnownPredicateExtendIdiom(ICmpInst::Predicate Pred,
11934                                         const SCEV *LHS, const SCEV *RHS) {
11935   // zext x u<= sext x, sext x s<= zext x
11936   switch (Pred) {
11937   case ICmpInst::ICMP_SGE:
11938     std::swap(LHS, RHS);
11939     LLVM_FALLTHROUGH;
11940   case ICmpInst::ICMP_SLE: {
11941     // If operand >=s 0 then ZExt == SExt.  If operand <s 0 then SExt <s ZExt.
11942     const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(LHS);
11943     const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(RHS);
11944     if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand())
11945       return true;
11946     break;
11947   }
11948   case ICmpInst::ICMP_UGE:
11949     std::swap(LHS, RHS);
11950     LLVM_FALLTHROUGH;
11951   case ICmpInst::ICMP_ULE: {
11952     // If operand >=s 0 then ZExt == SExt.  If operand <s 0 then ZExt <u SExt.
11953     const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS);
11954     const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(RHS);
11955     if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand())
11956       return true;
11957     break;
11958   }
11959   default:
11960     break;
11961   };
11962   return false;
11963 }
11964 
11965 bool
11966 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred,
11967                                            const SCEV *LHS, const SCEV *RHS) {
11968   return isKnownPredicateExtendIdiom(Pred, LHS, RHS) ||
11969          isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
11970          IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
11971          IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
11972          isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
11973 }
11974 
11975 bool
11976 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
11977                                              const SCEV *LHS, const SCEV *RHS,
11978                                              const SCEV *FoundLHS,
11979                                              const SCEV *FoundRHS) {
11980   switch (Pred) {
11981   default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
11982   case ICmpInst::ICMP_EQ:
11983   case ICmpInst::ICMP_NE:
11984     if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
11985       return true;
11986     break;
11987   case ICmpInst::ICMP_SLT:
11988   case ICmpInst::ICMP_SLE:
11989     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
11990         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS))
11991       return true;
11992     break;
11993   case ICmpInst::ICMP_SGT:
11994   case ICmpInst::ICMP_SGE:
11995     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
11996         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS))
11997       return true;
11998     break;
11999   case ICmpInst::ICMP_ULT:
12000   case ICmpInst::ICMP_ULE:
12001     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
12002         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS))
12003       return true;
12004     break;
12005   case ICmpInst::ICMP_UGT:
12006   case ICmpInst::ICMP_UGE:
12007     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
12008         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS))
12009       return true;
12010     break;
12011   }
12012 
12013   // Maybe it can be proved via operations?
12014   if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
12015     return true;
12016 
12017   return false;
12018 }
12019 
12020 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
12021                                                      const SCEV *LHS,
12022                                                      const SCEV *RHS,
12023                                                      const SCEV *FoundLHS,
12024                                                      const SCEV *FoundRHS) {
12025   if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
12026     // The restriction on `FoundRHS` be lifted easily -- it exists only to
12027     // reduce the compile time impact of this optimization.
12028     return false;
12029 
12030   Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
12031   if (!Addend)
12032     return false;
12033 
12034   const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
12035 
12036   // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
12037   // antecedent "`FoundLHS` `Pred` `FoundRHS`".
12038   ConstantRange FoundLHSRange =
12039       ConstantRange::makeExactICmpRegion(Pred, ConstFoundRHS);
12040 
12041   // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
12042   ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
12043 
12044   // We can also compute the range of values for `LHS` that satisfy the
12045   // consequent, "`LHS` `Pred` `RHS`":
12046   const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
12047   // The antecedent implies the consequent if every value of `LHS` that
12048   // satisfies the antecedent also satisfies the consequent.
12049   return LHSRange.icmp(Pred, ConstRHS);
12050 }
12051 
12052 bool ScalarEvolution::canIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
12053                                         bool IsSigned) {
12054   assert(isKnownPositive(Stride) && "Positive stride expected!");
12055 
12056   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
12057   const SCEV *One = getOne(Stride->getType());
12058 
12059   if (IsSigned) {
12060     APInt MaxRHS = getSignedRangeMax(RHS);
12061     APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
12062     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
12063 
12064     // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
12065     return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS);
12066   }
12067 
12068   APInt MaxRHS = getUnsignedRangeMax(RHS);
12069   APInt MaxValue = APInt::getMaxValue(BitWidth);
12070   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
12071 
12072   // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
12073   return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS);
12074 }
12075 
12076 bool ScalarEvolution::canIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
12077                                         bool IsSigned) {
12078 
12079   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
12080   const SCEV *One = getOne(Stride->getType());
12081 
12082   if (IsSigned) {
12083     APInt MinRHS = getSignedRangeMin(RHS);
12084     APInt MinValue = APInt::getSignedMinValue(BitWidth);
12085     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
12086 
12087     // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
12088     return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS);
12089   }
12090 
12091   APInt MinRHS = getUnsignedRangeMin(RHS);
12092   APInt MinValue = APInt::getMinValue(BitWidth);
12093   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
12094 
12095   // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
12096   return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS);
12097 }
12098 
12099 const SCEV *ScalarEvolution::getUDivCeilSCEV(const SCEV *N, const SCEV *D) {
12100   // umin(N, 1) + floor((N - umin(N, 1)) / D)
12101   // This is equivalent to "1 + floor((N - 1) / D)" for N != 0. The umin
12102   // expression fixes the case of N=0.
12103   const SCEV *MinNOne = getUMinExpr(N, getOne(N->getType()));
12104   const SCEV *NMinusOne = getMinusSCEV(N, MinNOne);
12105   return getAddExpr(MinNOne, getUDivExpr(NMinusOne, D));
12106 }
12107 
12108 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start,
12109                                                     const SCEV *Stride,
12110                                                     const SCEV *End,
12111                                                     unsigned BitWidth,
12112                                                     bool IsSigned) {
12113   // The logic in this function assumes we can represent a positive stride.
12114   // If we can't, the backedge-taken count must be zero.
12115   if (IsSigned && BitWidth == 1)
12116     return getZero(Stride->getType());
12117 
12118   // This code has only been closely audited for negative strides in the
12119   // unsigned comparison case, it may be correct for signed comparison, but
12120   // that needs to be established.
12121   assert((!IsSigned || !isKnownNonPositive(Stride)) &&
12122          "Stride is expected strictly positive for signed case!");
12123 
12124   // Calculate the maximum backedge count based on the range of values
12125   // permitted by Start, End, and Stride.
12126   APInt MinStart =
12127       IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start);
12128 
12129   APInt MinStride =
12130       IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride);
12131 
12132   // We assume either the stride is positive, or the backedge-taken count
12133   // is zero. So force StrideForMaxBECount to be at least one.
12134   APInt One(BitWidth, 1);
12135   APInt StrideForMaxBECount = IsSigned ? APIntOps::smax(One, MinStride)
12136                                        : APIntOps::umax(One, MinStride);
12137 
12138   APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth)
12139                             : APInt::getMaxValue(BitWidth);
12140   APInt Limit = MaxValue - (StrideForMaxBECount - 1);
12141 
12142   // Although End can be a MAX expression we estimate MaxEnd considering only
12143   // the case End = RHS of the loop termination condition. This is safe because
12144   // in the other case (End - Start) is zero, leading to a zero maximum backedge
12145   // taken count.
12146   APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit)
12147                           : APIntOps::umin(getUnsignedRangeMax(End), Limit);
12148 
12149   // MaxBECount = ceil((max(MaxEnd, MinStart) - MinStart) / Stride)
12150   MaxEnd = IsSigned ? APIntOps::smax(MaxEnd, MinStart)
12151                     : APIntOps::umax(MaxEnd, MinStart);
12152 
12153   return getUDivCeilSCEV(getConstant(MaxEnd - MinStart) /* Delta */,
12154                          getConstant(StrideForMaxBECount) /* Step */);
12155 }
12156 
12157 ScalarEvolution::ExitLimit
12158 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
12159                                   const Loop *L, bool IsSigned,
12160                                   bool ControlsExit, bool AllowPredicates) {
12161   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
12162 
12163   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
12164   bool PredicatedIV = false;
12165 
12166   auto canAssumeNoSelfWrap = [&](const SCEVAddRecExpr *AR) {
12167     // Can we prove this loop *must* be UB if overflow of IV occurs?
12168     // Reasoning goes as follows:
12169     // * Suppose the IV did self wrap.
12170     // * If Stride evenly divides the iteration space, then once wrap
12171     //   occurs, the loop must revisit the same values.
12172     // * We know that RHS is invariant, and that none of those values
12173     //   caused this exit to be taken previously.  Thus, this exit is
12174     //   dynamically dead.
12175     // * If this is the sole exit, then a dead exit implies the loop
12176     //   must be infinite if there are no abnormal exits.
12177     // * If the loop were infinite, then it must either not be mustprogress
12178     //   or have side effects. Otherwise, it must be UB.
12179     // * It can't (by assumption), be UB so we have contradicted our
12180     //   premise and can conclude the IV did not in fact self-wrap.
12181     if (!isLoopInvariant(RHS, L))
12182       return false;
12183 
12184     auto *StrideC = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this));
12185     if (!StrideC || !StrideC->getAPInt().isPowerOf2())
12186       return false;
12187 
12188     if (!ControlsExit || !loopHasNoAbnormalExits(L))
12189       return false;
12190 
12191     return loopIsFiniteByAssumption(L);
12192   };
12193 
12194   if (!IV) {
12195     if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS)) {
12196       const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(ZExt->getOperand());
12197       if (AR && AR->getLoop() == L && AR->isAffine()) {
12198         auto canProveNUW = [&]() {
12199           if (!isLoopInvariant(RHS, L))
12200             return false;
12201 
12202           if (!isKnownNonZero(AR->getStepRecurrence(*this)))
12203             // We need the sequence defined by AR to strictly increase in the
12204             // unsigned integer domain for the logic below to hold.
12205             return false;
12206 
12207           const unsigned InnerBitWidth = getTypeSizeInBits(AR->getType());
12208           const unsigned OuterBitWidth = getTypeSizeInBits(RHS->getType());
12209           // If RHS <=u Limit, then there must exist a value V in the sequence
12210           // defined by AR (e.g. {Start,+,Step}) such that V >u RHS, and
12211           // V <=u UINT_MAX.  Thus, we must exit the loop before unsigned
12212           // overflow occurs.  This limit also implies that a signed comparison
12213           // (in the wide bitwidth) is equivalent to an unsigned comparison as
12214           // the high bits on both sides must be zero.
12215           APInt StrideMax = getUnsignedRangeMax(AR->getStepRecurrence(*this));
12216           APInt Limit = APInt::getMaxValue(InnerBitWidth) - (StrideMax - 1);
12217           Limit = Limit.zext(OuterBitWidth);
12218           return getUnsignedRangeMax(applyLoopGuards(RHS, L)).ule(Limit);
12219         };
12220         auto Flags = AR->getNoWrapFlags();
12221         if (!hasFlags(Flags, SCEV::FlagNUW) && canProveNUW())
12222           Flags = setFlags(Flags, SCEV::FlagNUW);
12223 
12224         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
12225         if (AR->hasNoUnsignedWrap()) {
12226           // Emulate what getZeroExtendExpr would have done during construction
12227           // if we'd been able to infer the fact just above at that time.
12228           const SCEV *Step = AR->getStepRecurrence(*this);
12229           Type *Ty = ZExt->getType();
12230           auto *S = getAddRecExpr(
12231             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 0),
12232             getZeroExtendExpr(Step, Ty, 0), L, AR->getNoWrapFlags());
12233           IV = dyn_cast<SCEVAddRecExpr>(S);
12234         }
12235       }
12236     }
12237   }
12238 
12239 
12240   if (!IV && AllowPredicates) {
12241     // Try to make this an AddRec using runtime tests, in the first X
12242     // iterations of this loop, where X is the SCEV expression found by the
12243     // algorithm below.
12244     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
12245     PredicatedIV = true;
12246   }
12247 
12248   // Avoid weird loops
12249   if (!IV || IV->getLoop() != L || !IV->isAffine())
12250     return getCouldNotCompute();
12251 
12252   // A precondition of this method is that the condition being analyzed
12253   // reaches an exiting branch which dominates the latch.  Given that, we can
12254   // assume that an increment which violates the nowrap specification and
12255   // produces poison must cause undefined behavior when the resulting poison
12256   // value is branched upon and thus we can conclude that the backedge is
12257   // taken no more often than would be required to produce that poison value.
12258   // Note that a well defined loop can exit on the iteration which violates
12259   // the nowrap specification if there is another exit (either explicit or
12260   // implicit/exceptional) which causes the loop to execute before the
12261   // exiting instruction we're analyzing would trigger UB.
12262   auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW;
12263   bool NoWrap = ControlsExit && IV->getNoWrapFlags(WrapType);
12264   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
12265 
12266   const SCEV *Stride = IV->getStepRecurrence(*this);
12267 
12268   bool PositiveStride = isKnownPositive(Stride);
12269 
12270   // Avoid negative or zero stride values.
12271   if (!PositiveStride) {
12272     // We can compute the correct backedge taken count for loops with unknown
12273     // strides if we can prove that the loop is not an infinite loop with side
12274     // effects. Here's the loop structure we are trying to handle -
12275     //
12276     // i = start
12277     // do {
12278     //   A[i] = i;
12279     //   i += s;
12280     // } while (i < end);
12281     //
12282     // The backedge taken count for such loops is evaluated as -
12283     // (max(end, start + stride) - start - 1) /u stride
12284     //
12285     // The additional preconditions that we need to check to prove correctness
12286     // of the above formula is as follows -
12287     //
12288     // a) IV is either nuw or nsw depending upon signedness (indicated by the
12289     //    NoWrap flag).
12290     // b) the loop is guaranteed to be finite (e.g. is mustprogress and has
12291     //    no side effects within the loop)
12292     // c) loop has a single static exit (with no abnormal exits)
12293     //
12294     // Precondition a) implies that if the stride is negative, this is a single
12295     // trip loop. The backedge taken count formula reduces to zero in this case.
12296     //
12297     // Precondition b) and c) combine to imply that if rhs is invariant in L,
12298     // then a zero stride means the backedge can't be taken without executing
12299     // undefined behavior.
12300     //
12301     // The positive stride case is the same as isKnownPositive(Stride) returning
12302     // true (original behavior of the function).
12303     //
12304     if (PredicatedIV || !NoWrap || !loopIsFiniteByAssumption(L) ||
12305         !loopHasNoAbnormalExits(L))
12306       return getCouldNotCompute();
12307 
12308     // This bailout is protecting the logic in computeMaxBECountForLT which
12309     // has not yet been sufficiently auditted or tested with negative strides.
12310     // We used to filter out all known-non-positive cases here, we're in the
12311     // process of being less restrictive bit by bit.
12312     if (IsSigned && isKnownNonPositive(Stride))
12313       return getCouldNotCompute();
12314 
12315     if (!isKnownNonZero(Stride)) {
12316       // If we have a step of zero, and RHS isn't invariant in L, we don't know
12317       // if it might eventually be greater than start and if so, on which
12318       // iteration.  We can't even produce a useful upper bound.
12319       if (!isLoopInvariant(RHS, L))
12320         return getCouldNotCompute();
12321 
12322       // We allow a potentially zero stride, but we need to divide by stride
12323       // below.  Since the loop can't be infinite and this check must control
12324       // the sole exit, we can infer the exit must be taken on the first
12325       // iteration (e.g. backedge count = 0) if the stride is zero.  Given that,
12326       // we know the numerator in the divides below must be zero, so we can
12327       // pick an arbitrary non-zero value for the denominator (e.g. stride)
12328       // and produce the right result.
12329       // FIXME: Handle the case where Stride is poison?
12330       auto wouldZeroStrideBeUB = [&]() {
12331         // Proof by contradiction.  Suppose the stride were zero.  If we can
12332         // prove that the backedge *is* taken on the first iteration, then since
12333         // we know this condition controls the sole exit, we must have an
12334         // infinite loop.  We can't have a (well defined) infinite loop per
12335         // check just above.
12336         // Note: The (Start - Stride) term is used to get the start' term from
12337         // (start' + stride,+,stride). Remember that we only care about the
12338         // result of this expression when stride == 0 at runtime.
12339         auto *StartIfZero = getMinusSCEV(IV->getStart(), Stride);
12340         return isLoopEntryGuardedByCond(L, Cond, StartIfZero, RHS);
12341       };
12342       if (!wouldZeroStrideBeUB()) {
12343         Stride = getUMaxExpr(Stride, getOne(Stride->getType()));
12344       }
12345     }
12346   } else if (!Stride->isOne() && !NoWrap) {
12347     auto isUBOnWrap = [&]() {
12348       // From no-self-wrap, we need to then prove no-(un)signed-wrap.  This
12349       // follows trivially from the fact that every (un)signed-wrapped, but
12350       // not self-wrapped value must be LT than the last value before
12351       // (un)signed wrap.  Since we know that last value didn't exit, nor
12352       // will any smaller one.
12353       return canAssumeNoSelfWrap(IV);
12354     };
12355 
12356     // Avoid proven overflow cases: this will ensure that the backedge taken
12357     // count will not generate any unsigned overflow. Relaxed no-overflow
12358     // conditions exploit NoWrapFlags, allowing to optimize in presence of
12359     // undefined behaviors like the case of C language.
12360     if (canIVOverflowOnLT(RHS, Stride, IsSigned) && !isUBOnWrap())
12361       return getCouldNotCompute();
12362   }
12363 
12364   // On all paths just preceeding, we established the following invariant:
12365   //   IV can be assumed not to overflow up to and including the exiting
12366   //   iteration.  We proved this in one of two ways:
12367   //   1) We can show overflow doesn't occur before the exiting iteration
12368   //      1a) canIVOverflowOnLT, and b) step of one
12369   //   2) We can show that if overflow occurs, the loop must execute UB
12370   //      before any possible exit.
12371   // Note that we have not yet proved RHS invariant (in general).
12372 
12373   const SCEV *Start = IV->getStart();
12374 
12375   // Preserve pointer-typed Start/RHS to pass to isLoopEntryGuardedByCond.
12376   // If we convert to integers, isLoopEntryGuardedByCond will miss some cases.
12377   // Use integer-typed versions for actual computation; we can't subtract
12378   // pointers in general.
12379   const SCEV *OrigStart = Start;
12380   const SCEV *OrigRHS = RHS;
12381   if (Start->getType()->isPointerTy()) {
12382     Start = getLosslessPtrToIntExpr(Start);
12383     if (isa<SCEVCouldNotCompute>(Start))
12384       return Start;
12385   }
12386   if (RHS->getType()->isPointerTy()) {
12387     RHS = getLosslessPtrToIntExpr(RHS);
12388     if (isa<SCEVCouldNotCompute>(RHS))
12389       return RHS;
12390   }
12391 
12392   // When the RHS is not invariant, we do not know the end bound of the loop and
12393   // cannot calculate the ExactBECount needed by ExitLimit. However, we can
12394   // calculate the MaxBECount, given the start, stride and max value for the end
12395   // bound of the loop (RHS), and the fact that IV does not overflow (which is
12396   // checked above).
12397   if (!isLoopInvariant(RHS, L)) {
12398     const SCEV *MaxBECount = computeMaxBECountForLT(
12399         Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
12400     return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount,
12401                      false /*MaxOrZero*/, Predicates);
12402   }
12403 
12404   // We use the expression (max(End,Start)-Start)/Stride to describe the
12405   // backedge count, as if the backedge is taken at least once max(End,Start)
12406   // is End and so the result is as above, and if not max(End,Start) is Start
12407   // so we get a backedge count of zero.
12408   const SCEV *BECount = nullptr;
12409   auto *OrigStartMinusStride = getMinusSCEV(OrigStart, Stride);
12410   assert(isAvailableAtLoopEntry(OrigStartMinusStride, L) && "Must be!");
12411   assert(isAvailableAtLoopEntry(OrigStart, L) && "Must be!");
12412   assert(isAvailableAtLoopEntry(OrigRHS, L) && "Must be!");
12413   // Can we prove (max(RHS,Start) > Start - Stride?
12414   if (isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigStart) &&
12415       isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigRHS)) {
12416     // In this case, we can use a refined formula for computing backedge taken
12417     // count.  The general formula remains:
12418     //   "End-Start /uceiling Stride" where "End = max(RHS,Start)"
12419     // We want to use the alternate formula:
12420     //   "((End - 1) - (Start - Stride)) /u Stride"
12421     // Let's do a quick case analysis to show these are equivalent under
12422     // our precondition that max(RHS,Start) > Start - Stride.
12423     // * For RHS <= Start, the backedge-taken count must be zero.
12424     //   "((End - 1) - (Start - Stride)) /u Stride" reduces to
12425     //   "((Start - 1) - (Start - Stride)) /u Stride" which simplies to
12426     //   "Stride - 1 /u Stride" which is indeed zero for all non-zero values
12427     //     of Stride.  For 0 stride, we've use umin(1,Stride) above, reducing
12428     //     this to the stride of 1 case.
12429     // * For RHS >= Start, the backedge count must be "RHS-Start /uceil Stride".
12430     //   "((End - 1) - (Start - Stride)) /u Stride" reduces to
12431     //   "((RHS - 1) - (Start - Stride)) /u Stride" reassociates to
12432     //   "((RHS - (Start - Stride) - 1) /u Stride".
12433     //   Our preconditions trivially imply no overflow in that form.
12434     const SCEV *MinusOne = getMinusOne(Stride->getType());
12435     const SCEV *Numerator =
12436         getMinusSCEV(getAddExpr(RHS, MinusOne), getMinusSCEV(Start, Stride));
12437     BECount = getUDivExpr(Numerator, Stride);
12438   }
12439 
12440   const SCEV *BECountIfBackedgeTaken = nullptr;
12441   if (!BECount) {
12442     auto canProveRHSGreaterThanEqualStart = [&]() {
12443       auto CondGE = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
12444       if (isLoopEntryGuardedByCond(L, CondGE, OrigRHS, OrigStart))
12445         return true;
12446 
12447       // (RHS > Start - 1) implies RHS >= Start.
12448       // * "RHS >= Start" is trivially equivalent to "RHS > Start - 1" if
12449       //   "Start - 1" doesn't overflow.
12450       // * For signed comparison, if Start - 1 does overflow, it's equal
12451       //   to INT_MAX, and "RHS >s INT_MAX" is trivially false.
12452       // * For unsigned comparison, if Start - 1 does overflow, it's equal
12453       //   to UINT_MAX, and "RHS >u UINT_MAX" is trivially false.
12454       //
12455       // FIXME: Should isLoopEntryGuardedByCond do this for us?
12456       auto CondGT = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
12457       auto *StartMinusOne = getAddExpr(OrigStart,
12458                                        getMinusOne(OrigStart->getType()));
12459       return isLoopEntryGuardedByCond(L, CondGT, OrigRHS, StartMinusOne);
12460     };
12461 
12462     // If we know that RHS >= Start in the context of loop, then we know that
12463     // max(RHS, Start) = RHS at this point.
12464     const SCEV *End;
12465     if (canProveRHSGreaterThanEqualStart()) {
12466       End = RHS;
12467     } else {
12468       // If RHS < Start, the backedge will be taken zero times.  So in
12469       // general, we can write the backedge-taken count as:
12470       //
12471       //     RHS >= Start ? ceil(RHS - Start) / Stride : 0
12472       //
12473       // We convert it to the following to make it more convenient for SCEV:
12474       //
12475       //     ceil(max(RHS, Start) - Start) / Stride
12476       End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
12477 
12478       // See what would happen if we assume the backedge is taken. This is
12479       // used to compute MaxBECount.
12480       BECountIfBackedgeTaken = getUDivCeilSCEV(getMinusSCEV(RHS, Start), Stride);
12481     }
12482 
12483     // At this point, we know:
12484     //
12485     // 1. If IsSigned, Start <=s End; otherwise, Start <=u End
12486     // 2. The index variable doesn't overflow.
12487     //
12488     // Therefore, we know N exists such that
12489     // (Start + Stride * N) >= End, and computing "(Start + Stride * N)"
12490     // doesn't overflow.
12491     //
12492     // Using this information, try to prove whether the addition in
12493     // "(Start - End) + (Stride - 1)" has unsigned overflow.
12494     const SCEV *One = getOne(Stride->getType());
12495     bool MayAddOverflow = [&] {
12496       if (auto *StrideC = dyn_cast<SCEVConstant>(Stride)) {
12497         if (StrideC->getAPInt().isPowerOf2()) {
12498           // Suppose Stride is a power of two, and Start/End are unsigned
12499           // integers.  Let UMAX be the largest representable unsigned
12500           // integer.
12501           //
12502           // By the preconditions of this function, we know
12503           // "(Start + Stride * N) >= End", and this doesn't overflow.
12504           // As a formula:
12505           //
12506           //   End <= (Start + Stride * N) <= UMAX
12507           //
12508           // Subtracting Start from all the terms:
12509           //
12510           //   End - Start <= Stride * N <= UMAX - Start
12511           //
12512           // Since Start is unsigned, UMAX - Start <= UMAX.  Therefore:
12513           //
12514           //   End - Start <= Stride * N <= UMAX
12515           //
12516           // Stride * N is a multiple of Stride. Therefore,
12517           //
12518           //   End - Start <= Stride * N <= UMAX - (UMAX mod Stride)
12519           //
12520           // Since Stride is a power of two, UMAX + 1 is divisible by Stride.
12521           // Therefore, UMAX mod Stride == Stride - 1.  So we can write:
12522           //
12523           //   End - Start <= Stride * N <= UMAX - Stride - 1
12524           //
12525           // Dropping the middle term:
12526           //
12527           //   End - Start <= UMAX - Stride - 1
12528           //
12529           // Adding Stride - 1 to both sides:
12530           //
12531           //   (End - Start) + (Stride - 1) <= UMAX
12532           //
12533           // In other words, the addition doesn't have unsigned overflow.
12534           //
12535           // A similar proof works if we treat Start/End as signed values.
12536           // Just rewrite steps before "End - Start <= Stride * N <= UMAX" to
12537           // use signed max instead of unsigned max. Note that we're trying
12538           // to prove a lack of unsigned overflow in either case.
12539           return false;
12540         }
12541       }
12542       if (Start == Stride || Start == getMinusSCEV(Stride, One)) {
12543         // If Start is equal to Stride, (End - Start) + (Stride - 1) == End - 1.
12544         // If !IsSigned, 0 <u Stride == Start <=u End; so 0 <u End - 1 <u End.
12545         // If IsSigned, 0 <s Stride == Start <=s End; so 0 <s End - 1 <s End.
12546         //
12547         // If Start is equal to Stride - 1, (End - Start) + Stride - 1 == End.
12548         return false;
12549       }
12550       return true;
12551     }();
12552 
12553     const SCEV *Delta = getMinusSCEV(End, Start);
12554     if (!MayAddOverflow) {
12555       // floor((D + (S - 1)) / S)
12556       // We prefer this formulation if it's legal because it's fewer operations.
12557       BECount =
12558           getUDivExpr(getAddExpr(Delta, getMinusSCEV(Stride, One)), Stride);
12559     } else {
12560       BECount = getUDivCeilSCEV(Delta, Stride);
12561     }
12562   }
12563 
12564   const SCEV *MaxBECount;
12565   bool MaxOrZero = false;
12566   if (isa<SCEVConstant>(BECount)) {
12567     MaxBECount = BECount;
12568   } else if (BECountIfBackedgeTaken &&
12569              isa<SCEVConstant>(BECountIfBackedgeTaken)) {
12570     // If we know exactly how many times the backedge will be taken if it's
12571     // taken at least once, then the backedge count will either be that or
12572     // zero.
12573     MaxBECount = BECountIfBackedgeTaken;
12574     MaxOrZero = true;
12575   } else {
12576     MaxBECount = computeMaxBECountForLT(
12577         Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
12578   }
12579 
12580   if (isa<SCEVCouldNotCompute>(MaxBECount) &&
12581       !isa<SCEVCouldNotCompute>(BECount))
12582     MaxBECount = getConstant(getUnsignedRangeMax(BECount));
12583 
12584   return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates);
12585 }
12586 
12587 ScalarEvolution::ExitLimit
12588 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
12589                                      const Loop *L, bool IsSigned,
12590                                      bool ControlsExit, bool AllowPredicates) {
12591   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
12592   // We handle only IV > Invariant
12593   if (!isLoopInvariant(RHS, L))
12594     return getCouldNotCompute();
12595 
12596   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
12597   if (!IV && AllowPredicates)
12598     // Try to make this an AddRec using runtime tests, in the first X
12599     // iterations of this loop, where X is the SCEV expression found by the
12600     // algorithm below.
12601     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
12602 
12603   // Avoid weird loops
12604   if (!IV || IV->getLoop() != L || !IV->isAffine())
12605     return getCouldNotCompute();
12606 
12607   auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW;
12608   bool NoWrap = ControlsExit && IV->getNoWrapFlags(WrapType);
12609   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
12610 
12611   const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
12612 
12613   // Avoid negative or zero stride values
12614   if (!isKnownPositive(Stride))
12615     return getCouldNotCompute();
12616 
12617   // Avoid proven overflow cases: this will ensure that the backedge taken count
12618   // will not generate any unsigned overflow. Relaxed no-overflow conditions
12619   // exploit NoWrapFlags, allowing to optimize in presence of undefined
12620   // behaviors like the case of C language.
12621   if (!Stride->isOne() && !NoWrap)
12622     if (canIVOverflowOnGT(RHS, Stride, IsSigned))
12623       return getCouldNotCompute();
12624 
12625   const SCEV *Start = IV->getStart();
12626   const SCEV *End = RHS;
12627   if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) {
12628     // If we know that Start >= RHS in the context of loop, then we know that
12629     // min(RHS, Start) = RHS at this point.
12630     if (isLoopEntryGuardedByCond(
12631             L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, RHS))
12632       End = RHS;
12633     else
12634       End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
12635   }
12636 
12637   if (Start->getType()->isPointerTy()) {
12638     Start = getLosslessPtrToIntExpr(Start);
12639     if (isa<SCEVCouldNotCompute>(Start))
12640       return Start;
12641   }
12642   if (End->getType()->isPointerTy()) {
12643     End = getLosslessPtrToIntExpr(End);
12644     if (isa<SCEVCouldNotCompute>(End))
12645       return End;
12646   }
12647 
12648   // Compute ((Start - End) + (Stride - 1)) / Stride.
12649   // FIXME: This can overflow. Holding off on fixing this for now;
12650   // howManyGreaterThans will hopefully be gone soon.
12651   const SCEV *One = getOne(Stride->getType());
12652   const SCEV *BECount = getUDivExpr(
12653       getAddExpr(getMinusSCEV(Start, End), getMinusSCEV(Stride, One)), Stride);
12654 
12655   APInt MaxStart = IsSigned ? getSignedRangeMax(Start)
12656                             : getUnsignedRangeMax(Start);
12657 
12658   APInt MinStride = IsSigned ? getSignedRangeMin(Stride)
12659                              : getUnsignedRangeMin(Stride);
12660 
12661   unsigned BitWidth = getTypeSizeInBits(LHS->getType());
12662   APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
12663                          : APInt::getMinValue(BitWidth) + (MinStride - 1);
12664 
12665   // Although End can be a MIN expression we estimate MinEnd considering only
12666   // the case End = RHS. This is safe because in the other case (Start - End)
12667   // is zero, leading to a zero maximum backedge taken count.
12668   APInt MinEnd =
12669     IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit)
12670              : APIntOps::umax(getUnsignedRangeMin(RHS), Limit);
12671 
12672   const SCEV *MaxBECount = isa<SCEVConstant>(BECount)
12673                                ? BECount
12674                                : getUDivCeilSCEV(getConstant(MaxStart - MinEnd),
12675                                                  getConstant(MinStride));
12676 
12677   if (isa<SCEVCouldNotCompute>(MaxBECount))
12678     MaxBECount = BECount;
12679 
12680   return ExitLimit(BECount, MaxBECount, false, Predicates);
12681 }
12682 
12683 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range,
12684                                                     ScalarEvolution &SE) const {
12685   if (Range.isFullSet())  // Infinite loop.
12686     return SE.getCouldNotCompute();
12687 
12688   // If the start is a non-zero constant, shift the range to simplify things.
12689   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
12690     if (!SC->getValue()->isZero()) {
12691       SmallVector<const SCEV *, 4> Operands(operands());
12692       Operands[0] = SE.getZero(SC->getType());
12693       const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
12694                                              getNoWrapFlags(FlagNW));
12695       if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
12696         return ShiftedAddRec->getNumIterationsInRange(
12697             Range.subtract(SC->getAPInt()), SE);
12698       // This is strange and shouldn't happen.
12699       return SE.getCouldNotCompute();
12700     }
12701 
12702   // The only time we can solve this is when we have all constant indices.
12703   // Otherwise, we cannot determine the overflow conditions.
12704   if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
12705     return SE.getCouldNotCompute();
12706 
12707   // Okay at this point we know that all elements of the chrec are constants and
12708   // that the start element is zero.
12709 
12710   // First check to see if the range contains zero.  If not, the first
12711   // iteration exits.
12712   unsigned BitWidth = SE.getTypeSizeInBits(getType());
12713   if (!Range.contains(APInt(BitWidth, 0)))
12714     return SE.getZero(getType());
12715 
12716   if (isAffine()) {
12717     // If this is an affine expression then we have this situation:
12718     //   Solve {0,+,A} in Range  ===  Ax in Range
12719 
12720     // We know that zero is in the range.  If A is positive then we know that
12721     // the upper value of the range must be the first possible exit value.
12722     // If A is negative then the lower of the range is the last possible loop
12723     // value.  Also note that we already checked for a full range.
12724     APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
12725     APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower();
12726 
12727     // The exit value should be (End+A)/A.
12728     APInt ExitVal = (End + A).udiv(A);
12729     ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
12730 
12731     // Evaluate at the exit value.  If we really did fall out of the valid
12732     // range, then we computed our trip count, otherwise wrap around or other
12733     // things must have happened.
12734     ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
12735     if (Range.contains(Val->getValue()))
12736       return SE.getCouldNotCompute();  // Something strange happened
12737 
12738     // Ensure that the previous value is in the range.
12739     assert(Range.contains(
12740            EvaluateConstantChrecAtConstant(this,
12741            ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&
12742            "Linear scev computation is off in a bad way!");
12743     return SE.getConstant(ExitValue);
12744   }
12745 
12746   if (isQuadratic()) {
12747     if (auto S = SolveQuadraticAddRecRange(this, Range, SE))
12748       return SE.getConstant(S.getValue());
12749   }
12750 
12751   return SE.getCouldNotCompute();
12752 }
12753 
12754 const SCEVAddRecExpr *
12755 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const {
12756   assert(getNumOperands() > 1 && "AddRec with zero step?");
12757   // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)),
12758   // but in this case we cannot guarantee that the value returned will be an
12759   // AddRec because SCEV does not have a fixed point where it stops
12760   // simplification: it is legal to return ({rec1} + {rec2}). For example, it
12761   // may happen if we reach arithmetic depth limit while simplifying. So we
12762   // construct the returned value explicitly.
12763   SmallVector<const SCEV *, 3> Ops;
12764   // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and
12765   // (this + Step) is {A+B,+,B+C,+...,+,N}.
12766   for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i)
12767     Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1)));
12768   // We know that the last operand is not a constant zero (otherwise it would
12769   // have been popped out earlier). This guarantees us that if the result has
12770   // the same last operand, then it will also not be popped out, meaning that
12771   // the returned value will be an AddRec.
12772   const SCEV *Last = getOperand(getNumOperands() - 1);
12773   assert(!Last->isZero() && "Recurrency with zero step?");
12774   Ops.push_back(Last);
12775   return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(),
12776                                                SCEV::FlagAnyWrap));
12777 }
12778 
12779 // Return true when S contains at least an undef value.
12780 bool ScalarEvolution::containsUndefs(const SCEV *S) const {
12781   return SCEVExprContains(S, [](const SCEV *S) {
12782     if (const auto *SU = dyn_cast<SCEVUnknown>(S))
12783       return isa<UndefValue>(SU->getValue());
12784     return false;
12785   });
12786 }
12787 
12788 // Return true when S contains a value that is a nullptr.
12789 bool ScalarEvolution::containsErasedValue(const SCEV *S) const {
12790   return SCEVExprContains(S, [](const SCEV *S) {
12791     if (const auto *SU = dyn_cast<SCEVUnknown>(S))
12792       return SU->getValue() == nullptr;
12793     return false;
12794   });
12795 }
12796 
12797 /// Return the size of an element read or written by Inst.
12798 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
12799   Type *Ty;
12800   if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
12801     Ty = Store->getValueOperand()->getType();
12802   else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
12803     Ty = Load->getType();
12804   else
12805     return nullptr;
12806 
12807   Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
12808   return getSizeOfExpr(ETy, Ty);
12809 }
12810 
12811 //===----------------------------------------------------------------------===//
12812 //                   SCEVCallbackVH Class Implementation
12813 //===----------------------------------------------------------------------===//
12814 
12815 void ScalarEvolution::SCEVCallbackVH::deleted() {
12816   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
12817   if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
12818     SE->ConstantEvolutionLoopExitValue.erase(PN);
12819   SE->eraseValueFromMap(getValPtr());
12820   // this now dangles!
12821 }
12822 
12823 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
12824   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
12825 
12826   // Forget all the expressions associated with users of the old value,
12827   // so that future queries will recompute the expressions using the new
12828   // value.
12829   Value *Old = getValPtr();
12830   SmallVector<User *, 16> Worklist(Old->users());
12831   SmallPtrSet<User *, 8> Visited;
12832   while (!Worklist.empty()) {
12833     User *U = Worklist.pop_back_val();
12834     // Deleting the Old value will cause this to dangle. Postpone
12835     // that until everything else is done.
12836     if (U == Old)
12837       continue;
12838     if (!Visited.insert(U).second)
12839       continue;
12840     if (PHINode *PN = dyn_cast<PHINode>(U))
12841       SE->ConstantEvolutionLoopExitValue.erase(PN);
12842     SE->eraseValueFromMap(U);
12843     llvm::append_range(Worklist, U->users());
12844   }
12845   // Delete the Old value.
12846   if (PHINode *PN = dyn_cast<PHINode>(Old))
12847     SE->ConstantEvolutionLoopExitValue.erase(PN);
12848   SE->eraseValueFromMap(Old);
12849   // this now dangles!
12850 }
12851 
12852 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
12853   : CallbackVH(V), SE(se) {}
12854 
12855 //===----------------------------------------------------------------------===//
12856 //                   ScalarEvolution Class Implementation
12857 //===----------------------------------------------------------------------===//
12858 
12859 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
12860                                  AssumptionCache &AC, DominatorTree &DT,
12861                                  LoopInfo &LI)
12862     : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
12863       CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64),
12864       LoopDispositions(64), BlockDispositions(64) {
12865   // To use guards for proving predicates, we need to scan every instruction in
12866   // relevant basic blocks, and not just terminators.  Doing this is a waste of
12867   // time if the IR does not actually contain any calls to
12868   // @llvm.experimental.guard, so do a quick check and remember this beforehand.
12869   //
12870   // This pessimizes the case where a pass that preserves ScalarEvolution wants
12871   // to _add_ guards to the module when there weren't any before, and wants
12872   // ScalarEvolution to optimize based on those guards.  For now we prefer to be
12873   // efficient in lieu of being smart in that rather obscure case.
12874 
12875   auto *GuardDecl = F.getParent()->getFunction(
12876       Intrinsic::getName(Intrinsic::experimental_guard));
12877   HasGuards = GuardDecl && !GuardDecl->use_empty();
12878 }
12879 
12880 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
12881     : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT),
12882       LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
12883       ValueExprMap(std::move(Arg.ValueExprMap)),
12884       PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
12885       PendingPhiRanges(std::move(Arg.PendingPhiRanges)),
12886       PendingMerges(std::move(Arg.PendingMerges)),
12887       MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)),
12888       BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
12889       PredicatedBackedgeTakenCounts(
12890           std::move(Arg.PredicatedBackedgeTakenCounts)),
12891       BECountUsers(std::move(Arg.BECountUsers)),
12892       ConstantEvolutionLoopExitValue(
12893           std::move(Arg.ConstantEvolutionLoopExitValue)),
12894       ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
12895       ValuesAtScopesUsers(std::move(Arg.ValuesAtScopesUsers)),
12896       LoopDispositions(std::move(Arg.LoopDispositions)),
12897       LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
12898       BlockDispositions(std::move(Arg.BlockDispositions)),
12899       SCEVUsers(std::move(Arg.SCEVUsers)),
12900       UnsignedRanges(std::move(Arg.UnsignedRanges)),
12901       SignedRanges(std::move(Arg.SignedRanges)),
12902       UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
12903       UniquePreds(std::move(Arg.UniquePreds)),
12904       SCEVAllocator(std::move(Arg.SCEVAllocator)),
12905       LoopUsers(std::move(Arg.LoopUsers)),
12906       PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)),
12907       FirstUnknown(Arg.FirstUnknown) {
12908   Arg.FirstUnknown = nullptr;
12909 }
12910 
12911 ScalarEvolution::~ScalarEvolution() {
12912   // Iterate through all the SCEVUnknown instances and call their
12913   // destructors, so that they release their references to their values.
12914   for (SCEVUnknown *U = FirstUnknown; U;) {
12915     SCEVUnknown *Tmp = U;
12916     U = U->Next;
12917     Tmp->~SCEVUnknown();
12918   }
12919   FirstUnknown = nullptr;
12920 
12921   ExprValueMap.clear();
12922   ValueExprMap.clear();
12923   HasRecMap.clear();
12924   BackedgeTakenCounts.clear();
12925   PredicatedBackedgeTakenCounts.clear();
12926 
12927   assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
12928   assert(PendingPhiRanges.empty() && "getRangeRef garbage");
12929   assert(PendingMerges.empty() && "isImpliedViaMerge garbage");
12930   assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
12931   assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
12932 }
12933 
12934 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
12935   return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
12936 }
12937 
12938 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
12939                           const Loop *L) {
12940   // Print all inner loops first
12941   for (Loop *I : *L)
12942     PrintLoopInfo(OS, SE, I);
12943 
12944   OS << "Loop ";
12945   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12946   OS << ": ";
12947 
12948   SmallVector<BasicBlock *, 8> ExitingBlocks;
12949   L->getExitingBlocks(ExitingBlocks);
12950   if (ExitingBlocks.size() != 1)
12951     OS << "<multiple exits> ";
12952 
12953   if (SE->hasLoopInvariantBackedgeTakenCount(L))
12954     OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L) << "\n";
12955   else
12956     OS << "Unpredictable backedge-taken count.\n";
12957 
12958   if (ExitingBlocks.size() > 1)
12959     for (BasicBlock *ExitingBlock : ExitingBlocks) {
12960       OS << "  exit count for " << ExitingBlock->getName() << ": "
12961          << *SE->getExitCount(L, ExitingBlock) << "\n";
12962     }
12963 
12964   OS << "Loop ";
12965   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12966   OS << ": ";
12967 
12968   if (!isa<SCEVCouldNotCompute>(SE->getConstantMaxBackedgeTakenCount(L))) {
12969     OS << "max backedge-taken count is " << *SE->getConstantMaxBackedgeTakenCount(L);
12970     if (SE->isBackedgeTakenCountMaxOrZero(L))
12971       OS << ", actual taken count either this or zero.";
12972   } else {
12973     OS << "Unpredictable max backedge-taken count. ";
12974   }
12975 
12976   OS << "\n"
12977         "Loop ";
12978   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12979   OS << ": ";
12980 
12981   SmallVector<const SCEVPredicate *, 4> Preds;
12982   auto PBT = SE->getPredicatedBackedgeTakenCount(L, Preds);
12983   if (!isa<SCEVCouldNotCompute>(PBT)) {
12984     OS << "Predicated backedge-taken count is " << *PBT << "\n";
12985     OS << " Predicates:\n";
12986     for (auto *P : Preds)
12987       P->print(OS, 4);
12988   } else {
12989     OS << "Unpredictable predicated backedge-taken count. ";
12990   }
12991   OS << "\n";
12992 
12993   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
12994     OS << "Loop ";
12995     L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12996     OS << ": ";
12997     OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
12998   }
12999 }
13000 
13001 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) {
13002   switch (LD) {
13003   case ScalarEvolution::LoopVariant:
13004     return "Variant";
13005   case ScalarEvolution::LoopInvariant:
13006     return "Invariant";
13007   case ScalarEvolution::LoopComputable:
13008     return "Computable";
13009   }
13010   llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!");
13011 }
13012 
13013 void ScalarEvolution::print(raw_ostream &OS) const {
13014   // ScalarEvolution's implementation of the print method is to print
13015   // out SCEV values of all instructions that are interesting. Doing
13016   // this potentially causes it to create new SCEV objects though,
13017   // which technically conflicts with the const qualifier. This isn't
13018   // observable from outside the class though, so casting away the
13019   // const isn't dangerous.
13020   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
13021 
13022   if (ClassifyExpressions) {
13023     OS << "Classifying expressions for: ";
13024     F.printAsOperand(OS, /*PrintType=*/false);
13025     OS << "\n";
13026     for (Instruction &I : instructions(F))
13027       if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
13028         OS << I << '\n';
13029         OS << "  -->  ";
13030         const SCEV *SV = SE.getSCEV(&I);
13031         SV->print(OS);
13032         if (!isa<SCEVCouldNotCompute>(SV)) {
13033           OS << " U: ";
13034           SE.getUnsignedRange(SV).print(OS);
13035           OS << " S: ";
13036           SE.getSignedRange(SV).print(OS);
13037         }
13038 
13039         const Loop *L = LI.getLoopFor(I.getParent());
13040 
13041         const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
13042         if (AtUse != SV) {
13043           OS << "  -->  ";
13044           AtUse->print(OS);
13045           if (!isa<SCEVCouldNotCompute>(AtUse)) {
13046             OS << " U: ";
13047             SE.getUnsignedRange(AtUse).print(OS);
13048             OS << " S: ";
13049             SE.getSignedRange(AtUse).print(OS);
13050           }
13051         }
13052 
13053         if (L) {
13054           OS << "\t\t" "Exits: ";
13055           const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
13056           if (!SE.isLoopInvariant(ExitValue, L)) {
13057             OS << "<<Unknown>>";
13058           } else {
13059             OS << *ExitValue;
13060           }
13061 
13062           bool First = true;
13063           for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
13064             if (First) {
13065               OS << "\t\t" "LoopDispositions: { ";
13066               First = false;
13067             } else {
13068               OS << ", ";
13069             }
13070 
13071             Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
13072             OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter));
13073           }
13074 
13075           for (auto *InnerL : depth_first(L)) {
13076             if (InnerL == L)
13077               continue;
13078             if (First) {
13079               OS << "\t\t" "LoopDispositions: { ";
13080               First = false;
13081             } else {
13082               OS << ", ";
13083             }
13084 
13085             InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
13086             OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL));
13087           }
13088 
13089           OS << " }";
13090         }
13091 
13092         OS << "\n";
13093       }
13094   }
13095 
13096   OS << "Determining loop execution counts for: ";
13097   F.printAsOperand(OS, /*PrintType=*/false);
13098   OS << "\n";
13099   for (Loop *I : LI)
13100     PrintLoopInfo(OS, &SE, I);
13101 }
13102 
13103 ScalarEvolution::LoopDisposition
13104 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
13105   auto &Values = LoopDispositions[S];
13106   for (auto &V : Values) {
13107     if (V.getPointer() == L)
13108       return V.getInt();
13109   }
13110   Values.emplace_back(L, LoopVariant);
13111   LoopDisposition D = computeLoopDisposition(S, L);
13112   auto &Values2 = LoopDispositions[S];
13113   for (auto &V : llvm::reverse(Values2)) {
13114     if (V.getPointer() == L) {
13115       V.setInt(D);
13116       break;
13117     }
13118   }
13119   return D;
13120 }
13121 
13122 ScalarEvolution::LoopDisposition
13123 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
13124   switch (S->getSCEVType()) {
13125   case scConstant:
13126     return LoopInvariant;
13127   case scPtrToInt:
13128   case scTruncate:
13129   case scZeroExtend:
13130   case scSignExtend:
13131     return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
13132   case scAddRecExpr: {
13133     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
13134 
13135     // If L is the addrec's loop, it's computable.
13136     if (AR->getLoop() == L)
13137       return LoopComputable;
13138 
13139     // Add recurrences are never invariant in the function-body (null loop).
13140     if (!L)
13141       return LoopVariant;
13142 
13143     // Everything that is not defined at loop entry is variant.
13144     if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader()))
13145       return LoopVariant;
13146     assert(!L->contains(AR->getLoop()) && "Containing loop's header does not"
13147            " dominate the contained loop's header?");
13148 
13149     // This recurrence is invariant w.r.t. L if AR's loop contains L.
13150     if (AR->getLoop()->contains(L))
13151       return LoopInvariant;
13152 
13153     // This recurrence is variant w.r.t. L if any of its operands
13154     // are variant.
13155     for (auto *Op : AR->operands())
13156       if (!isLoopInvariant(Op, L))
13157         return LoopVariant;
13158 
13159     // Otherwise it's loop-invariant.
13160     return LoopInvariant;
13161   }
13162   case scAddExpr:
13163   case scMulExpr:
13164   case scUMaxExpr:
13165   case scSMaxExpr:
13166   case scUMinExpr:
13167   case scSMinExpr:
13168   case scSequentialUMinExpr: {
13169     bool HasVarying = false;
13170     for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) {
13171       LoopDisposition D = getLoopDisposition(Op, L);
13172       if (D == LoopVariant)
13173         return LoopVariant;
13174       if (D == LoopComputable)
13175         HasVarying = true;
13176     }
13177     return HasVarying ? LoopComputable : LoopInvariant;
13178   }
13179   case scUDivExpr: {
13180     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
13181     LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
13182     if (LD == LoopVariant)
13183       return LoopVariant;
13184     LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
13185     if (RD == LoopVariant)
13186       return LoopVariant;
13187     return (LD == LoopInvariant && RD == LoopInvariant) ?
13188            LoopInvariant : LoopComputable;
13189   }
13190   case scUnknown:
13191     // All non-instruction values are loop invariant.  All instructions are loop
13192     // invariant if they are not contained in the specified loop.
13193     // Instructions are never considered invariant in the function body
13194     // (null loop) because they are defined within the "loop".
13195     if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
13196       return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
13197     return LoopInvariant;
13198   case scCouldNotCompute:
13199     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
13200   }
13201   llvm_unreachable("Unknown SCEV kind!");
13202 }
13203 
13204 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
13205   return getLoopDisposition(S, L) == LoopInvariant;
13206 }
13207 
13208 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
13209   return getLoopDisposition(S, L) == LoopComputable;
13210 }
13211 
13212 ScalarEvolution::BlockDisposition
13213 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
13214   auto &Values = BlockDispositions[S];
13215   for (auto &V : Values) {
13216     if (V.getPointer() == BB)
13217       return V.getInt();
13218   }
13219   Values.emplace_back(BB, DoesNotDominateBlock);
13220   BlockDisposition D = computeBlockDisposition(S, BB);
13221   auto &Values2 = BlockDispositions[S];
13222   for (auto &V : llvm::reverse(Values2)) {
13223     if (V.getPointer() == BB) {
13224       V.setInt(D);
13225       break;
13226     }
13227   }
13228   return D;
13229 }
13230 
13231 ScalarEvolution::BlockDisposition
13232 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
13233   switch (S->getSCEVType()) {
13234   case scConstant:
13235     return ProperlyDominatesBlock;
13236   case scPtrToInt:
13237   case scTruncate:
13238   case scZeroExtend:
13239   case scSignExtend:
13240     return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
13241   case scAddRecExpr: {
13242     // This uses a "dominates" query instead of "properly dominates" query
13243     // to test for proper dominance too, because the instruction which
13244     // produces the addrec's value is a PHI, and a PHI effectively properly
13245     // dominates its entire containing block.
13246     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
13247     if (!DT.dominates(AR->getLoop()->getHeader(), BB))
13248       return DoesNotDominateBlock;
13249 
13250     // Fall through into SCEVNAryExpr handling.
13251     LLVM_FALLTHROUGH;
13252   }
13253   case scAddExpr:
13254   case scMulExpr:
13255   case scUMaxExpr:
13256   case scSMaxExpr:
13257   case scUMinExpr:
13258   case scSMinExpr:
13259   case scSequentialUMinExpr: {
13260     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
13261     bool Proper = true;
13262     for (const SCEV *NAryOp : NAry->operands()) {
13263       BlockDisposition D = getBlockDisposition(NAryOp, BB);
13264       if (D == DoesNotDominateBlock)
13265         return DoesNotDominateBlock;
13266       if (D == DominatesBlock)
13267         Proper = false;
13268     }
13269     return Proper ? ProperlyDominatesBlock : DominatesBlock;
13270   }
13271   case scUDivExpr: {
13272     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
13273     const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
13274     BlockDisposition LD = getBlockDisposition(LHS, BB);
13275     if (LD == DoesNotDominateBlock)
13276       return DoesNotDominateBlock;
13277     BlockDisposition RD = getBlockDisposition(RHS, BB);
13278     if (RD == DoesNotDominateBlock)
13279       return DoesNotDominateBlock;
13280     return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
13281       ProperlyDominatesBlock : DominatesBlock;
13282   }
13283   case scUnknown:
13284     if (Instruction *I =
13285           dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
13286       if (I->getParent() == BB)
13287         return DominatesBlock;
13288       if (DT.properlyDominates(I->getParent(), BB))
13289         return ProperlyDominatesBlock;
13290       return DoesNotDominateBlock;
13291     }
13292     return ProperlyDominatesBlock;
13293   case scCouldNotCompute:
13294     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
13295   }
13296   llvm_unreachable("Unknown SCEV kind!");
13297 }
13298 
13299 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
13300   return getBlockDisposition(S, BB) >= DominatesBlock;
13301 }
13302 
13303 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
13304   return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
13305 }
13306 
13307 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
13308   return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; });
13309 }
13310 
13311 void ScalarEvolution::forgetBackedgeTakenCounts(const Loop *L,
13312                                                 bool Predicated) {
13313   auto &BECounts =
13314       Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts;
13315   auto It = BECounts.find(L);
13316   if (It != BECounts.end()) {
13317     for (const ExitNotTakenInfo &ENT : It->second.ExitNotTaken) {
13318       if (!isa<SCEVConstant>(ENT.ExactNotTaken)) {
13319         auto UserIt = BECountUsers.find(ENT.ExactNotTaken);
13320         assert(UserIt != BECountUsers.end());
13321         UserIt->second.erase({L, Predicated});
13322       }
13323     }
13324     BECounts.erase(It);
13325   }
13326 }
13327 
13328 void ScalarEvolution::forgetMemoizedResults(ArrayRef<const SCEV *> SCEVs) {
13329   SmallPtrSet<const SCEV *, 8> ToForget(SCEVs.begin(), SCEVs.end());
13330   SmallVector<const SCEV *, 8> Worklist(ToForget.begin(), ToForget.end());
13331 
13332   while (!Worklist.empty()) {
13333     const SCEV *Curr = Worklist.pop_back_val();
13334     auto Users = SCEVUsers.find(Curr);
13335     if (Users != SCEVUsers.end())
13336       for (auto *User : Users->second)
13337         if (ToForget.insert(User).second)
13338           Worklist.push_back(User);
13339   }
13340 
13341   for (auto *S : ToForget)
13342     forgetMemoizedResultsImpl(S);
13343 
13344   for (auto I = PredicatedSCEVRewrites.begin();
13345        I != PredicatedSCEVRewrites.end();) {
13346     std::pair<const SCEV *, const Loop *> Entry = I->first;
13347     if (ToForget.count(Entry.first))
13348       PredicatedSCEVRewrites.erase(I++);
13349     else
13350       ++I;
13351   }
13352 }
13353 
13354 void ScalarEvolution::forgetMemoizedResultsImpl(const SCEV *S) {
13355   LoopDispositions.erase(S);
13356   BlockDispositions.erase(S);
13357   UnsignedRanges.erase(S);
13358   SignedRanges.erase(S);
13359   HasRecMap.erase(S);
13360   MinTrailingZerosCache.erase(S);
13361 
13362   auto ExprIt = ExprValueMap.find(S);
13363   if (ExprIt != ExprValueMap.end()) {
13364     for (Value *V : ExprIt->second) {
13365       auto ValueIt = ValueExprMap.find_as(V);
13366       if (ValueIt != ValueExprMap.end())
13367         ValueExprMap.erase(ValueIt);
13368     }
13369     ExprValueMap.erase(ExprIt);
13370   }
13371 
13372   auto ScopeIt = ValuesAtScopes.find(S);
13373   if (ScopeIt != ValuesAtScopes.end()) {
13374     for (const auto &Pair : ScopeIt->second)
13375       if (!isa_and_nonnull<SCEVConstant>(Pair.second))
13376         erase_value(ValuesAtScopesUsers[Pair.second],
13377                     std::make_pair(Pair.first, S));
13378     ValuesAtScopes.erase(ScopeIt);
13379   }
13380 
13381   auto ScopeUserIt = ValuesAtScopesUsers.find(S);
13382   if (ScopeUserIt != ValuesAtScopesUsers.end()) {
13383     for (const auto &Pair : ScopeUserIt->second)
13384       erase_value(ValuesAtScopes[Pair.second], std::make_pair(Pair.first, S));
13385     ValuesAtScopesUsers.erase(ScopeUserIt);
13386   }
13387 
13388   auto BEUsersIt = BECountUsers.find(S);
13389   if (BEUsersIt != BECountUsers.end()) {
13390     // Work on a copy, as forgetBackedgeTakenCounts() will modify the original.
13391     auto Copy = BEUsersIt->second;
13392     for (const auto &Pair : Copy)
13393       forgetBackedgeTakenCounts(Pair.getPointer(), Pair.getInt());
13394     BECountUsers.erase(BEUsersIt);
13395   }
13396 }
13397 
13398 void
13399 ScalarEvolution::getUsedLoops(const SCEV *S,
13400                               SmallPtrSetImpl<const Loop *> &LoopsUsed) {
13401   struct FindUsedLoops {
13402     FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed)
13403         : LoopsUsed(LoopsUsed) {}
13404     SmallPtrSetImpl<const Loop *> &LoopsUsed;
13405     bool follow(const SCEV *S) {
13406       if (auto *AR = dyn_cast<SCEVAddRecExpr>(S))
13407         LoopsUsed.insert(AR->getLoop());
13408       return true;
13409     }
13410 
13411     bool isDone() const { return false; }
13412   };
13413 
13414   FindUsedLoops F(LoopsUsed);
13415   SCEVTraversal<FindUsedLoops>(F).visitAll(S);
13416 }
13417 
13418 void ScalarEvolution::getReachableBlocks(
13419     SmallPtrSetImpl<BasicBlock *> &Reachable, Function &F) {
13420   SmallVector<BasicBlock *> Worklist;
13421   Worklist.push_back(&F.getEntryBlock());
13422   while (!Worklist.empty()) {
13423     BasicBlock *BB = Worklist.pop_back_val();
13424     if (!Reachable.insert(BB).second)
13425       continue;
13426 
13427     Value *Cond;
13428     BasicBlock *TrueBB, *FalseBB;
13429     if (match(BB->getTerminator(), m_Br(m_Value(Cond), m_BasicBlock(TrueBB),
13430                                         m_BasicBlock(FalseBB)))) {
13431       if (auto *C = dyn_cast<ConstantInt>(Cond)) {
13432         Worklist.push_back(C->isOne() ? TrueBB : FalseBB);
13433         continue;
13434       }
13435 
13436       if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
13437         const SCEV *L = getSCEV(Cmp->getOperand(0));
13438         const SCEV *R = getSCEV(Cmp->getOperand(1));
13439         if (isKnownPredicateViaConstantRanges(Cmp->getPredicate(), L, R)) {
13440           Worklist.push_back(TrueBB);
13441           continue;
13442         }
13443         if (isKnownPredicateViaConstantRanges(Cmp->getInversePredicate(), L,
13444                                               R)) {
13445           Worklist.push_back(FalseBB);
13446           continue;
13447         }
13448       }
13449     }
13450 
13451     append_range(Worklist, successors(BB));
13452   }
13453 }
13454 
13455 void ScalarEvolution::verify() const {
13456   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
13457   ScalarEvolution SE2(F, TLI, AC, DT, LI);
13458 
13459   SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end());
13460 
13461   // Map's SCEV expressions from one ScalarEvolution "universe" to another.
13462   struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> {
13463     SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {}
13464 
13465     const SCEV *visitConstant(const SCEVConstant *Constant) {
13466       return SE.getConstant(Constant->getAPInt());
13467     }
13468 
13469     const SCEV *visitUnknown(const SCEVUnknown *Expr) {
13470       return SE.getUnknown(Expr->getValue());
13471     }
13472 
13473     const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
13474       return SE.getCouldNotCompute();
13475     }
13476   };
13477 
13478   SCEVMapper SCM(SE2);
13479   SmallPtrSet<BasicBlock *, 16> ReachableBlocks;
13480   SE2.getReachableBlocks(ReachableBlocks, F);
13481 
13482   auto GetDelta = [&](const SCEV *Old, const SCEV *New) -> const SCEV * {
13483     if (containsUndefs(Old) || containsUndefs(New)) {
13484       // SCEV treats "undef" as an unknown but consistent value (i.e. it does
13485       // not propagate undef aggressively).  This means we can (and do) fail
13486       // verification in cases where a transform makes a value go from "undef"
13487       // to "undef+1" (say).  The transform is fine, since in both cases the
13488       // result is "undef", but SCEV thinks the value increased by 1.
13489       return nullptr;
13490     }
13491 
13492     // Unless VerifySCEVStrict is set, we only compare constant deltas.
13493     const SCEV *Delta = SE2.getMinusSCEV(Old, New);
13494     if (!VerifySCEVStrict && !isa<SCEVConstant>(Delta))
13495       return nullptr;
13496 
13497     return Delta;
13498   };
13499 
13500   while (!LoopStack.empty()) {
13501     auto *L = LoopStack.pop_back_val();
13502     llvm::append_range(LoopStack, *L);
13503 
13504     // Only verify BECounts in reachable loops. For an unreachable loop,
13505     // any BECount is legal.
13506     if (!ReachableBlocks.contains(L->getHeader()))
13507       continue;
13508 
13509     // Only verify cached BECounts. Computing new BECounts may change the
13510     // results of subsequent SCEV uses.
13511     auto It = BackedgeTakenCounts.find(L);
13512     if (It == BackedgeTakenCounts.end())
13513       continue;
13514 
13515     auto *CurBECount =
13516         SCM.visit(It->second.getExact(L, const_cast<ScalarEvolution *>(this)));
13517     auto *NewBECount = SE2.getBackedgeTakenCount(L);
13518 
13519     if (CurBECount == SE2.getCouldNotCompute() ||
13520         NewBECount == SE2.getCouldNotCompute()) {
13521       // NB! This situation is legal, but is very suspicious -- whatever pass
13522       // change the loop to make a trip count go from could not compute to
13523       // computable or vice-versa *should have* invalidated SCEV.  However, we
13524       // choose not to assert here (for now) since we don't want false
13525       // positives.
13526       continue;
13527     }
13528 
13529     if (SE.getTypeSizeInBits(CurBECount->getType()) >
13530         SE.getTypeSizeInBits(NewBECount->getType()))
13531       NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType());
13532     else if (SE.getTypeSizeInBits(CurBECount->getType()) <
13533              SE.getTypeSizeInBits(NewBECount->getType()))
13534       CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType());
13535 
13536     const SCEV *Delta = GetDelta(CurBECount, NewBECount);
13537     if (Delta && !Delta->isZero()) {
13538       dbgs() << "Trip Count for " << *L << " Changed!\n";
13539       dbgs() << "Old: " << *CurBECount << "\n";
13540       dbgs() << "New: " << *NewBECount << "\n";
13541       dbgs() << "Delta: " << *Delta << "\n";
13542       std::abort();
13543     }
13544   }
13545 
13546   // Collect all valid loops currently in LoopInfo.
13547   SmallPtrSet<Loop *, 32> ValidLoops;
13548   SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end());
13549   while (!Worklist.empty()) {
13550     Loop *L = Worklist.pop_back_val();
13551     if (ValidLoops.insert(L).second)
13552       Worklist.append(L->begin(), L->end());
13553   }
13554   for (auto &KV : ValueExprMap) {
13555 #ifndef NDEBUG
13556     // Check for SCEV expressions referencing invalid/deleted loops.
13557     if (auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second)) {
13558       assert(ValidLoops.contains(AR->getLoop()) &&
13559              "AddRec references invalid loop");
13560     }
13561 #endif
13562 
13563     // Check that the value is also part of the reverse map.
13564     auto It = ExprValueMap.find(KV.second);
13565     if (It == ExprValueMap.end() || !It->second.contains(KV.first)) {
13566       dbgs() << "Value " << *KV.first
13567              << " is in ValueExprMap but not in ExprValueMap\n";
13568       std::abort();
13569     }
13570 
13571     if (auto *I = dyn_cast<Instruction>(&*KV.first)) {
13572       if (!ReachableBlocks.contains(I->getParent()))
13573         continue;
13574       const SCEV *OldSCEV = SCM.visit(KV.second);
13575       const SCEV *NewSCEV = SE2.getSCEV(I);
13576       const SCEV *Delta = GetDelta(OldSCEV, NewSCEV);
13577       if (Delta && !Delta->isZero()) {
13578         dbgs() << "SCEV for value " << *I << " changed!\n"
13579                << "Old: " << *OldSCEV << "\n"
13580                << "New: " << *NewSCEV << "\n"
13581                << "Delta: " << *Delta << "\n";
13582         std::abort();
13583       }
13584     }
13585   }
13586 
13587   for (const auto &KV : ExprValueMap) {
13588     for (Value *V : KV.second) {
13589       auto It = ValueExprMap.find_as(V);
13590       if (It == ValueExprMap.end()) {
13591         dbgs() << "Value " << *V
13592                << " is in ExprValueMap but not in ValueExprMap\n";
13593         std::abort();
13594       }
13595       if (It->second != KV.first) {
13596         dbgs() << "Value " << *V << " mapped to " << *It->second
13597                << " rather than " << *KV.first << "\n";
13598         std::abort();
13599       }
13600     }
13601   }
13602 
13603   // Verify integrity of SCEV users.
13604   for (const auto &S : UniqueSCEVs) {
13605     SmallVector<const SCEV *, 4> Ops;
13606     collectUniqueOps(&S, Ops);
13607     for (const auto *Op : Ops) {
13608       // We do not store dependencies of constants.
13609       if (isa<SCEVConstant>(Op))
13610         continue;
13611       auto It = SCEVUsers.find(Op);
13612       if (It != SCEVUsers.end() && It->second.count(&S))
13613         continue;
13614       dbgs() << "Use of operand  " << *Op << " by user " << S
13615              << " is not being tracked!\n";
13616       std::abort();
13617     }
13618   }
13619 
13620   // Verify integrity of ValuesAtScopes users.
13621   for (const auto &ValueAndVec : ValuesAtScopes) {
13622     const SCEV *Value = ValueAndVec.first;
13623     for (const auto &LoopAndValueAtScope : ValueAndVec.second) {
13624       const Loop *L = LoopAndValueAtScope.first;
13625       const SCEV *ValueAtScope = LoopAndValueAtScope.second;
13626       if (!isa<SCEVConstant>(ValueAtScope)) {
13627         auto It = ValuesAtScopesUsers.find(ValueAtScope);
13628         if (It != ValuesAtScopesUsers.end() &&
13629             is_contained(It->second, std::make_pair(L, Value)))
13630           continue;
13631         dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: "
13632                << *ValueAtScope << " missing in ValuesAtScopesUsers\n";
13633         std::abort();
13634       }
13635     }
13636   }
13637 
13638   for (const auto &ValueAtScopeAndVec : ValuesAtScopesUsers) {
13639     const SCEV *ValueAtScope = ValueAtScopeAndVec.first;
13640     for (const auto &LoopAndValue : ValueAtScopeAndVec.second) {
13641       const Loop *L = LoopAndValue.first;
13642       const SCEV *Value = LoopAndValue.second;
13643       assert(!isa<SCEVConstant>(Value));
13644       auto It = ValuesAtScopes.find(Value);
13645       if (It != ValuesAtScopes.end() &&
13646           is_contained(It->second, std::make_pair(L, ValueAtScope)))
13647         continue;
13648       dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: "
13649              << *ValueAtScope << " missing in ValuesAtScopes\n";
13650       std::abort();
13651     }
13652   }
13653 
13654   // Verify integrity of BECountUsers.
13655   auto VerifyBECountUsers = [&](bool Predicated) {
13656     auto &BECounts =
13657         Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts;
13658     for (const auto &LoopAndBEInfo : BECounts) {
13659       for (const ExitNotTakenInfo &ENT : LoopAndBEInfo.second.ExitNotTaken) {
13660         if (!isa<SCEVConstant>(ENT.ExactNotTaken)) {
13661           auto UserIt = BECountUsers.find(ENT.ExactNotTaken);
13662           if (UserIt != BECountUsers.end() &&
13663               UserIt->second.contains({ LoopAndBEInfo.first, Predicated }))
13664             continue;
13665           dbgs() << "Value " << *ENT.ExactNotTaken << " for loop "
13666                  << *LoopAndBEInfo.first << " missing from BECountUsers\n";
13667           std::abort();
13668         }
13669       }
13670     }
13671   };
13672   VerifyBECountUsers(/* Predicated */ false);
13673   VerifyBECountUsers(/* Predicated */ true);
13674 }
13675 
13676 bool ScalarEvolution::invalidate(
13677     Function &F, const PreservedAnalyses &PA,
13678     FunctionAnalysisManager::Invalidator &Inv) {
13679   // Invalidate the ScalarEvolution object whenever it isn't preserved or one
13680   // of its dependencies is invalidated.
13681   auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
13682   return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
13683          Inv.invalidate<AssumptionAnalysis>(F, PA) ||
13684          Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
13685          Inv.invalidate<LoopAnalysis>(F, PA);
13686 }
13687 
13688 AnalysisKey ScalarEvolutionAnalysis::Key;
13689 
13690 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
13691                                              FunctionAnalysisManager &AM) {
13692   return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F),
13693                          AM.getResult<AssumptionAnalysis>(F),
13694                          AM.getResult<DominatorTreeAnalysis>(F),
13695                          AM.getResult<LoopAnalysis>(F));
13696 }
13697 
13698 PreservedAnalyses
13699 ScalarEvolutionVerifierPass::run(Function &F, FunctionAnalysisManager &AM) {
13700   AM.getResult<ScalarEvolutionAnalysis>(F).verify();
13701   return PreservedAnalyses::all();
13702 }
13703 
13704 PreservedAnalyses
13705 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
13706   // For compatibility with opt's -analyze feature under legacy pass manager
13707   // which was not ported to NPM. This keeps tests using
13708   // update_analyze_test_checks.py working.
13709   OS << "Printing analysis 'Scalar Evolution Analysis' for function '"
13710      << F.getName() << "':\n";
13711   AM.getResult<ScalarEvolutionAnalysis>(F).print(OS);
13712   return PreservedAnalyses::all();
13713 }
13714 
13715 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
13716                       "Scalar Evolution Analysis", false, true)
13717 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
13718 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
13719 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
13720 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
13721 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
13722                     "Scalar Evolution Analysis", false, true)
13723 
13724 char ScalarEvolutionWrapperPass::ID = 0;
13725 
13726 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
13727   initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
13728 }
13729 
13730 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
13731   SE.reset(new ScalarEvolution(
13732       F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F),
13733       getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
13734       getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
13735       getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
13736   return false;
13737 }
13738 
13739 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
13740 
13741 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
13742   SE->print(OS);
13743 }
13744 
13745 void ScalarEvolutionWrapperPass::verifyAnalysis() const {
13746   if (!VerifySCEV)
13747     return;
13748 
13749   SE->verify();
13750 }
13751 
13752 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
13753   AU.setPreservesAll();
13754   AU.addRequiredTransitive<AssumptionCacheTracker>();
13755   AU.addRequiredTransitive<LoopInfoWrapperPass>();
13756   AU.addRequiredTransitive<DominatorTreeWrapperPass>();
13757   AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
13758 }
13759 
13760 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS,
13761                                                         const SCEV *RHS) {
13762   return getComparePredicate(ICmpInst::ICMP_EQ, LHS, RHS);
13763 }
13764 
13765 const SCEVPredicate *
13766 ScalarEvolution::getComparePredicate(const ICmpInst::Predicate Pred,
13767                                      const SCEV *LHS, const SCEV *RHS) {
13768   FoldingSetNodeID ID;
13769   assert(LHS->getType() == RHS->getType() &&
13770          "Type mismatch between LHS and RHS");
13771   // Unique this node based on the arguments
13772   ID.AddInteger(SCEVPredicate::P_Compare);
13773   ID.AddInteger(Pred);
13774   ID.AddPointer(LHS);
13775   ID.AddPointer(RHS);
13776   void *IP = nullptr;
13777   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
13778     return S;
13779   SCEVComparePredicate *Eq = new (SCEVAllocator)
13780     SCEVComparePredicate(ID.Intern(SCEVAllocator), Pred, LHS, RHS);
13781   UniquePreds.InsertNode(Eq, IP);
13782   return Eq;
13783 }
13784 
13785 const SCEVPredicate *ScalarEvolution::getWrapPredicate(
13786     const SCEVAddRecExpr *AR,
13787     SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
13788   FoldingSetNodeID ID;
13789   // Unique this node based on the arguments
13790   ID.AddInteger(SCEVPredicate::P_Wrap);
13791   ID.AddPointer(AR);
13792   ID.AddInteger(AddedFlags);
13793   void *IP = nullptr;
13794   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
13795     return S;
13796   auto *OF = new (SCEVAllocator)
13797       SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
13798   UniquePreds.InsertNode(OF, IP);
13799   return OF;
13800 }
13801 
13802 namespace {
13803 
13804 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
13805 public:
13806 
13807   /// Rewrites \p S in the context of a loop L and the SCEV predication
13808   /// infrastructure.
13809   ///
13810   /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
13811   /// equivalences present in \p Pred.
13812   ///
13813   /// If \p NewPreds is non-null, rewrite is free to add further predicates to
13814   /// \p NewPreds such that the result will be an AddRecExpr.
13815   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
13816                              SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
13817                              const SCEVPredicate *Pred) {
13818     SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
13819     return Rewriter.visit(S);
13820   }
13821 
13822   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
13823     if (Pred) {
13824       if (auto *U = dyn_cast<SCEVUnionPredicate>(Pred)) {
13825         for (auto *Pred : U->getPredicates())
13826           if (const auto *IPred = dyn_cast<SCEVComparePredicate>(Pred))
13827             if (IPred->getLHS() == Expr &&
13828                 IPred->getPredicate() == ICmpInst::ICMP_EQ)
13829               return IPred->getRHS();
13830       } else if (const auto *IPred = dyn_cast<SCEVComparePredicate>(Pred)) {
13831         if (IPred->getLHS() == Expr &&
13832             IPred->getPredicate() == ICmpInst::ICMP_EQ)
13833           return IPred->getRHS();
13834       }
13835     }
13836     return convertToAddRecWithPreds(Expr);
13837   }
13838 
13839   const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
13840     const SCEV *Operand = visit(Expr->getOperand());
13841     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
13842     if (AR && AR->getLoop() == L && AR->isAffine()) {
13843       // This couldn't be folded because the operand didn't have the nuw
13844       // flag. Add the nusw flag as an assumption that we could make.
13845       const SCEV *Step = AR->getStepRecurrence(SE);
13846       Type *Ty = Expr->getType();
13847       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
13848         return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
13849                                 SE.getSignExtendExpr(Step, Ty), L,
13850                                 AR->getNoWrapFlags());
13851     }
13852     return SE.getZeroExtendExpr(Operand, Expr->getType());
13853   }
13854 
13855   const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
13856     const SCEV *Operand = visit(Expr->getOperand());
13857     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
13858     if (AR && AR->getLoop() == L && AR->isAffine()) {
13859       // This couldn't be folded because the operand didn't have the nsw
13860       // flag. Add the nssw flag as an assumption that we could make.
13861       const SCEV *Step = AR->getStepRecurrence(SE);
13862       Type *Ty = Expr->getType();
13863       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
13864         return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
13865                                 SE.getSignExtendExpr(Step, Ty), L,
13866                                 AR->getNoWrapFlags());
13867     }
13868     return SE.getSignExtendExpr(Operand, Expr->getType());
13869   }
13870 
13871 private:
13872   explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE,
13873                         SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
13874                         const SCEVPredicate *Pred)
13875       : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
13876 
13877   bool addOverflowAssumption(const SCEVPredicate *P) {
13878     if (!NewPreds) {
13879       // Check if we've already made this assumption.
13880       return Pred && Pred->implies(P);
13881     }
13882     NewPreds->insert(P);
13883     return true;
13884   }
13885 
13886   bool addOverflowAssumption(const SCEVAddRecExpr *AR,
13887                              SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
13888     auto *A = SE.getWrapPredicate(AR, AddedFlags);
13889     return addOverflowAssumption(A);
13890   }
13891 
13892   // If \p Expr represents a PHINode, we try to see if it can be represented
13893   // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible
13894   // to add this predicate as a runtime overflow check, we return the AddRec.
13895   // If \p Expr does not meet these conditions (is not a PHI node, or we
13896   // couldn't create an AddRec for it, or couldn't add the predicate), we just
13897   // return \p Expr.
13898   const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) {
13899     if (!isa<PHINode>(Expr->getValue()))
13900       return Expr;
13901     Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
13902     PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr);
13903     if (!PredicatedRewrite)
13904       return Expr;
13905     for (auto *P : PredicatedRewrite->second){
13906       // Wrap predicates from outer loops are not supported.
13907       if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) {
13908         if (L != WP->getExpr()->getLoop())
13909           return Expr;
13910       }
13911       if (!addOverflowAssumption(P))
13912         return Expr;
13913     }
13914     return PredicatedRewrite->first;
13915   }
13916 
13917   SmallPtrSetImpl<const SCEVPredicate *> *NewPreds;
13918   const SCEVPredicate *Pred;
13919   const Loop *L;
13920 };
13921 
13922 } // end anonymous namespace
13923 
13924 const SCEV *
13925 ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
13926                                        const SCEVPredicate &Preds) {
13927   return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
13928 }
13929 
13930 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates(
13931     const SCEV *S, const Loop *L,
13932     SmallPtrSetImpl<const SCEVPredicate *> &Preds) {
13933   SmallPtrSet<const SCEVPredicate *, 4> TransformPreds;
13934   S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
13935   auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
13936 
13937   if (!AddRec)
13938     return nullptr;
13939 
13940   // Since the transformation was successful, we can now transfer the SCEV
13941   // predicates.
13942   for (auto *P : TransformPreds)
13943     Preds.insert(P);
13944 
13945   return AddRec;
13946 }
13947 
13948 /// SCEV predicates
13949 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
13950                              SCEVPredicateKind Kind)
13951     : FastID(ID), Kind(Kind) {}
13952 
13953 SCEVComparePredicate::SCEVComparePredicate(const FoldingSetNodeIDRef ID,
13954                                    const ICmpInst::Predicate Pred,
13955                                    const SCEV *LHS, const SCEV *RHS)
13956   : SCEVPredicate(ID, P_Compare), Pred(Pred), LHS(LHS), RHS(RHS) {
13957   assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match");
13958   assert(LHS != RHS && "LHS and RHS are the same SCEV");
13959 }
13960 
13961 bool SCEVComparePredicate::implies(const SCEVPredicate *N) const {
13962   const auto *Op = dyn_cast<SCEVComparePredicate>(N);
13963 
13964   if (!Op)
13965     return false;
13966 
13967   if (Pred != ICmpInst::ICMP_EQ)
13968     return false;
13969 
13970   return Op->LHS == LHS && Op->RHS == RHS;
13971 }
13972 
13973 bool SCEVComparePredicate::isAlwaysTrue() const { return false; }
13974 
13975 void SCEVComparePredicate::print(raw_ostream &OS, unsigned Depth) const {
13976   if (Pred == ICmpInst::ICMP_EQ)
13977     OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
13978   else
13979     OS.indent(Depth) << "Compare predicate: " << *LHS
13980                      << " " << CmpInst::getPredicateName(Pred) << ") "
13981                      << *RHS << "\n";
13982 
13983 }
13984 
13985 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
13986                                      const SCEVAddRecExpr *AR,
13987                                      IncrementWrapFlags Flags)
13988     : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
13989 
13990 const SCEVAddRecExpr *SCEVWrapPredicate::getExpr() const { return AR; }
13991 
13992 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const {
13993   const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
13994 
13995   return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags;
13996 }
13997 
13998 bool SCEVWrapPredicate::isAlwaysTrue() const {
13999   SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
14000   IncrementWrapFlags IFlags = Flags;
14001 
14002   if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
14003     IFlags = clearFlags(IFlags, IncrementNSSW);
14004 
14005   return IFlags == IncrementAnyWrap;
14006 }
14007 
14008 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
14009   OS.indent(Depth) << *getExpr() << " Added Flags: ";
14010   if (SCEVWrapPredicate::IncrementNUSW & getFlags())
14011     OS << "<nusw>";
14012   if (SCEVWrapPredicate::IncrementNSSW & getFlags())
14013     OS << "<nssw>";
14014   OS << "\n";
14015 }
14016 
14017 SCEVWrapPredicate::IncrementWrapFlags
14018 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR,
14019                                    ScalarEvolution &SE) {
14020   IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
14021   SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
14022 
14023   // We can safely transfer the NSW flag as NSSW.
14024   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
14025     ImpliedFlags = IncrementNSSW;
14026 
14027   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
14028     // If the increment is positive, the SCEV NUW flag will also imply the
14029     // WrapPredicate NUSW flag.
14030     if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
14031       if (Step->getValue()->getValue().isNonNegative())
14032         ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
14033   }
14034 
14035   return ImpliedFlags;
14036 }
14037 
14038 /// Union predicates don't get cached so create a dummy set ID for it.
14039 SCEVUnionPredicate::SCEVUnionPredicate(ArrayRef<const SCEVPredicate *> Preds)
14040   : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {
14041   for (auto *P : Preds)
14042     add(P);
14043 }
14044 
14045 bool SCEVUnionPredicate::isAlwaysTrue() const {
14046   return all_of(Preds,
14047                 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
14048 }
14049 
14050 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
14051   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
14052     return all_of(Set->Preds,
14053                   [this](const SCEVPredicate *I) { return this->implies(I); });
14054 
14055   return any_of(Preds,
14056                 [N](const SCEVPredicate *I) { return I->implies(N); });
14057 }
14058 
14059 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
14060   for (auto Pred : Preds)
14061     Pred->print(OS, Depth);
14062 }
14063 
14064 void SCEVUnionPredicate::add(const SCEVPredicate *N) {
14065   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
14066     for (auto Pred : Set->Preds)
14067       add(Pred);
14068     return;
14069   }
14070 
14071   Preds.push_back(N);
14072 }
14073 
14074 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
14075                                                      Loop &L)
14076     : SE(SE), L(L) {
14077   SmallVector<const SCEVPredicate*, 4> Empty;
14078   Preds = std::make_unique<SCEVUnionPredicate>(Empty);
14079 }
14080 
14081 void ScalarEvolution::registerUser(const SCEV *User,
14082                                    ArrayRef<const SCEV *> Ops) {
14083   for (auto *Op : Ops)
14084     // We do not expect that forgetting cached data for SCEVConstants will ever
14085     // open any prospects for sharpening or introduce any correctness issues,
14086     // so we don't bother storing their dependencies.
14087     if (!isa<SCEVConstant>(Op))
14088       SCEVUsers[Op].insert(User);
14089 }
14090 
14091 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
14092   const SCEV *Expr = SE.getSCEV(V);
14093   RewriteEntry &Entry = RewriteMap[Expr];
14094 
14095   // If we already have an entry and the version matches, return it.
14096   if (Entry.second && Generation == Entry.first)
14097     return Entry.second;
14098 
14099   // We found an entry but it's stale. Rewrite the stale entry
14100   // according to the current predicate.
14101   if (Entry.second)
14102     Expr = Entry.second;
14103 
14104   const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, *Preds);
14105   Entry = {Generation, NewSCEV};
14106 
14107   return NewSCEV;
14108 }
14109 
14110 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() {
14111   if (!BackedgeCount) {
14112     SmallVector<const SCEVPredicate *, 4> Preds;
14113     BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, Preds);
14114     for (auto *P : Preds)
14115       addPredicate(*P);
14116   }
14117   return BackedgeCount;
14118 }
14119 
14120 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
14121   if (Preds->implies(&Pred))
14122     return;
14123 
14124   auto &OldPreds = Preds->getPredicates();
14125   SmallVector<const SCEVPredicate*, 4> NewPreds(OldPreds.begin(), OldPreds.end());
14126   NewPreds.push_back(&Pred);
14127   Preds = std::make_unique<SCEVUnionPredicate>(NewPreds);
14128   updateGeneration();
14129 }
14130 
14131 const SCEVPredicate &PredicatedScalarEvolution::getPredicate() const {
14132   return *Preds;
14133 }
14134 
14135 void PredicatedScalarEvolution::updateGeneration() {
14136   // If the generation number wrapped recompute everything.
14137   if (++Generation == 0) {
14138     for (auto &II : RewriteMap) {
14139       const SCEV *Rewritten = II.second.second;
14140       II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, *Preds)};
14141     }
14142   }
14143 }
14144 
14145 void PredicatedScalarEvolution::setNoOverflow(
14146     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
14147   const SCEV *Expr = getSCEV(V);
14148   const auto *AR = cast<SCEVAddRecExpr>(Expr);
14149 
14150   auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE);
14151 
14152   // Clear the statically implied flags.
14153   Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags);
14154   addPredicate(*SE.getWrapPredicate(AR, Flags));
14155 
14156   auto II = FlagsMap.insert({V, Flags});
14157   if (!II.second)
14158     II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second);
14159 }
14160 
14161 bool PredicatedScalarEvolution::hasNoOverflow(
14162     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
14163   const SCEV *Expr = getSCEV(V);
14164   const auto *AR = cast<SCEVAddRecExpr>(Expr);
14165 
14166   Flags = SCEVWrapPredicate::clearFlags(
14167       Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
14168 
14169   auto II = FlagsMap.find(V);
14170 
14171   if (II != FlagsMap.end())
14172     Flags = SCEVWrapPredicate::clearFlags(Flags, II->second);
14173 
14174   return Flags == SCEVWrapPredicate::IncrementAnyWrap;
14175 }
14176 
14177 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) {
14178   const SCEV *Expr = this->getSCEV(V);
14179   SmallPtrSet<const SCEVPredicate *, 4> NewPreds;
14180   auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
14181 
14182   if (!New)
14183     return nullptr;
14184 
14185   for (auto *P : NewPreds)
14186     addPredicate(*P);
14187 
14188   RewriteMap[SE.getSCEV(V)] = {Generation, New};
14189   return New;
14190 }
14191 
14192 PredicatedScalarEvolution::PredicatedScalarEvolution(
14193     const PredicatedScalarEvolution &Init)
14194   : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L),
14195     Preds(std::make_unique<SCEVUnionPredicate>(Init.Preds->getPredicates())),
14196     Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
14197   for (auto I : Init.FlagsMap)
14198     FlagsMap.insert(I);
14199 }
14200 
14201 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const {
14202   // For each block.
14203   for (auto *BB : L.getBlocks())
14204     for (auto &I : *BB) {
14205       if (!SE.isSCEVable(I.getType()))
14206         continue;
14207 
14208       auto *Expr = SE.getSCEV(&I);
14209       auto II = RewriteMap.find(Expr);
14210 
14211       if (II == RewriteMap.end())
14212         continue;
14213 
14214       // Don't print things that are not interesting.
14215       if (II->second.second == Expr)
14216         continue;
14217 
14218       OS.indent(Depth) << "[PSE]" << I << ":\n";
14219       OS.indent(Depth + 2) << *Expr << "\n";
14220       OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
14221     }
14222 }
14223 
14224 // Match the mathematical pattern A - (A / B) * B, where A and B can be
14225 // arbitrary expressions. Also match zext (trunc A to iB) to iY, which is used
14226 // for URem with constant power-of-2 second operands.
14227 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is
14228 // 4, A / B becomes X / 8).
14229 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS,
14230                                 const SCEV *&RHS) {
14231   // Try to match 'zext (trunc A to iB) to iY', which is used
14232   // for URem with constant power-of-2 second operands. Make sure the size of
14233   // the operand A matches the size of the whole expressions.
14234   if (const auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(Expr))
14235     if (const auto *Trunc = dyn_cast<SCEVTruncateExpr>(ZExt->getOperand(0))) {
14236       LHS = Trunc->getOperand();
14237       // Bail out if the type of the LHS is larger than the type of the
14238       // expression for now.
14239       if (getTypeSizeInBits(LHS->getType()) >
14240           getTypeSizeInBits(Expr->getType()))
14241         return false;
14242       if (LHS->getType() != Expr->getType())
14243         LHS = getZeroExtendExpr(LHS, Expr->getType());
14244       RHS = getConstant(APInt(getTypeSizeInBits(Expr->getType()), 1)
14245                         << getTypeSizeInBits(Trunc->getType()));
14246       return true;
14247     }
14248   const auto *Add = dyn_cast<SCEVAddExpr>(Expr);
14249   if (Add == nullptr || Add->getNumOperands() != 2)
14250     return false;
14251 
14252   const SCEV *A = Add->getOperand(1);
14253   const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0));
14254 
14255   if (Mul == nullptr)
14256     return false;
14257 
14258   const auto MatchURemWithDivisor = [&](const SCEV *B) {
14259     // (SomeExpr + (-(SomeExpr / B) * B)).
14260     if (Expr == getURemExpr(A, B)) {
14261       LHS = A;
14262       RHS = B;
14263       return true;
14264     }
14265     return false;
14266   };
14267 
14268   // (SomeExpr + (-1 * (SomeExpr / B) * B)).
14269   if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0)))
14270     return MatchURemWithDivisor(Mul->getOperand(1)) ||
14271            MatchURemWithDivisor(Mul->getOperand(2));
14272 
14273   // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)).
14274   if (Mul->getNumOperands() == 2)
14275     return MatchURemWithDivisor(Mul->getOperand(1)) ||
14276            MatchURemWithDivisor(Mul->getOperand(0)) ||
14277            MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) ||
14278            MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0)));
14279   return false;
14280 }
14281 
14282 const SCEV *
14283 ScalarEvolution::computeSymbolicMaxBackedgeTakenCount(const Loop *L) {
14284   SmallVector<BasicBlock*, 16> ExitingBlocks;
14285   L->getExitingBlocks(ExitingBlocks);
14286 
14287   // Form an expression for the maximum exit count possible for this loop. We
14288   // merge the max and exact information to approximate a version of
14289   // getConstantMaxBackedgeTakenCount which isn't restricted to just constants.
14290   SmallVector<const SCEV*, 4> ExitCounts;
14291   for (BasicBlock *ExitingBB : ExitingBlocks) {
14292     const SCEV *ExitCount = getExitCount(L, ExitingBB);
14293     if (isa<SCEVCouldNotCompute>(ExitCount))
14294       ExitCount = getExitCount(L, ExitingBB,
14295                                   ScalarEvolution::ConstantMaximum);
14296     if (!isa<SCEVCouldNotCompute>(ExitCount)) {
14297       assert(DT.dominates(ExitingBB, L->getLoopLatch()) &&
14298              "We should only have known counts for exiting blocks that "
14299              "dominate latch!");
14300       ExitCounts.push_back(ExitCount);
14301     }
14302   }
14303   if (ExitCounts.empty())
14304     return getCouldNotCompute();
14305   return getUMinFromMismatchedTypes(ExitCounts);
14306 }
14307 
14308 /// A rewriter to replace SCEV expressions in Map with the corresponding entry
14309 /// in the map. It skips AddRecExpr because we cannot guarantee that the
14310 /// replacement is loop invariant in the loop of the AddRec.
14311 ///
14312 /// At the moment only rewriting SCEVUnknown and SCEVZeroExtendExpr is
14313 /// supported.
14314 class SCEVLoopGuardRewriter : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> {
14315   const DenseMap<const SCEV *, const SCEV *> &Map;
14316 
14317 public:
14318   SCEVLoopGuardRewriter(ScalarEvolution &SE,
14319                         DenseMap<const SCEV *, const SCEV *> &M)
14320       : SCEVRewriteVisitor(SE), Map(M) {}
14321 
14322   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; }
14323 
14324   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
14325     auto I = Map.find(Expr);
14326     if (I == Map.end())
14327       return Expr;
14328     return I->second;
14329   }
14330 
14331   const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
14332     auto I = Map.find(Expr);
14333     if (I == Map.end())
14334       return SCEVRewriteVisitor<SCEVLoopGuardRewriter>::visitZeroExtendExpr(
14335           Expr);
14336     return I->second;
14337   }
14338 };
14339 
14340 const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) {
14341   SmallVector<const SCEV *> ExprsToRewrite;
14342   auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS,
14343                               const SCEV *RHS,
14344                               DenseMap<const SCEV *, const SCEV *>
14345                                   &RewriteMap) {
14346     // WARNING: It is generally unsound to apply any wrap flags to the proposed
14347     // replacement SCEV which isn't directly implied by the structure of that
14348     // SCEV.  In particular, using contextual facts to imply flags is *NOT*
14349     // legal.  See the scoping rules for flags in the header to understand why.
14350 
14351     // If LHS is a constant, apply information to the other expression.
14352     if (isa<SCEVConstant>(LHS)) {
14353       std::swap(LHS, RHS);
14354       Predicate = CmpInst::getSwappedPredicate(Predicate);
14355     }
14356 
14357     // Check for a condition of the form (-C1 + X < C2).  InstCombine will
14358     // create this form when combining two checks of the form (X u< C2 + C1) and
14359     // (X >=u C1).
14360     auto MatchRangeCheckIdiom = [this, Predicate, LHS, RHS, &RewriteMap,
14361                                  &ExprsToRewrite]() {
14362       auto *AddExpr = dyn_cast<SCEVAddExpr>(LHS);
14363       if (!AddExpr || AddExpr->getNumOperands() != 2)
14364         return false;
14365 
14366       auto *C1 = dyn_cast<SCEVConstant>(AddExpr->getOperand(0));
14367       auto *LHSUnknown = dyn_cast<SCEVUnknown>(AddExpr->getOperand(1));
14368       auto *C2 = dyn_cast<SCEVConstant>(RHS);
14369       if (!C1 || !C2 || !LHSUnknown)
14370         return false;
14371 
14372       auto ExactRegion =
14373           ConstantRange::makeExactICmpRegion(Predicate, C2->getAPInt())
14374               .sub(C1->getAPInt());
14375 
14376       // Bail out, unless we have a non-wrapping, monotonic range.
14377       if (ExactRegion.isWrappedSet() || ExactRegion.isFullSet())
14378         return false;
14379       auto I = RewriteMap.find(LHSUnknown);
14380       const SCEV *RewrittenLHS = I != RewriteMap.end() ? I->second : LHSUnknown;
14381       RewriteMap[LHSUnknown] = getUMaxExpr(
14382           getConstant(ExactRegion.getUnsignedMin()),
14383           getUMinExpr(RewrittenLHS, getConstant(ExactRegion.getUnsignedMax())));
14384       ExprsToRewrite.push_back(LHSUnknown);
14385       return true;
14386     };
14387     if (MatchRangeCheckIdiom())
14388       return;
14389 
14390     // If we have LHS == 0, check if LHS is computing a property of some unknown
14391     // SCEV %v which we can rewrite %v to express explicitly.
14392     const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS);
14393     if (Predicate == CmpInst::ICMP_EQ && RHSC &&
14394         RHSC->getValue()->isNullValue()) {
14395       // If LHS is A % B, i.e. A % B == 0, rewrite A to (A /u B) * B to
14396       // explicitly express that.
14397       const SCEV *URemLHS = nullptr;
14398       const SCEV *URemRHS = nullptr;
14399       if (matchURem(LHS, URemLHS, URemRHS)) {
14400         if (const SCEVUnknown *LHSUnknown = dyn_cast<SCEVUnknown>(URemLHS)) {
14401           auto Multiple = getMulExpr(getUDivExpr(URemLHS, URemRHS), URemRHS);
14402           RewriteMap[LHSUnknown] = Multiple;
14403           ExprsToRewrite.push_back(LHSUnknown);
14404           return;
14405         }
14406       }
14407     }
14408 
14409     // Do not apply information for constants or if RHS contains an AddRec.
14410     if (isa<SCEVConstant>(LHS) || containsAddRecurrence(RHS))
14411       return;
14412 
14413     // If RHS is SCEVUnknown, make sure the information is applied to it.
14414     if (!isa<SCEVUnknown>(LHS) && isa<SCEVUnknown>(RHS)) {
14415       std::swap(LHS, RHS);
14416       Predicate = CmpInst::getSwappedPredicate(Predicate);
14417     }
14418 
14419     // Limit to expressions that can be rewritten.
14420     if (!isa<SCEVUnknown>(LHS) && !isa<SCEVZeroExtendExpr>(LHS))
14421       return;
14422 
14423     // Check whether LHS has already been rewritten. In that case we want to
14424     // chain further rewrites onto the already rewritten value.
14425     auto I = RewriteMap.find(LHS);
14426     const SCEV *RewrittenLHS = I != RewriteMap.end() ? I->second : LHS;
14427 
14428     const SCEV *RewrittenRHS = nullptr;
14429     switch (Predicate) {
14430     case CmpInst::ICMP_ULT:
14431       RewrittenRHS =
14432           getUMinExpr(RewrittenLHS, getMinusSCEV(RHS, getOne(RHS->getType())));
14433       break;
14434     case CmpInst::ICMP_SLT:
14435       RewrittenRHS =
14436           getSMinExpr(RewrittenLHS, getMinusSCEV(RHS, getOne(RHS->getType())));
14437       break;
14438     case CmpInst::ICMP_ULE:
14439       RewrittenRHS = getUMinExpr(RewrittenLHS, RHS);
14440       break;
14441     case CmpInst::ICMP_SLE:
14442       RewrittenRHS = getSMinExpr(RewrittenLHS, RHS);
14443       break;
14444     case CmpInst::ICMP_UGT:
14445       RewrittenRHS =
14446           getUMaxExpr(RewrittenLHS, getAddExpr(RHS, getOne(RHS->getType())));
14447       break;
14448     case CmpInst::ICMP_SGT:
14449       RewrittenRHS =
14450           getSMaxExpr(RewrittenLHS, getAddExpr(RHS, getOne(RHS->getType())));
14451       break;
14452     case CmpInst::ICMP_UGE:
14453       RewrittenRHS = getUMaxExpr(RewrittenLHS, RHS);
14454       break;
14455     case CmpInst::ICMP_SGE:
14456       RewrittenRHS = getSMaxExpr(RewrittenLHS, RHS);
14457       break;
14458     case CmpInst::ICMP_EQ:
14459       if (isa<SCEVConstant>(RHS))
14460         RewrittenRHS = RHS;
14461       break;
14462     case CmpInst::ICMP_NE:
14463       if (isa<SCEVConstant>(RHS) &&
14464           cast<SCEVConstant>(RHS)->getValue()->isNullValue())
14465         RewrittenRHS = getUMaxExpr(RewrittenLHS, getOne(RHS->getType()));
14466       break;
14467     default:
14468       break;
14469     }
14470 
14471     if (RewrittenRHS) {
14472       RewriteMap[LHS] = RewrittenRHS;
14473       if (LHS == RewrittenLHS)
14474         ExprsToRewrite.push_back(LHS);
14475     }
14476   };
14477   // First, collect conditions from dominating branches. Starting at the loop
14478   // predecessor, climb up the predecessor chain, as long as there are
14479   // predecessors that can be found that have unique successors leading to the
14480   // original header.
14481   // TODO: share this logic with isLoopEntryGuardedByCond.
14482   SmallVector<std::pair<Value *, bool>> Terms;
14483   for (std::pair<const BasicBlock *, const BasicBlock *> Pair(
14484            L->getLoopPredecessor(), L->getHeader());
14485        Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
14486 
14487     const BranchInst *LoopEntryPredicate =
14488         dyn_cast<BranchInst>(Pair.first->getTerminator());
14489     if (!LoopEntryPredicate || LoopEntryPredicate->isUnconditional())
14490       continue;
14491 
14492     Terms.emplace_back(LoopEntryPredicate->getCondition(),
14493                        LoopEntryPredicate->getSuccessor(0) == Pair.second);
14494   }
14495 
14496   // Now apply the information from the collected conditions to RewriteMap.
14497   // Conditions are processed in reverse order, so the earliest conditions is
14498   // processed first. This ensures the SCEVs with the shortest dependency chains
14499   // are constructed first.
14500   DenseMap<const SCEV *, const SCEV *> RewriteMap;
14501   for (auto &E : reverse(Terms)) {
14502     bool EnterIfTrue = E.second;
14503     SmallVector<Value *, 8> Worklist;
14504     SmallPtrSet<Value *, 8> Visited;
14505     Worklist.push_back(E.first);
14506     while (!Worklist.empty()) {
14507       Value *Cond = Worklist.pop_back_val();
14508       if (!Visited.insert(Cond).second)
14509         continue;
14510 
14511       if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
14512         auto Predicate =
14513             EnterIfTrue ? Cmp->getPredicate() : Cmp->getInversePredicate();
14514         CollectCondition(Predicate, getSCEV(Cmp->getOperand(0)),
14515                          getSCEV(Cmp->getOperand(1)), RewriteMap);
14516         continue;
14517       }
14518 
14519       Value *L, *R;
14520       if (EnterIfTrue ? match(Cond, m_LogicalAnd(m_Value(L), m_Value(R)))
14521                       : match(Cond, m_LogicalOr(m_Value(L), m_Value(R)))) {
14522         Worklist.push_back(L);
14523         Worklist.push_back(R);
14524       }
14525     }
14526   }
14527 
14528   // Also collect information from assumptions dominating the loop.
14529   for (auto &AssumeVH : AC.assumptions()) {
14530     if (!AssumeVH)
14531       continue;
14532     auto *AssumeI = cast<CallInst>(AssumeVH);
14533     auto *Cmp = dyn_cast<ICmpInst>(AssumeI->getOperand(0));
14534     if (!Cmp || !DT.dominates(AssumeI, L->getHeader()))
14535       continue;
14536     CollectCondition(Cmp->getPredicate(), getSCEV(Cmp->getOperand(0)),
14537                      getSCEV(Cmp->getOperand(1)), RewriteMap);
14538   }
14539 
14540   if (RewriteMap.empty())
14541     return Expr;
14542 
14543   // Now that all rewrite information is collect, rewrite the collected
14544   // expressions with the information in the map. This applies information to
14545   // sub-expressions.
14546   if (ExprsToRewrite.size() > 1) {
14547     for (const SCEV *Expr : ExprsToRewrite) {
14548       const SCEV *RewriteTo = RewriteMap[Expr];
14549       RewriteMap.erase(Expr);
14550       SCEVLoopGuardRewriter Rewriter(*this, RewriteMap);
14551       RewriteMap.insert({Expr, Rewriter.visit(RewriteTo)});
14552     }
14553   }
14554 
14555   SCEVLoopGuardRewriter Rewriter(*this, RewriteMap);
14556   return Rewriter.visit(Expr);
14557 }
14558